diff --git a/internal/cli/atlas/atlas.go b/internal/cli/atlas/atlas.go deleted file mode 100644 index b4eab7342e..0000000000 --- a/internal/cli/atlas/atlas.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package atlas - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/accesslists" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/accesslogs" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/cloudproviders" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/clusters" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/customdbroles" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/customdns" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/datalake" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/dbusers" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/integrations" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/livemigrations" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/logs" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/maintenance" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/metrics" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/networking" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/privateendpoints" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/processes" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/security" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/alerts" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/events" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/performanceadvisor" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/serverless" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/validate" - "github.com/spf13/cobra" -) - -const ( - Use = "atlas" - deprecatedMessage = "There's a new, dedicated Atlas CLI available for Atlas users. Install the Atlas CLI to enjoy the same capabilities and keep getting new features: https://dochub.mongodb.org/core/migrate-to-atlas-cli. Atlas commands for MongoCLI are now deprecated, but you can keep using them for 12 months (until April 30, 2023).\n\n" -) - -func Builder() *cobra.Command { - opts := &cli.RefresherOpts{} - cmd := &cobra.Command{ - Use: Use, - Short: "MongoDB Atlas operations.", - Deprecated: deprecatedMessage, - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - if err := opts.InitFlow(config.Default())(); err != nil { - return err - } - if err := opts.RefreshAccessToken(cmd.Context()); err != nil { - return err - } - if config.Service() == "" { - config.SetService(config.CloudService) - } - return validate.Credentials() - }, - Annotations: map[string]string{ - "toc": "true", - }, - } - cmd.AddCommand( - clusters.MongoCLIBuilder(), - dbusers.Builder(), - customdbroles.Builder(), - accesslists.Builder(), - datalake.Builder(), - alerts.Builder(), - backup.Builder(), - events.Builder(), - metrics.Builder(), - performanceadvisor.Builder(), - logs.MongoCLIBuilder(), - processes.Builder(), - privateendpoints.Builder(), - networking.Builder(), - security.Builder(), - integrations.Builder(), - maintenance.Builder(), - customdns.Builder(), - cloudproviders.Builder(), - serverless.Builder(), - livemigrations.Builder(), - accesslogs.Builder(), - ) - return cmd -} diff --git a/internal/cli/atlas/atlas_test.go b/internal/cli/atlas/atlas_test.go deleted file mode 100644 index b45b6c9a45..0000000000 --- a/internal/cli/atlas/atlas_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package atlas - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 22, - []string{}, - ) -} diff --git a/internal/cli/atlas/backup/compliancepolicy/policies/scheduled/update.go b/internal/cli/atlas/backup/compliancepolicy/policies/scheduled/update.go deleted file mode 100644 index 2c04848966..0000000000 --- a/internal/cli/atlas/backup/compliancepolicy/policies/scheduled/update.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package scheduled - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - store "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -type UpdateOpts struct { - cli.GlobalOpts - cli.WatchOpts - store store.CompliancePolicyScheduledPolicyUpdater - policy *atlasv2.DataProtectionSettings20231001 - scheduledPolicyID string - frequencyType string - frequencyInterval int - retentionUnit string - retentionValue int -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() (err error) { - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return - } -} - -func (opts *UpdateOpts) watcher() (any, bool, error) { - res, err := opts.store.DescribeCompliancePolicy(opts.ConfigProjectID()) - if err != nil { - return nil, false, err - } - opts.policy = res - return nil, res.GetState() == active, nil -} - -func (opts *UpdateOpts) Run() (err error) { - policyItem := &atlasv2.BackupComplianceScheduledPolicyItem{ - FrequencyType: opts.frequencyType, - FrequencyInterval: opts.frequencyInterval, - RetentionUnit: opts.retentionUnit, - RetentionValue: opts.retentionValue, - Id: &opts.scheduledPolicyID, - } - - if opts.policy, err = opts.store.UpdateScheduledPolicy(opts.ProjectID, policyItem); err != nil { - return err - } - - if opts.EnableWatch { - if _, errW := opts.Watch(opts.watcher); errW != nil { - return fmt.Errorf("received an error while watching for completion: %w", errW) - } - opts.Template = updateWatchTemplate - } - return opts.Print(opts.policy) -} - -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - cmd := &cobra.Command{ - Use: "update", - Short: "Update a scheduled policy item for the backup compliance policy for your project.", - Example: ` # Update a backup compliance schedule policy with a weekly frequency, where the snapshot occurs on Monday and has a retention of two months: - atlas backups compliancepolicy policies scheduled update --scheduledPolicyId 6567f8ad00e6a55f9e448087 --frequencyType weekly --frequencyInterval 1 --retentionUnit months --retentionValue 2`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.scheduledPolicyID, flag.ScheduledPolicyID, "", usage.ScheduledPolicyID) - cmd.Flags().StringVar(&opts.frequencyType, flag.FrequencyType, "", usage.FrequencyType) - cmd.Flags().IntVar(&opts.frequencyInterval, flag.FrequencyInterval, 0, usage.FrequencyInterval) - cmd.Flags().StringVar(&opts.retentionUnit, flag.RetentionUnit, "", usage.RetentionUnit) - cmd.Flags().IntVar(&opts.retentionValue, flag.RetentionValue, 0, usage.RetentionValue) - _ = cmd.MarkFlagRequired(flag.ScheduledPolicyID) - _ = cmd.MarkFlagRequired(flag.FrequencyType) - _ = cmd.MarkFlagRequired(flag.FrequencyInterval) - _ = cmd.MarkFlagRequired(flag.RetentionUnit) - _ = cmd.MarkFlagRequired(flag.RetentionValue) - - cmd.Flags().BoolVarP(&opts.EnableWatch, flag.EnableWatch, flag.EnableWatchShort, false, usage.EnableWatchDefault) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/atlas/backup/compliancepolicy/policies/scheduled/update_test.go b/internal/cli/atlas/backup/compliancepolicy/policies/scheduled/update_test.go deleted file mode 100644 index a0d0efb6ae..0000000000 --- a/internal/cli/atlas/backup/compliancepolicy/policies/scheduled/update_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package scheduled - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks/atlas" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestUpdateOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := atlas.NewMockCompliancePolicyScheduledPolicyUpdater(ctrl) - - opts := &UpdateOpts{ - store: mockStore, - scheduledPolicyID: "123", - frequencyType: "weekly", - frequencyInterval: 1, - retentionUnit: "days", - retentionValue: 30, - } - - policyItem := &atlasv2.BackupComplianceScheduledPolicyItem{ - Id: &opts.scheduledPolicyID, - FrequencyType: opts.frequencyType, - FrequencyInterval: opts.frequencyInterval, - RetentionUnit: opts.retentionUnit, - RetentionValue: opts.retentionValue, - } - - expected := &atlasv2.DataProtectionSettings20231001{} - - mockStore. - EXPECT(). - UpdateScheduledPolicy("", policyItem).Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.ScheduledPolicyID, flag.FrequencyType, flag.FrequencyInterval, flag.RetentionUnit, flag.RetentionValue, flag.EnableWatch, flag.ProjectID, flag.Output}, - ) -} - -func TestUpdateTemplate(t *testing.T) { - test.VerifyOutputTemplate(t, updateTemplate, &atlasv2.DataProtectionSettings20231001{}) -} diff --git a/internal/cli/cloudmanager/cloud_manager.go b/internal/cli/cloudmanager/cloud_manager.go deleted file mode 100644 index 3631cda11f..0000000000 --- a/internal/cli/cloudmanager/cloud_manager.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cloudmanager - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/alerts" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/events" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/performanceadvisor" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/agents" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/automation" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/clusters" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/dbusers" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/featurepolicies" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/livemigrations" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/logs" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/maintenance" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/metrics" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/monitoring" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/processes" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/security" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/servers" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/log" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/mongodb/mongodb-atlas-cli/internal/validate" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - opts := &cli.RefresherOpts{} - var debugLevel bool - cmd := &cobra.Command{ - Use: "cloud-manager", - Aliases: []string{"cm"}, - Short: "MongoDB Cloud Manager operations.", - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - log.SetWriter(cmd.ErrOrStderr()) - if debugLevel { - log.SetLevel(log.DebugLevel) - } - if err := opts.InitFlow(config.Default())(); err != nil { - return err - } - if err := opts.RefreshAccessToken(cmd.Context()); err != nil { - return err - } - config.SetService(config.CloudManagerService) - return validate.Credentials() - }, - Annotations: map[string]string{ - "toc": "true", - }, - } - - cmd.AddCommand( - clusters.Builder(), - alerts.Builder(), - backup.Builder(), - servers.Builder(), - automation.Builder(), - security.Builder(), - dbusers.Builder(), - events.Builder(), - monitoring.Builder(), - processes.Builder(), - metrics.Builder(), - logs.Builder(), - agents.Builder(), - maintenance.Builder(), - performanceadvisor.Builder(), - featurepolicies.Builder(), - livemigrations.Builder()) - - cmd.PersistentFlags().BoolVarP(&debugLevel, flag.Debug, flag.DebugShort, false, usage.Debug) - _ = cmd.PersistentFlags().MarkHidden(flag.Debug) - - return cmd -} diff --git a/internal/cli/cloudmanager/cloud_manager_test.go b/internal/cli/cloudmanager/cloud_manager_test.go deleted file mode 100644 index 7fb3282cf0..0000000000 --- a/internal/cli/cloudmanager/cloud_manager_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package cloudmanager - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 17, - []string{}, - ) -} diff --git a/internal/cli/config/config.go b/internal/cli/config/config.go deleted file mode 100644 index 8f1d6a16a5..0000000000 --- a/internal/cli/config/config.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/prompt" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type opts struct { - cli.DigestConfigOpts -} - -func (opts *opts) Run(ctx context.Context) error { - _, _ = fmt.Fprintf(opts.OutWriter, `You are configuring a profile for %s. - -All values are optional and you can use environment variables (MCLI_*) instead. - -Enter [?] on any option to get help. - -`, config.ToolName) - - q := prompt.AccessQuestions(opts.IsOpsManager()) - if err := telemetry.TrackAsk(q, opts); err != nil { - return err - } - opts.SetUpDigestAccess() - - if err := opts.InitStore(ctx); err != nil { - return err - } - - if config.IsAccessSet() { - if err := opts.AskOrg(); err != nil { - return err - } - if err := opts.AskProject(); err != nil { - return err - } - } else { - q = prompt.TenantQuestions() - if err := telemetry.TrackAsk(q, opts); err != nil { - return err - } - } - opts.SetUpProject() - opts.SetUpOrg() - - if err := telemetry.TrackAsk(opts.DefaultQuestions(), opts); err != nil { - return err - } - opts.SetUpOutput() - - if err := config.Save(); err != nil { - return err - } - - if config.Name() != config.DefaultProfile { - _, _ = fmt.Fprintf(opts.OutWriter, "\nYour profile is now configured.\n") - _, _ = fmt.Fprintf(opts.OutWriter, "To use this profile, you must set the flag [-%s %s] for every command.\n", flag.ProfileShort, config.Name()) - _, _ = fmt.Fprintf(opts.OutWriter, "You can use [%s config set] to change these settings at a later time.\n", config.ToolName) - } - - return nil -} - -func (opts *opts) validateService() error { - if opts.Service == config.CloudService { - return nil - } - - if opts.Service == "gov" { - opts.Service = config.CloudGovService - return nil - } - - if opts.Service == "cloudmanager" || opts.Service == "cm" { - opts.Service = config.CloudManagerService - return nil - } - - if opts.Service == "opsmanager" || opts.Service == "om" { - opts.Service = config.OpsManagerService - return nil - } - - if opts.Service != config.OpsManagerService && opts.Service != config.CloudManagerService && opts.Service != config.CloudGovService { - return fmt.Errorf("the '%s' service is not supported. Please run 'mongocli config --help' to see the list of available services", opts.Service) - } - - return nil -} - -func Builder() *cobra.Command { - opt := &opts{} - cmd := &cobra.Command{ - Use: "config", - Short: "Configure and manage your user profiles.", - Long: `You can define the settings that the MongoDB CLI uses to interact with MongoDB services. -All settings are optional. You can specify settings individually by running: -$ mongocli config set --help -You can also use environment variables (MCLI_*) when running the tool. -To find out more, see the documentation: https://docs.mongodb.com/mongocli/stable/configure/environment-variables/.`, - Example: ` - # Configure a profile to interact with Atlas: - mongocli config - # Configure a profile to interact with Atlas for Government: - mongocli config --service cloudgov - - # Configure a profile to interact with Cloud Manager: - mongocli config --service cloud-manager - # Configure a profile to interact with Ops Manager: - mongocli config --service ops-manager -`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opt.OutWriter = cmd.OutOrStdout() - return opt.validateService() - }, - - RunE: func(cmd *cobra.Command, _ []string) error { - return opt.Run(cmd.Context()) - }, - Annotations: map[string]string{ - "toc": "true", - }, - Args: require.NoArgs, - } - cmd.Flags().StringVar(&opt.Service, flag.Service, config.CloudService, usage.Service) - cmd.AddCommand( - SetBuilder(), - ListBuilder(), - DescribeBuilder(), - RenameBuilder(), - DeleteBuilder(), - EditBuilder(), - ) - - return cmd -} diff --git a/internal/cli/config/config_test.go b/internal/cli/config/config_test.go deleted file mode 100644 index 640ccf4cf0..0000000000 --- a/internal/cli/config/config_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2022 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package config - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 6, - []string{flag.Service}, - ) -} diff --git a/internal/cli/iam/globalaccesslists/create.go b/internal/cli/iam/globalaccesslists/create.go deleted file mode 100644 index c85672cc0a..0000000000 --- a/internal/cli/iam/globalaccesslists/create.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalaccesslists - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -const createTemplate = "Global access list entry '{{.ID}}' created.\n" - -type CreateOpts struct { - cli.OutputOpts - description string - cidr string - store store.GlobalAPIKeyWhitelistCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) newWhitelistAPIKeysReq() *opsmngr.WhitelistAPIKeysReq { - entry := &opsmngr.WhitelistAPIKeysReq{ - CidrBlock: opts.cidr, - Description: opts.description, - } - return entry -} - -func (opts *CreateOpts) Run() error { - entry := opts.newWhitelistAPIKeysReq() - r, err := opts.store.CreateGlobalAPIKeyWhitelist(entry) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam globalAccessList(s) create [--cidr cidr][--desc description]. -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "create", - Short: "Create an IP access list entry for your global API key.", - Example: ` # Create an access list entry for your global API key to allow access from 192.0.2.0/24: - mongocli iam globalAccessLists create --cidr 192.0.2.0/24 --desc "My Global IP" --output json`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().StringVar(&opts.cidr, flag.CIDR, "", usage.AccessListCIDREntry) - cmd.Flags().StringVar(&opts.description, flag.Description, "", usage.APIAccessListIPEntry) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.CIDR) - _ = cmd.MarkFlagRequired(flag.Description) - return cmd -} diff --git a/internal/cli/iam/globalaccesslists/create_test.go b/internal/cli/iam/globalaccesslists/create_test.go deleted file mode 100644 index c497148c6d..0000000000 --- a/internal/cli/iam/globalaccesslists/create_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalaccesslists - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyWhitelistCreator(ctrl) - - createOpts := &CreateOpts{ - store: mockStore, - description: "test", - cidr: "77.54.32.11", - } - - r := createOpts.newWhitelistAPIKeysReq() - expected := &opsmngr.GlobalWhitelistAPIKey{} - mockStore. - EXPECT(). - CreateGlobalAPIKeyWhitelist(r). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/globalaccesslists/delete.go b/internal/cli/iam/globalaccesslists/delete.go deleted file mode 100644 index 6de3c33022..0000000000 --- a/internal/cli/iam/globalaccesslists/delete.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalaccesslists - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.GlobalAPIKeyWhitelistDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteGlobalAPIKeyWhitelist) -} - -// mongocli iam globalAccessList(s) delete [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Global access list entry '%s' deleted\n", "Global access list entry not deleted"), - } - - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified IP access list entry for your global API key.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the access list entry.", - }, - Example: ` # Remove the IP access list entry with the ID 5f5bad7a57aef32b04ed0210 from the access list for the global API key: - mongocli iam globalAccessLists delete 5f5bad7a57aef32b04ed0210`, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/iam/globalaccesslists/delete_test.go b/internal/cli/iam/globalaccesslists/delete_test.go deleted file mode 100644 index 258cfc8047..0000000000 --- a/internal/cli/iam/globalaccesslists/delete_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalaccesslists - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyWhitelistDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - mockStore. - EXPECT(). - DeleteGlobalAPIKeyWhitelist(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/globalaccesslists/describe.go b/internal/cli/iam/globalaccesslists/describe.go deleted file mode 100644 index 29b77e1450..0000000000 --- a/internal/cli/iam/globalaccesslists/describe.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalaccesslists - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.OutputOpts - id string - store store.GlobalAPIKeyWhitelistDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -const describeTemplate = `ID CIDR BLOCK CREATED AT -{{.ID}} {{.CidrBlock}} {{.Created}} -` - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GlobalAPIKeyWhitelist(opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam globalAccessList(s) describe . -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"show"}, - Args: require.ExactArgs(1), - Short: "Return the details for the specified access list entry for your global API key.", - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the access list entry.", - }, - Example: ` # Return the JSON-formatted details for the access list entry with the ID 5f5bad7a57aef32b04ed0210 from the access list for the global API key: - mongocli iam globalAccessLists describe 5f5bad7a57aef32b04ed0210 --output json`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/globalaccesslists/describe_test.go b/internal/cli/iam/globalaccesslists/describe_test.go deleted file mode 100644 index a77a8ebe50..0000000000 --- a/internal/cli/iam/globalaccesslists/describe_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalaccesslists - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyWhitelistDescriber(ctrl) - - opts := &DescribeOpts{ - store: mockStore, - id: "1", - } - - mockStore. - EXPECT(). - GlobalAPIKeyWhitelist(opts.id). - Return(&opsmngr.GlobalWhitelistAPIKey{}, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/globalaccesslists/global_access_lists.go b/internal/cli/iam/globalaccesslists/global_access_lists.go deleted file mode 100644 index b6041b3f7a..0000000000 --- a/internal/cli/iam/globalaccesslists/global_access_lists.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalaccesslists - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "globalAccessLists" - deprecated := append([]string{"globalWhitelists"}, cli.GenerateAliases("globalWhitelists")...) - var cmd = &cobra.Command{ - Use: use, - Short: "Manage IP access list for Global API Key.", - Aliases: cli.GenerateAliases(use, deprecated...), - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - CreateBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/globalaccesslists/global_access_lists_test.go b/internal/cli/iam/globalaccesslists/global_access_lists_test.go deleted file mode 100644 index 691a4f9bde..0000000000 --- a/internal/cli/iam/globalaccesslists/global_access_lists_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalaccesslists - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 4, - []string{}, - ) -} diff --git a/internal/cli/iam/globalaccesslists/list.go b/internal/cli/iam/globalaccesslists/list.go deleted file mode 100644 index af00e46b63..0000000000 --- a/internal/cli/iam/globalaccesslists/list.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalaccesslists - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID CIDR BLOCK CREATED AT{{range valueOrEmptySlice .Results}} -{{.ID}} {{.CidrBlock}} {{.Created}}{{end}} -` - -type ListOpts struct { - cli.OutputOpts - cli.ListOpts - store store.GlobalAPIKeyWhitelistLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.GlobalAPIKeyWhitelists(opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam globalAccessList(s) list|ls. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Args: require.NoArgs, - Annotations: map[string]string{ - "output": listTemplate, - }, - Short: "Return all IP access list entries for your global API key.", - Example: ` # Return a JSON-formatted list of all access list entries for the global API key: - mongocli iam globalAccessLists list --output json`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/globalaccesslists/list_test.go b/internal/cli/iam/globalaccesslists/list_test.go deleted file mode 100644 index bd1c0f30ec..0000000000 --- a/internal/cli/iam/globalaccesslists/list_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalaccesslists - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyWhitelistLister(ctrl) - - var expected = &opsmngr.GlobalWhitelistAPIKeys{ - Results: []*opsmngr.GlobalWhitelistAPIKey{}, - } - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GlobalAPIKeyWhitelists(opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - test.VerifyOutputTemplate(t, listTemplate, expected) -} diff --git a/internal/cli/iam/globalapikeys/create.go b/internal/cli/iam/globalapikeys/create.go deleted file mode 100644 index 200873bffa..0000000000 --- a/internal/cli/iam/globalapikeys/create.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalapikeys - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -const createTemplate = `API Key '{{.ID}}' created. -Public API Key {{.PublicKey}} -Private API Key {{.PrivateKey}} -` - -type CreateOpts struct { - cli.OutputOpts - desc string - roles []string - store store.GlobalAPIKeyCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) newAPIKeyInput() *opsmngr.APIKeyInput { - return &opsmngr.APIKeyInput{ - Desc: opts.desc, - Roles: opts.roles, - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateGlobalAPIKey(opts.newAPIKeyInput()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam globalApiKey(s) create [--role role][--desc description]. -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "create", - Short: "Create a global API key for your Ops Manager instance.", - Example: ` # Create a global API key that grants GLOBAL_READ_ONLY and GLOBAL_USER_ADMIN access for your Ops Manager instance: - mongocli iam globalApiKeys create --desc "My Global API key" --role "GLOBAL_READ_ONLY","GLOBAL_USER_ADMIN" --output json`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.GlobalAPIKeyRoles) - cmd.Flags().StringVar(&opts.desc, flag.Description, "", usage.APIKeyDescription) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Description) - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/globalapikeys/create_test.go b/internal/cli/iam/globalapikeys/create_test.go deleted file mode 100644 index fe94323919..0000000000 --- a/internal/cli/iam/globalapikeys/create_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalapikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyCreator(ctrl) - - expected := &opsmngr.APIKey{ - ID: "1", - } - - createOpts := &CreateOpts{ - store: mockStore, - roles: []string{"ORG_OWNER"}, - } - - mockStore. - EXPECT(). - CreateGlobalAPIKey(createOpts.newAPIKeyInput()). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/globalapikeys/delete.go b/internal/cli/iam/globalapikeys/delete.go deleted file mode 100644 index 8d559aebcc..0000000000 --- a/internal/cli/iam/globalapikeys/delete.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalapikeys - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.GlobalAPIKeyDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteGlobalAPIKey) -} - -// mongocli iam globalApiKey(s) delete . -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("API Key '%s' deleted\n", "API Key not deleted"), - } - - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified global API key from your Ops Manager instance.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the global API key.", - }, - Example: ` # Remove the global API key with the ID 5f5bad7a57aef32b04ed0210 from your Ops Manager instance: - mongocli iam globalApiKeys delete 5f5bad7a57aef32b04ed0210`, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/iam/globalapikeys/delete_test.go b/internal/cli/iam/globalapikeys/delete_test.go deleted file mode 100644 index 0f8b56e909..0000000000 --- a/internal/cli/iam/globalapikeys/delete_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalapikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - mockStore. - EXPECT(). - DeleteGlobalAPIKey(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/globalapikeys/describe.go b/internal/cli/iam/globalapikeys/describe.go deleted file mode 100644 index 283017f0bb..0000000000 --- a/internal/cli/iam/globalapikeys/describe.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalapikeys - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.OutputOpts - id string - store store.GlobalAPIKeyDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -const describeTemplate = `ID DESCRIPTION PUBLIC KEY PRIVATE KEY -{{.ID}} {{.Desc}} {{.PublicKey}} {{.PrivateKey}} -` - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GlobalAPIKey(opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam globalApiKey(s) describe . -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Short: "Return the details for the specified global API key for your Ops Manager instance.", - Aliases: []string{"show"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the global API key.", - }, - Example: ` # Return the JSON-formatted details for the global API key with the ID 5f5bad7a57aef32b04ed0210: - mongocli iam globalApiKeys describe 5f5bad7a57aef32b04ed0210 --output json`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/globalapikeys/describe_test.go b/internal/cli/iam/globalapikeys/describe_test.go deleted file mode 100644 index 88191d5379..0000000000 --- a/internal/cli/iam/globalapikeys/describe_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalapikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyDescriber(ctrl) - - opts := &DescribeOpts{ - store: mockStore, - id: "1", - } - - mockStore. - EXPECT(). - GlobalAPIKey(opts.id). - Return(&opsmngr.APIKey{}, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/globalapikeys/global_api_keys.go b/internal/cli/iam/globalapikeys/global_api_keys.go deleted file mode 100644 index 19cf7d608f..0000000000 --- a/internal/cli/iam/globalapikeys/global_api_keys.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalapikeys - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "globalApiKeys" - var cmd = &cobra.Command{ - Use: use, - Short: "Global API Keys operations.", - Aliases: cli.GenerateAliases(use), - } - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - CreateBuilder(), - UpdateBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/globalapikeys/list.go b/internal/cli/iam/globalapikeys/list.go deleted file mode 100644 index bb65339cec..0000000000 --- a/internal/cli/iam/globalapikeys/list.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalapikeys - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID DESCRIPTION PUBLIC KEY PRIVATE KEY{{range valueOrEmptySlice .}} -{{.ID}} {{.Desc}} {{.PublicKey}} {{.PrivateKey}}{{end}} -` - -type ListOpts struct { - cli.OutputOpts - cli.ListOpts - store store.GlobalAPIKeyLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.GlobalAPIKeys(opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam globalApiKey(s) list|ls. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all global API keys for your Ops Manager instance.", - Example: ` # Return a JSON-formatted list of global API keys: - mongocli iam globalApiKeys list --output json`, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/globalapikeys/list_test.go b/internal/cli/iam/globalapikeys/list_test.go deleted file mode 100644 index a2da4c08aa..0000000000 --- a/internal/cli/iam/globalapikeys/list_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalapikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyLister(ctrl) - - var expected []opsmngr.APIKey - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GlobalAPIKeys(opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - test.VerifyOutputTemplate(t, listTemplate, expected) -} diff --git a/internal/cli/iam/globalapikeys/update.go b/internal/cli/iam/globalapikeys/update.go deleted file mode 100644 index b18ba52032..0000000000 --- a/internal/cli/iam/globalapikeys/update.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package globalapikeys - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type UpdateOpts struct { - cli.OutputOpts - id string - desc string - roles []string - store store.GlobalAPIKeyUpdater -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) newAPIKeyInput() *opsmngr.APIKeyInput { - return &opsmngr.APIKeyInput{ - Desc: opts.desc, - Roles: opts.roles, - } -} - -const updateTemplate = "API Key '{{.ID}}' successfully updated.\n" - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateGlobalAPIKey(opts.id, opts.newAPIKeyInput()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam globalApiKey(s) update [--role role][--desc description]. -func UpdateBuilder() *cobra.Command { - opts := new(UpdateOpts) - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update ", - Args: require.ExactArgs(1), - Short: "Modify the roles and description for a global API key.", - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the global API key.", - }, - Example: ` # Modify the roles and description for the global API key with the ID 5f5bad7a57aef32b04ed0210: - mongocli iam globalApiKeys update 5f5bad7a57aef32b04ed0210 --desc "My Sample Global API Key" --role GLOBAL_MONITORING_ADMIN --output json`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.GlobalAPIKeyRoles+usage.UpdateWarning) - cmd.Flags().StringVar(&opts.desc, flag.Description, "", usage.APIKeyDescription) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Description) - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/globalapikeys/update_test.go b/internal/cli/iam/globalapikeys/update_test.go deleted file mode 100644 index 5643cb9c4c..0000000000 --- a/internal/cli/iam/globalapikeys/update_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package globalapikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdateOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAPIKeyUpdater(ctrl) - - expected := &opsmngr.APIKey{ - ID: "1", - } - - opts := &UpdateOpts{ - store: mockStore, - id: "1", - roles: []string{"ORG_OWNER"}, - } - - mockStore. - EXPECT(). - UpdateGlobalAPIKey(opts.id, opts.newAPIKeyInput()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/iam.go b/internal/cli/iam/iam.go deleted file mode 100644 index 4820e5cc15..0000000000 --- a/internal/cli/iam/iam.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package iam - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/globalaccesslists" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/globalapikeys" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/organizations" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/projects" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/teams" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/users" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/log" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/mongodb/mongodb-atlas-cli/internal/validate" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - opts := &cli.RefresherOpts{} - var debugLevel bool - cmd := &cobra.Command{ - Use: "iam", - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - log.SetWriter(cmd.ErrOrStderr()) - if debugLevel { - log.SetLevel(log.DebugLevel) - } - - if err := opts.InitFlow(config.Default())(); err != nil { - return err - } - if err := opts.RefreshAccessToken(cmd.Context()); err != nil { - return err - } - if config.Service() == "" { - config.SetService(config.CloudService) - } - return validate.Credentials() - }, - Short: "Organization and projects operations.", - Long: "Identity and Access Management.", - Annotations: map[string]string{ - "toc": "true", - }, - } - cmd.AddCommand( - projects.Builder(), - organizations.Builder(), - globalapikeys.Builder(), - globalaccesslists.Builder(), - users.Builder(), - teams.Builder(), - ) - - cmd.PersistentFlags().BoolVarP(&debugLevel, flag.Debug, flag.DebugShort, false, usage.Debug) - _ = cmd.PersistentFlags().MarkHidden(flag.Debug) - - return cmd -} diff --git a/internal/cli/iam/iam_test.go b/internal/cli/iam/iam_test.go deleted file mode 100644 index c02f291c41..0000000000 --- a/internal/cli/iam/iam_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package iam - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestBuilder(t *testing.T) { - got := Builder() - a := assert.New(t) - a.Len(got.Commands(), 6) - a.False(got.HasAvailableFlags()) -} diff --git a/internal/cli/iam/organizations/apikeys/accesslists/access_lists.go b/internal/cli/iam/organizations/apikeys/accesslists/access_lists.go deleted file mode 100644 index 88e793a3de..0000000000 --- a/internal/cli/iam/organizations/apikeys/accesslists/access_lists.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package accesslists - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "accessLists" - deprecated := append([]string{"whitelists"}, cli.GenerateAliases("whitelists")...) - cmd := &cobra.Command{ - Use: use, - Short: "Manage the IP access list for your API Key.", - Aliases: cli.GenerateAliases(use, deprecated...), - } - - cmd.AddCommand( - ListBuilder(), - CreateBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/accesslists/access_lists_test.go b/internal/cli/iam/organizations/apikeys/accesslists/access_lists_test.go deleted file mode 100644 index 8e98142390..0000000000 --- a/internal/cli/iam/organizations/apikeys/accesslists/access_lists_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package accesslists - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} diff --git a/internal/cli/iam/organizations/apikeys/accesslists/create.go b/internal/cli/iam/organizations/apikeys/accesslists/create.go deleted file mode 100644 index 49178089be..0000000000 --- a/internal/cli/iam/organizations/apikeys/accesslists/create.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package accesslists - -import ( - "context" - "errors" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const createTemplate = "Created new access list entry(s).\n" - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - apyKey string - ips []string - cidrs []string - currentIP bool - store store.OrganizationAPIKeyAccessListCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) newAccessListAPIKeysReq() ([]*atlas.AccessListAPIKeysReq, error) { - req := make([]*atlas.AccessListAPIKeysReq, 0, len(opts.ips)+len(opts.cidrs)) - if len(opts.ips) == 0 && len(opts.cidrs) == 0 { - return nil, fmt.Errorf("either --%s, --%s must be set", flag.IP, flag.CIDR) - } - for _, v := range opts.ips { - entry := &atlas.AccessListAPIKeysReq{ - IPAddress: v, - } - req = append(req, entry) - } - - for _, v := range opts.cidrs { - entry := &atlas.AccessListAPIKeysReq{ - CidrBlock: v, - } - req = append(req, entry) - } - - return req, nil -} - -func (opts *CreateOpts) Run() error { - req, err := opts.newAccessListAPIKeysReq() - if err != nil { - return err - } - - var result *atlas.AccessListAPIKeys - - result, err = opts.store.CreateOrganizationAPIKeyAccessList(opts.ConfigOrgID(), opts.apyKey, req) - if err != nil { - return err - } - return opts.Print(result) -} - -// mongocli iam organizations|orgs apiKey(s)|apikeys accessList create [--apiKey keyId] [--orgId orgId] [--ip ip] [--cidr cidr]. -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - cmd := &cobra.Command{ - Use: "create", - Short: "Create an IP access list entry for your API Key.", - Long: fmt.Sprintf(`To view possible values for the apiKey option, run %s organizations apiKeys list. - -`+fmt.Sprintf(usage.RequiredRole, "Read Write"), cli.ExampleAtlasEntryPoint()), - Example: fmt.Sprintf(` # Create access list entries for two IP addresses for the API key with the ID 5f24084d8dbffa3ad3f21234 in the organization with the ID 5a1b39eec902201990f12345: - %s organizations apiKeys accessLists create --apiKey 5f24084d8dbffa3ad3f21234 --cidr 192.0.2.0/24,198.51.100.0/24 --orgId 5a1b39eec902201990f12345 --output json`, cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "output": createTemplate, - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - if opts.currentIP { - publicIP := store.IPAddress() - if publicIP == "" { - return errors.New("unable to find your public IP address. Specify the public IP address for this command") - } - opts.ips = append(opts.ips, publicIP) - } - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.apyKey, flag.APIKey, "", usage.APIKey) - cmd.Flags().StringSliceVar(&opts.cidrs, flag.CIDR, []string{}, usage.AccessListCIDREntry) - cmd.Flags().StringSliceVar(&opts.ips, flag.IP, []string{}, usage.APIAccessListIPEntry) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - cmd.Flags().BoolVar(&opts.currentIP, flag.CurrentIP, false, usage.CurrentIP) - - _ = cmd.MarkFlagRequired(flag.APIKey) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/accesslists/create_test.go b/internal/cli/iam/organizations/apikeys/accesslists/create_test.go deleted file mode 100644 index 63b58b32c6..0000000000 --- a/internal/cli/iam/organizations/apikeys/accesslists/create_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package accesslists - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationAPIKeyAccessListCreator(ctrl) - - createOpts := &CreateOpts{ - store: mockStore, - apyKey: "1", - ips: []string{"77.54.32.11"}, - } - - r, err := createOpts.newAccessListAPIKeysReq() - if err != nil { - t.Fatalf("newAccessListAPIKeysReq() unexpected error: %v", err) - } - - mockStore. - EXPECT(). - CreateOrganizationAPIKeyAccessList(createOpts.OrgID, createOpts.apyKey, r). - Return(&atlas.AccessListAPIKeys{}, nil). - Times(1) - - if err = createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.OrgID, flag.Output, flag.APIKey, flag.CIDR, flag.IP}, - ) -} diff --git a/internal/cli/iam/organizations/apikeys/accesslists/delete.go b/internal/cli/iam/organizations/apikeys/accesslists/delete.go deleted file mode 100644 index 75f3b85d58..0000000000 --- a/internal/cli/iam/organizations/apikeys/accesslists/delete.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package accesslists - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - cli.GlobalOpts - apiKey string - store store.OrganizationAPIKeyAccessListDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteOrganizationAPIKeyAccessList, opts.ConfigOrgID(), opts.apiKey) -} - -// DeleteBuilder mongocli iam organizations|orgs apiKey(s)|apikey(s) accesslist delete [--orgId orgId] [--apiKey apiKey] --force. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Access list entry '%s' deleted\n", "Access list entry not deleted"), - } - - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified IP access list entry from your API Key.", - Long: fmt.Sprintf(usage.RequiredRole, "Read Write"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "entryDesc": "IP or CIDR address that you want to remove from the access list. If the entry includes a subnet mask, such as 192.0.2.0/24, use the URL-encoded value %2F for the forward slash /.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the IP address 192.0.2.0 from the access list for the API key with the ID 5f24084d8dbffa3ad3f21234 in the organization with the ID 5a1b39eec902201990f12345: - %s organizations apiKeys accessLists delete 192.0.2.0 --apiKey 5f24084d8dbffa3ad3f21234 --orgId 5a1b39eec902201990f12345`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateOrgID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.apiKey, flag.APIKey, "", usage.APIKey) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/accesslists/delete_test.go b/internal/cli/iam/organizations/apikeys/accesslists/delete_test.go deleted file mode 100644 index c6fc0deabf..0000000000 --- a/internal/cli/iam/organizations/apikeys/accesslists/delete_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package accesslists - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationAPIKeyAccessListDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - apiKey: "1", - GlobalOpts: cli.GlobalOpts{ - OrgID: "2", - }, - } - - mockStore. - EXPECT(). - DeleteOrganizationAPIKeyAccessList(deleteOpts.OrgID, deleteOpts.apiKey, gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.OrgID, flag.Force, flag.APIKey}, - ) -} diff --git a/internal/cli/iam/organizations/apikeys/accesslists/list.go b/internal/cli/iam/organizations/apikeys/accesslists/list.go deleted file mode 100644 index 2600793669..0000000000 --- a/internal/cli/iam/organizations/apikeys/accesslists/list.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package accesslists - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `IP ADDRESS CIDR BLOCK CREATED AT{{range valueOrEmptySlice .Results}} -{{.IPAddress}} {{.CidrBlock}} {{.Created}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - id string - store store.OrganizationAPIKeyAccessListLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - result, err := opts.store.OrganizationAPIKeyAccessLists(opts.ConfigOrgID(), opts.id, opts.NewListOptions()) - if err != nil { - return err - } - return opts.Print(result) -} - -// mongocli iam organizations|orgs apiKey(s)|apikey(s) accessList list|ls [--orgId orgId]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list ", - Aliases: []string{"ls"}, - Args: require.ExactArgs(1), - Short: "Return all IP access list entries for your API Key.", - Long: fmt.Sprintf(`To view possible values for the apiKeyID argument, run %s organizations apiKeys list. - -`+fmt.Sprintf(usage.RequiredRole, "Organization Member"), cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "apiKeyIDDesc": "Unique 24-digit string that identifies your API key.", - }, - Example: fmt.Sprintf(` # Return a JSON-formatted list of access list entries for the API key with the ID 5f24084d8dbffa3ad3f21234 in the organization with the ID 5a1b39eec902201990f12345: - %s organizations apiKeys accessLists list --apiKey 5f24084d8dbffa3ad3f21234 --orgId 5a1b39eec902201990f12345 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/accesslists/list_test.go b/internal/cli/iam/organizations/apikeys/accesslists/list_test.go deleted file mode 100644 index e2269e014d..0000000000 --- a/internal/cli/iam/organizations/apikeys/accesslists/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package accesslists - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -func TestListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationAPIKeyAccessListLister(ctrl) - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - OrganizationAPIKeyAccessLists(opts.OrgID, opts.id, opts.NewListOptions()). - Return(&atlas.AccessListAPIKeys{ - Results: []*atlas.AccessListAPIKey{}, - }, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.OrgID, flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/iam/organizations/apikeys/apikeys.go b/internal/cli/iam/organizations/apikeys/apikeys.go deleted file mode 100644 index 4d45a103cd..0000000000 --- a/internal/cli/iam/organizations/apikeys/apikeys.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/organizations/apikeys/accesslists" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "apiKeys" - var cmd = &cobra.Command{ - Use: use, - Short: "Organization API Keys operations.", - Aliases: cli.GenerateAliases(use), - } - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - UpdateBuilder(), - CreateBuilder(), - DeleteBuilder(), - accesslists.Builder(), - ) - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/create.go b/internal/cli/iam/organizations/apikeys/create.go deleted file mode 100644 index f98351fadc..0000000000 --- a/internal/cli/iam/organizations/apikeys/create.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const createTemplate = `API Key '{{.ID}}' created. -Public API Key {{.PublicKey}} -Private API Key {{.PrivateKey}} -` - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - desc string - roles []string - store store.OrganizationAPIKeyCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) newAPIKeyInput() *atlas.APIKeyInput { - return &atlas.APIKeyInput{ - Desc: opts.desc, - Roles: opts.roles, - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateOrganizationAPIKey(opts.ConfigOrgID(), opts.newAPIKeyInput()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam organizations|orgs apiKey(s)|apikeys create [--role role][--desc description][--orgId orgId]. -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - cmd := &cobra.Command{ - Use: "create", - Short: "Create an API Key for your organization.", - Long: `MongoDB returns the private API key only once. After you run this command, immediately copy, save, and secure both the public and private API keys. - -` + fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), - Args: require.NoArgs, - Annotations: map[string]string{ - "output": createTemplate, - }, - Example: fmt.Sprintf(` # Create an organization API key with organization owner access in the organization with the ID 5a1b39eec902201990f12345: - %s organizations apiKeys create --role ORG_OWNER --desc "My API Key" --orgId 5a1b39eec902201990f12345 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.APIKeyRoles) - cmd.Flags().StringVar(&opts.desc, flag.Description, "", usage.APIKeyDescription) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Description) - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/create_test.go b/internal/cli/iam/organizations/apikeys/create_test.go deleted file mode 100644 index 102e17b95d..0000000000 --- a/internal/cli/iam/organizations/apikeys/create_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationAPIKeyCreator(ctrl) - - expected := &mongodbatlas.APIKey{ - ID: "1", - } - - createOpts := &CreateOpts{ - store: mockStore, - roles: []string{"ORG_OWNER"}, - } - - mockStore. - EXPECT(). - CreateOrganizationAPIKey(createOpts.OrgID, createOpts.newAPIKeyInput()). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/organizations/apikeys/delete.go b/internal/cli/iam/organizations/apikeys/delete.go deleted file mode 100644 index dcb06b94ce..0000000000 --- a/internal/cli/iam/organizations/apikeys/delete.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - cli.GlobalOpts - store store.OrganizationAPIKeyDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteOrganizationAPIKey, opts.ConfigOrgID()) -} - -// mongocli iam organizations|orgs apiKey(s)|apikey(s) delete [--orgId orgId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("API Key '%s' deleted\n", "API Key not deleted"), - } - - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified API key for your organization.", - Long: fmt.Sprintf(`To view possible values for the ID argument, run %s organizations apiKeys list. - -%s`, cli.ExampleAtlasEntryPoint(), fmt.Sprintf(usage.RequiredRole, "Organization User Admin")), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the organization's API key.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the organization API key with the ID 5f24084d8dbffa3ad3f21234 for the organization with the ID 5a1b39eec902201990f12345: - %s organizations apiKeys delete 5f24084d8dbffa3ad3f21234 --orgId 5a1b39eec902201990f12345`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateOrgID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/delete_test.go b/internal/cli/iam/organizations/apikeys/delete_test.go deleted file mode 100644 index db0266cdd4..0000000000 --- a/internal/cli/iam/organizations/apikeys/delete_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationAPIKeyDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - mockStore. - EXPECT(). - DeleteOrganizationAPIKey(deleteOpts.OrgID, gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/organizations/apikeys/describe.go b/internal/cli/iam/organizations/apikeys/describe.go deleted file mode 100644 index f28f892ed6..0000000000 --- a/internal/cli/iam/organizations/apikeys/describe.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - id string - store store.OrganizationAPIKeyDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -const describeTemplate = `ID DESCRIPTION PUBLIC KEY PRIVATE KEY -{{.ID}} {{.Desc}} {{.PublicKey}} {{.PrivateKey}} -` - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.OrganizationAPIKey(opts.ConfigOrgID(), opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam organizations(s) apiKey(s)|apikey(s) describe --orgID. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"show"}, - Args: require.ExactArgs(1), - Short: "Return the details for the specified API key for your organization.", - Long: fmt.Sprintf(`To view possible values for the ID argument, run %s organizations apiKeys list. - -%s`, cli.ExampleAtlasEntryPoint(), fmt.Sprintf(usage.RequiredRole, "Organization Member")), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies your API key.", - "output": describeTemplate, - }, - Example: fmt.Sprintf(` # Return the JSON-formatted details for the organization API key with the ID 5f24084d8dbffa3ad3f21234 for the organization with the ID 5a1b39eec902201990f12345: - %s organizations apiKeys describe 5f24084d8dbffa3ad3f21234 --orgId 5a1b39eec902201990f12345 -output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/describe_test.go b/internal/cli/iam/organizations/apikeys/describe_test.go deleted file mode 100644 index 021845966e..0000000000 --- a/internal/cli/iam/organizations/apikeys/describe_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationAPIKeyDescriber(ctrl) - - opts := &DescribeOpts{ - store: mockStore, - id: "1", - } - - mockStore. - EXPECT(). - OrganizationAPIKey(opts.OrgID, opts.id). - Return(&mongodbatlas.APIKey{}, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/organizations/apikeys/list.go b/internal/cli/iam/organizations/apikeys/list.go deleted file mode 100644 index eae2570451..0000000000 --- a/internal/cli/iam/organizations/apikeys/list.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID DESCRIPTION PUBLIC KEY PRIVATE KEY{{range valueOrEmptySlice .}} -{{.ID}} {{.Desc}} {{.PublicKey}} {{.PrivateKey}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.OrganizationAPIKeyLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.OrganizationAPIKeys(opts.ConfigOrgID(), opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam organizations|orgs apiKey(s)|apikey(s) list|ls [--orgId orgId]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all API keys for your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization Member"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of organization API keys for the organization with the ID 5a1b39eec902201990f12345: - %s organizations apiKeys list --orgId 5a1b39eec902201990f12345 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/list_test.go b/internal/cli/iam/organizations/apikeys/list_test.go deleted file mode 100644 index 5b5184ba97..0000000000 --- a/internal/cli/iam/organizations/apikeys/list_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationAPIKeyLister(ctrl) - - var expected []mongodbatlas.APIKey - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - OrganizationAPIKeys(opts.OrgID, opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - test.VerifyOutputTemplate(t, listTemplate, expected) -} diff --git a/internal/cli/iam/organizations/apikeys/update.go b/internal/cli/iam/organizations/apikeys/update.go deleted file mode 100644 index 13dce9ae37..0000000000 --- a/internal/cli/iam/organizations/apikeys/update.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type UpdateOpts struct { - cli.GlobalOpts - cli.OutputOpts - id string - desc string - roles []string - store store.OrganizationAPIKeyUpdater -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) newAPIKeyInput() *atlas.APIKeyInput { - return &atlas.APIKeyInput{ - Desc: opts.desc, - Roles: opts.roles, - } -} - -const updateTemplate = "API Key '{{.ID}}' successfully updated.\n" - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateOrganizationAPIKey(opts.ConfigOrgID(), opts.id, opts.newAPIKeyInput()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam organizations|orgs apiKey(s)|apikey(s) update [--role role][--desc description][--orgId orgId]. -func UpdateBuilder() *cobra.Command { - opts := new(UpdateOpts) - cmd := &cobra.Command{ - Use: "assign ", - Aliases: []string{"updates"}, - Args: require.ExactArgs(1), - Short: "Modify the roles or description for the specified organization API key.", - Long: fmt.Sprintf(`When you modify the roles for an organization API key with this command, the values you specify overwrite the existing roles assigned to the API key. - -To view possible values for the apiKeyId argument, run %s organizations apiKeys list. - -`+fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "apiKeyIdDesc": "Unique 24-digit string that identifies your API key.", - "output": updateTemplate, - }, - Example: fmt.Sprintf(` # Modify the role and description for the API key with the ID 5f24084d8dbffa3ad3f21234 for the organization with the ID 5a1b39eec902201990f12345: - %s organizations apiKeys assign 5f24084d8dbffa3ad3f21234 --role ORG_MEMBER --desc "User1 Member Key" --orgId 5a1b39eec902201990f12345 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.APIKeyRoles+usage.UpdateWarning) - cmd.Flags().StringVar(&opts.desc, flag.Description, "", usage.APIKeyDescription) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/apikeys/update_test.go b/internal/cli/iam/organizations/apikeys/update_test.go deleted file mode 100644 index 8a0a5d2452..0000000000 --- a/internal/cli/iam/organizations/apikeys/update_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestUpdateOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationAPIKeyUpdater(ctrl) - - expected := &mongodbatlas.APIKey{ - ID: "1", - } - - opts := &UpdateOpts{ - store: mockStore, - id: "1", - roles: []string{"ORG_OWNER"}, - } - - mockStore. - EXPECT(). - UpdateOrganizationAPIKey(opts.OrgID, opts.id, opts.newAPIKeyInput()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/organizations/create.go b/internal/cli/iam/organizations/create.go deleted file mode 100644 index a930df933e..0000000000 --- a/internal/cli/iam/organizations/create.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package organizations - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/prerun" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const createTemplate = "Organization '{{.ID}}' created.\n" - -type CreateOpts struct { - cli.OutputOpts - name string - store store.OrganizationCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateOrganization(opts.name) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// CreateBuilder mongocli iam organization(s) create . -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - cmd := &cobra.Command{ - Use: "create ", - Short: "Create an Ops Manager or Cloud Manager organization. This command is unavailable for Atlas.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "nameDesc": "Label that identifies the organization.", - "output": createTemplate, - }, - Example: ` # Create an Ops Manager organization with the name myOrg: - mongocli iam organizations create myOrg --output json`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return prerun.ExecuteE( - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.name = args[0] - - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/create_test.go b/internal/cli/iam/organizations/create_test.go deleted file mode 100644 index 8d29f19f00..0000000000 --- a/internal/cli/iam/organizations/create_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package organizations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationCreator(ctrl) - - expected := &opsmngr.Organization{} - - mockStore. - EXPECT(). - CreateOrganization("Org 0").Return(expected, nil). - Times(1) - - createOpts := &CreateOpts{ - store: mockStore, - name: "Org 0", - } - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Output}, - ) -} diff --git a/internal/cli/iam/organizations/delete.go b/internal/cli/iam/organizations/delete.go deleted file mode 100644 index 00425d4326..0000000000 --- a/internal/cli/iam/organizations/delete.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package organizations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.OrganizationDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteOrganization) -} - -// DeleteBuilder mongocli iam organization(s) delete [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Organization '%s' deleted\n", "Organization not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified organization.", - Long: `Organizations with active projects can't be removed. - -` + fmt.Sprintf(usage.RequiredRole, "Organization Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the organization.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the organization with the ID 5e2211c17a3e5a48f5497de3: - %s organizations delete 5e2211c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/iam/organizations/delete_test.go b/internal/cli/iam/organizations/delete_test.go deleted file mode 100644 index eac48bbe85..0000000000 --- a/internal/cli/iam/organizations/delete_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package organizations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteOrganization(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force}, - ) -} diff --git a/internal/cli/iam/organizations/describe.go b/internal/cli/iam/organizations/describe.go deleted file mode 100644 index bc725d4dd2..0000000000 --- a/internal/cli/iam/organizations/describe.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package organizations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const ( - describeTemplate = `ID NAME -{{.ID}} {{.Name}} -` -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - id string - store store.OrganizationDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.Organization(opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam organizations(s) describe . -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"show"}, - Args: require.ExactArgs(1), - Short: "Return the details for the specified organizations.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization Member"), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the organization.", - "output": describeTemplate, - }, - Example: fmt.Sprintf(` # Return the JSON-formatted details for the organization with the ID 5e2211c17a3e5a48f5497de3: - %s organizations describe 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/describe_test.go b/internal/cli/iam/organizations/describe_test.go deleted file mode 100644 index 2be61562af..0000000000 --- a/internal/cli/iam/organizations/describe_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package organizations - -import ( - "bytes" - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/stretchr/testify/assert" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationDescriber(ctrl) - stringVal := "test" - expected := &opsmngr.Organization{ - Links: nil, - ID: stringVal, - Name: stringVal, - } - buf := new(bytes.Buffer) - - mockStore. - EXPECT(). - Organization(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(expected, nil). - Times(1) - - opts := &DescribeOpts{ - store: mockStore, - id: "5a0a1e7e0f2912c554080adc", - OutputOpts: cli.OutputOpts{ - Template: describeTemplate, - OutWriter: buf, - }, - } - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - test.VerifyOutputTemplate(t, describeTemplate, expected) - assert.Equal(t, `ID NAME -test test -`, buf.String()) - t.Log(buf.String()) -} diff --git a/internal/cli/iam/organizations/invitations/delete.go b/internal/cli/iam/organizations/invitations/delete.go deleted file mode 100644 index 4a7c2fc2e6..0000000000 --- a/internal/cli/iam/organizations/invitations/delete.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - cli.GlobalOpts - store store.OrganizationInvitationDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteInvitation, opts.ConfigOrgID()) -} - -// mongocli iam organization(s) invitation(s) delete [--force] [--orgId orgId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Invitation '%s' deleted\n", "Invitation not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified pending invitation to your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "invitationIdDesc": "Unique 24-digit string that identifies the invitation.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the pending invitation with the ID 5dd56c847a3e5a1f363d424d from the organization with the ID 5f71e5255afec75a3d0f96dc: - %s organizations invitations delete 5dd56c847a3e5a1f363d424d --orgId 5f71e5255afec75a3d0f96dc`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateOrgID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - return cmd -} diff --git a/internal/cli/iam/organizations/invitations/delete_test.go b/internal/cli/iam/organizations/invitations/delete_test.go deleted file mode 100644 index 7a73559db5..0000000000 --- a/internal/cli/iam/organizations/invitations/delete_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationInvitationDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - GlobalOpts: cli.GlobalOpts{OrgID: "1"}, - } - - mockStore. - EXPECT(). - DeleteInvitation(deleteOpts.ConfigOrgID(), deleteOpts.Entry). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force, flag.OrgID}, - ) -} diff --git a/internal/cli/iam/organizations/invitations/describe.go b/internal/cli/iam/organizations/invitations/describe.go deleted file mode 100644 index 3e85418fc0..0000000000 --- a/internal/cli/iam/organizations/invitations/describe.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const describeTemplate = `ID USERNAME CREATED AT EXPIRES AT -{{.ID}} {{.Username}} {{.CreatedAt}} {{.ExpiresAt}} -` - -type DescribeOpts struct { - cli.OutputOpts - cli.GlobalOpts - id string - store store.OrganizationInvitationDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.OrganizationInvitation(opts.ConfigOrgID(), opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam organizations(s) invitations describe|get [--orgId orgId]. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Args: require.ExactArgs(1), - Short: "Return the details for the specified pending invitation to your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), - Annotations: map[string]string{ - "invitationIdDesc": "Unique 24-digit string that identifies the invitation.", - "output": describeTemplate, - }, - Example: fmt.Sprintf(` # Return the JSON-formatted details of the pending invitation with the ID 5dd56c847a3e5a1f363d424d for the organization with the ID 5f71e5255afec75a3d0f96dc: - %s organizations invitations describe 5dd56c847a3e5a1f363d424d --orgId 5f71e5255afec75a3d0f96dc --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/invitations/describe_test.go b/internal/cli/iam/organizations/invitations/describe_test.go deleted file mode 100644 index a134af0b3d..0000000000 --- a/internal/cli/iam/organizations/invitations/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationInvitationDescriber(ctrl) - - opts := &DescribeOpts{ - store: mockStore, - id: "5a0a1e7e0f2912c554080adc", - } - - mockStore. - EXPECT(). - OrganizationInvitation(opts.ConfigOrgID(), opts.id). - Return(&mongodbatlas.Invitation{}, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.OrgID}, - ) -} diff --git a/internal/cli/iam/organizations/invitations/invitations.go b/internal/cli/iam/organizations/invitations/invitations.go deleted file mode 100644 index ba29b1baf0..0000000000 --- a/internal/cli/iam/organizations/invitations/invitations.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "invitations" - cmd := &cobra.Command{ - Use: use, - Short: "Invitation operations.", - Long: "Create, list and manage your MongoDB organization invites.", - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - DeleteBuilder(), - UpdateBuilder(), - InviteBuilder()) - return cmd -} diff --git a/internal/cli/iam/organizations/invitations/invitations_test.go b/internal/cli/iam/organizations/invitations/invitations_test.go deleted file mode 100644 index 48b2d703f1..0000000000 --- a/internal/cli/iam/organizations/invitations/invitations_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/iam/organizations/invitations/invite.go b/internal/cli/iam/organizations/invitations/invite.go deleted file mode 100644 index ba1abb7c65..0000000000 --- a/internal/cli/iam/organizations/invitations/invite.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const createTemplate = "User '{{.Username}}' invited.\n" - -type InviteOpts struct { - cli.OutputOpts - cli.GlobalOpts - username string - roles []string - teamIDs []string - store store.OrganizationInviter -} - -func (opts *InviteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *InviteOpts) Run() error { - r, err := opts.store.InviteUser(opts.ConfigOrgID(), opts.newInvitation()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *InviteOpts) newInvitation() *atlas.Invitation { - return &atlas.Invitation{ - Username: opts.username, - Roles: opts.roles, - TeamIDs: opts.teamIDs, - } -} - -// mongocli iam organization(s) invitation(s) invite|create --role role [--teamId teamId] [--orgId orgId]. -func InviteBuilder() *cobra.Command { - opts := new(InviteOpts) - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "invite ", - Short: "Invite the specified MongoDB user to your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), - Aliases: []string{"create"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "emailDesc": "Email address that belongs to the user that you want to invite to the organization.", - }, - Example: fmt.Sprintf(` # Invite the MongoDB user with the email user@example.com to the organization with the ID 5f71e5255afec75a3d0f96dc with ORG_OWNER access: - %s organizations invitations invite user@example.com --orgId 5f71e5255afec75a3d0f96dc --role ORG_OWNER --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.PreRunE(opts.ValidateOrgID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.username = args[0] - return opts.Run() - }, - } - - if config.BinName() == config.MongoCLI { - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.MCLIOrgRole) - } else { - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.OrgRole) - } - cmd.Flags().StringSliceVar(&opts.teamIDs, flag.TeamID, []string{}, usage.TeamID) - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/organizations/invitations/invite_test.go b/internal/cli/iam/organizations/invitations/invite_test.go deleted file mode 100644 index 36e7c072ec..0000000000 --- a/internal/cli/iam/organizations/invitations/invite_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationInviter(ctrl) - - expected := &mongodbatlas.Invitation{} - opts := &InviteOpts{ - store: mockStore, - username: "test", - } - - mockStore. - EXPECT(). - InviteUser(opts.ConfigOrgID(), opts.newInvitation()).Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestInviteBuilder(t *testing.T) { - test.CmdValidator( - t, - InviteBuilder(), - 0, - []string{flag.Role, flag.TeamID, flag.OrgID}, - ) -} diff --git a/internal/cli/iam/organizations/invitations/list.go b/internal/cli/iam/organizations/invitations/list.go deleted file mode 100644 index c274316fd1..0000000000 --- a/internal/cli/iam/organizations/invitations/list.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const listTemplate = `ID USERNAME CREATED AT EXPIRES AT{{range valueOrEmptySlice .}} -{{.Id}} {{.Username}} {{.CreatedAt}} {{.ExpiresAt}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.OrganizationInvitationLister - username string -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.OrganizationInvitations(opts.ConfigOrgID(), opts.newInvitationOptions()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *ListOpts) newInvitationOptions() *atlas.InvitationOptions { - return &atlas.InvitationOptions{ - Username: opts.username, - } -} - -// mongocli iam organizations(s) invitations list [--email email] [--orgId orgId]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all pending invitations to your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of pending invitations to the organization with the ID 5f71e5255afec75a3d0f96dc: - %s organizations invitations list --orgId 5f71e5255afec75a3d0f96dc --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.username, flag.Email, "", usage.Email) - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/invitations/list_test.go b/internal/cli/iam/organizations/invitations/list_test.go deleted file mode 100644 index 01f1916956..0000000000 --- a/internal/cli/iam/organizations/invitations/list_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationInvitationLister(ctrl) - - var expected []*mongodbatlas.Invitation - - listOpts := &ListOpts{store: mockStore} - - mockStore. - EXPECT(). - OrganizationInvitations(listOpts.ConfigOrgID(), listOpts.newInvitationOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Email, flag.OrgID}, - ) -} diff --git a/internal/cli/iam/organizations/invitations/update.go b/internal/cli/iam/organizations/invitations/update.go deleted file mode 100644 index 0f2ae781ac..0000000000 --- a/internal/cli/iam/organizations/invitations/update.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "errors" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const updateTemplate = "Invitation {{.ID}} updated.\n" - -type UpdateOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.OrganizationInvitationUpdater - invitationID string - username string - roles []string -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateOrganizationInvitation(opts.ConfigOrgID(), opts.invitationID, opts.newInvitation()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *UpdateOpts) newInvitation() *atlas.Invitation { - return &atlas.Invitation{ - Username: opts.username, - Roles: opts.roles, - } -} - -func (opts *UpdateOpts) validate() error { - if opts.username == "" && opts.invitationID == "" { - return errors.New("you must provide the email address or the invitationId") - } - - return nil -} - -// mongocli iam organization(s) invitation(s) updates [invitationId] --role role [--orgId orgId] [--email email]. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - cmd := &cobra.Command{ - Use: "update [invitationId]", - Aliases: []string{"updates"}, - Short: "Modifies the details of the specified pending invitation to your organization.", - Long: `You can use either the invitation ID or the user's email address to specify the invitation. - -` + fmt.Sprintf(usage.RequiredRole, "Organization Owner"), - Annotations: map[string]string{ - "invitationIdDesc": "Unique 24-digit string that identifies the invitation.", - "output": updateTemplate, - }, - Example: fmt.Sprintf(` # Modify the pending invitation with the ID 5dd56c847a3e5a1f363d424d to grant ORG_OWNER access the organization with the ID 5f71e5255afec75a3d0f96dc: - %[1]s organizations invitations update 5dd56c847a3e5a1f363d424d --orgId 5f71e5255afec75a3d0f96dc --role ORG_OWNER --output json - - # Modify the invitation for the user with the email address user@example.com to grant ORG_OWNER access the organization with the ID 5f71e5255afec75a3d0f96dc: - %[1]s organizations invitations update --email user@example.com --orgId 5f71e5255afec75a3d0f96dc --role ORG_OWNER --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if len(args) > 0 { - opts.invitationID = args[0] - } - - return opts.PreRunE( - opts.ValidateProjectID, - opts.ValidateOrgID, - opts.validate, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.username, flag.Email, "", usage.Email) - if config.BinName() == config.MongoCLI { - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.MCLIOrgRole+usage.UpdateWarning) - } else { - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.OrgRole+usage.UpdateWarning) - } - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/organizations/invitations/update_test.go b/internal/cli/iam/organizations/invitations/update_test.go deleted file mode 100644 index 2114a48338..0000000000 --- a/internal/cli/iam/organizations/invitations/update_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationInvitationUpdater(ctrl) - - expected := &atlas.Invitation{} - - updateOpts := &UpdateOpts{ - roles: []string{"test"}, - store: mockStore, - GlobalOpts: cli.GlobalOpts{OrgID: "1"}, - } - - mockStore. - EXPECT(). - UpdateOrganizationInvitation(updateOpts.ConfigOrgID(), updateOpts.invitationID, updateOpts.newInvitation()). - Return(expected, nil). - Times(1) - - if err := updateOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Email, flag.OrgID, flag.Role}, - ) -} diff --git a/internal/cli/iam/organizations/list.go b/internal/cli/iam/organizations/list.go deleted file mode 100644 index 25a24b2af6..0000000000 --- a/internal/cli/iam/organizations/list.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package organizations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -const listTemplate = `ID NAME{{range valueOrEmptySlice .Results}} -{{.ID}} {{.Name}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.ListOpts - cli.OutputOpts - store store.OrganizationLister - name string - includeDeletedOrgs bool -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.Organizations(opts.newOrganizationListOptions()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *ListOpts) newOrganizationListOptions() *opsmngr.OrganizationsListOptions { - return &atlas.OrganizationsListOptions{ - Name: opts.name, - IncludeDeletedOrgs: &opts.includeDeletedOrgs, - ListOptions: *opts.NewListOptions(), - } -} - -// mongocli iam organizations(s) list --name --includeDeletedOrgs. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all organizations.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization Member"), - Args: require.NoArgs, - Annotations: map[string]string{ - "output": listTemplate, - }, - Example: fmt.Sprintf(` # Return a JSON-formatted list of all organizations: - %[1]s organizations list --output json - - # Return a JSON-formatted list that includes the organizations named org1 and Org1, but doesn't return org123: - %[1]s organizations list --name org1 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.name, flag.Name, "", usage.OrgNameFilter) - cmd.Flags().BoolVar(&opts.includeDeletedOrgs, flag.IncludeDeleted, false, usage.OrgIncludeDeleted) - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/organizations/list_test.go b/internal/cli/iam/organizations/list_test.go deleted file mode 100644 index 879118d865..0000000000 --- a/internal/cli/iam/organizations/list_test.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package organizations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationLister(ctrl) - - expected := &atlasv2.PaginatedOrganization{} - - listOpts := &ListOpts{store: mockStore} - - mockStore. - EXPECT(). - Organizations(listOpts.newOrganizationListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/organizations/organizations.go b/internal/cli/iam/organizations/organizations.go deleted file mode 100644 index 4081e3212a..0000000000 --- a/internal/cli/iam/organizations/organizations.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package organizations - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/organizations/apikeys" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/organizations/invitations" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/organizations/users" - "github.com/spf13/cobra" -) - -const use = "organizations" - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: use, - Short: fmt.Sprintf("Manage your %s organizations.", cli.DescriptionServiceName()), - Long: "Create, list and manage your MongoDB organizations.", - Aliases: cli.GenerateAliases(use, "orgs", "org"), - } - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - CreateBuilder(), - DeleteBuilder(), - apikeys.Builder(), - users.Builder(), - invitations.Builder(), - ) - return cmd -} diff --git a/internal/cli/iam/organizations/organizations_test.go b/internal/cli/iam/organizations/organizations_test.go deleted file mode 100644 index 12aa42bef7..0000000000 --- a/internal/cli/iam/organizations/organizations_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package organizations - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 7, - []string{}, - ) -} diff --git a/internal/cli/iam/organizations/users/list.go b/internal/cli/iam/organizations/users/list.go deleted file mode 100644 index f63ede1b6a..0000000000 --- a/internal/cli/iam/organizations/users/list.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID FIRST NAME LAST NAME USERNAME{{range valueOrEmptySlice .Results}} -{{.ID}} {{.FirstName}} {{.LastName}} {{.Username}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.ListOpts - cli.OutputOpts - store store.UserLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - listOptions := opts.NewListOptions() - r, err := opts.store.OrganizationUsers(opts.ConfigOrgID(), listOptions) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// ListBuilder mongocli iam organizations(s) users list --orgId orgId. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all users for an organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization Member"), - Args: require.NoArgs, - Annotations: map[string]string{ - "output": listTemplate, - }, - Example: fmt.Sprintf(` # Return a JSON-formatted list of all users for the organization with the ID 5e2211c17a3e5a48f5497de3: - %s organizations users list --orgId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.PreRunE( - opts.ValidateOrgID, - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - return cmd -} - -func Builder() *cobra.Command { - const use = "users" - cmd := &cobra.Command{ - Use: use, - Short: fmt.Sprintf("Manage your %s users.", - cli.DescriptionServiceName()), - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - ListBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/organizations/users/list_test.go b/internal/cli/iam/organizations/users/list_test.go deleted file mode 100644 index e911de9a7e..0000000000 --- a/internal/cli/iam/organizations/users/list_test.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package users - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockUserLister(ctrl) - - expected := &mongodbatlas.AtlasUsersResponse{} - - listOpts := &ListOpts{ - GlobalOpts: cli.GlobalOpts{ - OrgID: "1", - }, - store: mockStore, - } - - mockStore. - EXPECT(). - OrganizationUsers(listOpts.ConfigOrgID(), listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{ - flag.Page, - flag.Limit, - flag.Output, - flag.OrgID, - }, - ) -} - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/iam/projects/apikeys/api_keys.go b/internal/cli/iam/projects/apikeys/api_keys.go deleted file mode 100644 index 33a94b3187..0000000000 --- a/internal/cli/iam/projects/apikeys/api_keys.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "apiKeys" - cmd := &cobra.Command{ - Use: use, - Short: "Manage API Keys for your project.", - Aliases: cli.GenerateAliases(use), - } - cmd.AddCommand( - ListBuilder(), - CreateBuilder(), - DeleteBuilder(), - AssignBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/projects/apikeys/assign.go b/internal/cli/iam/projects/apikeys/assign.go deleted file mode 100644 index 795c6583f2..0000000000 --- a/internal/cli/iam/projects/apikeys/assign.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type AssignOpts struct { - cli.GlobalOpts - cli.OutputOpts - id string - roles []string - store store.ProjectAPIKeyAssigner -} - -func (opts *AssignOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *AssignOpts) newAssignAPIKey() *atlas.AssignAPIKey { - return &atlas.AssignAPIKey{ - Roles: opts.roles, - } -} - -var updateTemplate = "API Key successfully assigned.\n" - -func (opts *AssignOpts) Run() error { - err := opts.store.AssignProjectAPIKey(opts.ConfigProjectID(), opts.id, opts.newAssignAPIKey()) - if err != nil { - return err - } - return opts.Print(nil) -} - -// mongocli iam project(s) apiKey(s)|apikey(s) assign [--role role][--projectId projectId]. -func AssignBuilder() *cobra.Command { - opts := new(AssignOpts) - cmd := &cobra.Command{ - Use: "assign ", - Aliases: []string{"update"}, - Args: require.ExactArgs(1), - Short: "Assign the specified organization API key to your project and modify the API key's roles for the project.", - Long: fmt.Sprintf(`When you modify the roles for an organization API key with this command, the values you specify overwrite the existing roles assigned to the API key. - -To view possible values for the ID argument, run %s organizations apiKeys list.`, cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies your API key.", - }, - Example: fmt.Sprintf(` # Assign an organization API key with the ID 5f46ae53d58b421fe3edc115 and grant the GROUP_DATA_ACCESS_READ_WRITE role for the project with ID 5e2211c17a3e5a48f5497de3: - %s projects apiKeys assign 5f46ae53d58b421fe3edc115 --projectId 5e1234c17a3e5a48f5497de3 --role GROUP_DATA_ACCESS_READ_WRITE --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.ProjectAPIKeyRoles) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.Role) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/apikeys/assign_test.go b/internal/cli/iam/projects/apikeys/assign_test.go deleted file mode 100644 index b7b05f5952..0000000000 --- a/internal/cli/iam/projects/apikeys/assign_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestUpdateOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectAPIKeyAssigner(ctrl) - - opts := &AssignOpts{ - store: mockStore, - id: "1", - roles: []string{"ORG_OWNER"}, - } - - mockStore. - EXPECT(). - AssignProjectAPIKey(opts.OrgID, opts.id, opts.newAssignAPIKey()). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/apikeys/create.go b/internal/cli/iam/projects/apikeys/create.go deleted file mode 100644 index eaaff12b43..0000000000 --- a/internal/cli/iam/projects/apikeys/create.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/atlas/mongodbatlas" -) - -var createTemplate = `API Key '{{.ID}}' created. -Public API Key {{.PublicKey}} -Private API Key {{.PrivateKey}} -` - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.ProjectAPIKeyCreator - description string - roles []string -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - apiKeyInput := &mongodbatlas.APIKeyInput{ - Desc: opts.description, - Roles: opts.roles, - } - - r, err := opts.store.CreateProjectAPIKey(opts.ProjectID, apiKeyInput) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam project apiKey create --roles roles --description description. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - cmd := &cobra.Command{ - Use: "create", - Short: "Create an organization API key and assign it to your project.", - Long: `MongoDB returns the private API key only once. After you run this command, immediately copy, save, and secure both the public and private API keys. - -` + fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Annotations: map[string]string{ - "output": createTemplate, - }, - Args: require.NoArgs, - Example: fmt.Sprintf(` # Create an organization API key with the ORG_OWNER role and assign it to the project with ID 5e2211c17a3e5a48f5497de3: - %s projects apiKeys create --desc "My API key" --projectId 5e1234c17a3e5a48f5497de3 --role ORG_OWNER --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.ProjectAPIKeyRoles) - cmd.Flags().StringVar(&opts.description, flag.Description, "", usage.APIKeyDescription) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Description) - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/projects/apikeys/create_test.go b/internal/cli/iam/projects/apikeys/create_test.go deleted file mode 100644 index 1f0960abe6..0000000000 --- a/internal/cli/iam/projects/apikeys/create_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectAPIKeyCreator(ctrl) - - createOpts := &CreateOpts{ - store: mockStore, - description: "desc", - roles: []string{}, - } - - createOpts.ProjectID = "5a0a1e7e0f2912c554080adc" - - apiKey := &mongodbatlas.APIKeyInput{ - Desc: createOpts.description, - Roles: []string{}, - } - expected := &mongodbatlas.APIKey{} - - mockStore. - EXPECT(). - CreateProjectAPIKey(createOpts.ProjectID, apiKey).Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/apikeys/delete.go b/internal/cli/iam/projects/apikeys/delete.go deleted file mode 100644 index b4360034fc..0000000000 --- a/internal/cli/iam/projects/apikeys/delete.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - cli.GlobalOpts - store store.ProjectAPIKeyDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteProjectAPIKey, opts.ConfigProjectID()) -} - -// mongocli iam project(s) apiKey(s)|apikey(s) delete [--projectId projectId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("API Key '%s' deleted\n", "APIKey not deleted"), - } - - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified organization API key from your project.", - Long: fmt.Sprintf(`The API key still exists at the organization level. To reassign the organization API key to a project, run the %[1]s projects apiKeys assign command. - -To view possible values for the ID argument, run %[1]s organizations apiKeys list. - -`+fmt.Sprintf(usage.RequiredRole, "Project User Admin"), cli.ExampleAtlasEntryPoint()), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies your API key.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove an organization API key with the ID 5f46ae53d58b421fe3edc115 from the project with ID 5e2211c17a3e5a48f5497de3: - %s projects apiKeys delete 5f46ae53d58b421fe3edc115 --projectId 5e1234c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/iam/projects/apikeys/delete_test.go b/internal/cli/iam/projects/apikeys/delete_test.go deleted file mode 100644 index e35493bda5..0000000000 --- a/internal/cli/iam/projects/apikeys/delete_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectAPIKeyDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - mockStore. - EXPECT(). - DeleteProjectAPIKey(deleteOpts.ProjectID, gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/apikeys/list.go b/internal/cli/iam/projects/apikeys/list.go deleted file mode 100644 index 7aa3a6a9c8..0000000000 --- a/internal/cli/iam/projects/apikeys/list.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID PUBLIC KEY DESCRIPTION{{range valueOrEmptySlice .}} -{{.ID}} {{.PublicKey}} {{.Desc}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.ProjectAPIKeyLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - listOptions := opts.NewListOptions() - - r, err := opts.store.ProjectAPIKeys(opts.ConfigProjectID(), listOptions) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam project(s) apiKeys list. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all organization API keys assigned to your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of organization API keys assigned to the project with ID 5e2211c17a3e5a48f5497de3: - %s projects apiKeys list --projectId 5e1234c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/apikeys/list_test.go b/internal/cli/iam/projects/apikeys/list_test.go deleted file mode 100644 index d4ad9e438b..0000000000 --- a/internal/cli/iam/projects/apikeys/list_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectAPIKeyLister(ctrl) - - var expected []mongodbatlas.APIKey - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ProjectAPIKeys(listOpts.ProjectID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/create.go b/internal/cli/iam/projects/create.go deleted file mode 100644 index 8e20558243..0000000000 --- a/internal/cli/iam/projects/create.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package projects - -import ( - "context" - "fmt" - - "github.com/Masterminds/semver/v3" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const ( - atlasCreateTemplate = "Project '{{.ID}}' created.\n" - govRegionOnly = "GOV_REGIONS_ONLY" -) - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - name string - projectOwnerID string - regionUsageRestrictions bool - withoutDefaultAlertSettings bool - serviceVersion *semver.Version - store store.ProjectCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - if opts.ConfigOrgID() == "" { - return cli.ErrMissingOrgID - } - - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - var defaultAlertSettings *bool - if opts.withoutDefaultAlertSettings { - f := false - defaultAlertSettings = &f - } - - r, err := opts.store.CreateProject(opts.name, opts.ConfigOrgID(), - opts.newRegionUsageRestrictions(), defaultAlertSettings, opts.newCreateProjectOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *CreateOpts) newRegionUsageRestrictions() string { - if opts.regionUsageRestrictions { - return govRegionOnly - } - - return "" -} - -func (opts *CreateOpts) newCreateProjectOptions() *atlas.CreateProjectOptions { - return &atlas.CreateProjectOptions{ProjectOwnerID: opts.projectOwnerID} -} - -func (opts *CreateOpts) validateOwnerID() error { - if opts.projectOwnerID == "" || opts.serviceVersion == nil { - return nil - } - - constrain, err := semver.NewConstraint(">= 6.0") - if err != nil { - return err - } - - if !constrain.Check(opts.serviceVersion) { - return fmt.Errorf("%s is available only for Atlas, Cloud Manager and Ops Manager >= 6.0", flag.OwnerID) - } - - return nil -} - -func (opts *CreateOpts) validateWithoutDefaultAlertSettings() error { - if !opts.withoutDefaultAlertSettings || opts.serviceVersion == nil { - return nil - } - - constrain, err := semver.NewConstraint(">= 6.0") - if err != nil { - return err - } - - if !constrain.Check(opts.serviceVersion) { - return fmt.Errorf("%s is available only for Atlas, Cloud Manager and Ops Manager >= 6.0", flag.WithoutDefaultAlertSettings) - } - - return nil -} - -func (opts *CreateOpts) initServiceVersion() error { - if config.Service() != config.OpsManagerService { - return nil - } - v, err := opts.store.ServiceVersion() - if err != nil { - return err - } - - sv, err := cli.ParseServiceVersion(v) - if err != nil { - return err - } - - opts.serviceVersion = sv - return nil -} - -// mongocli iam project(s) create [--orgId orgId] [--ownerID ownerID] [--withoutDefaultAlertSettings]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - opts.Template = atlasCreateTemplate - cmd := &cobra.Command{ - Use: "create ", - Short: "Create a project in your organization.", - Long: `Projects group clusters into logical collections that support an application environment, workload, or both. Each project can have its own users, teams, security, and alert settings. - -` + fmt.Sprintf(usage.RequiredRole, "Project Data Access Read/Write"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "projectNameDesc": "Label that identifies the project.", - "output": atlasCreateTemplate, - }, - Example: fmt.Sprintf(` # Create a project in the organization with the ID 5e2211c17a3e5a48f5497de3 using default alert settings: - %s projects create --orgId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - if !config.IsCloud() { - opts.Template += "Agent API Key: '{{.AgentAPIKey}}'\n" - } - return opts.PreRunE(opts.initStore(cmd.Context()), opts.initServiceVersion, opts.validateOwnerID, opts.validateWithoutDefaultAlertSettings) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.name = args[0] - return opts.Run() - }, - } - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVar(&opts.projectOwnerID, flag.OwnerID, "", usage.ProjectOwnerID) - cmd.Flags().BoolVar(&opts.regionUsageRestrictions, flag.GovCloudRegionsOnly, false, usage.GovCloudRegionsOnly) - cmd.Flags().BoolVar(&opts.withoutDefaultAlertSettings, flag.WithoutDefaultAlertSettings, false, usage.WithoutDefaultAlertSettings) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/create_test.go b/internal/cli/iam/projects/create_test.go deleted file mode 100644 index 56b5f7aadb..0000000000 --- a/internal/cli/iam/projects/create_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package projects - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectCreator(ctrl) - - opts := CreateOpts{} - expected := &mongodbatlas.Project{} - - mockStore. - EXPECT(). - CreateProject(gomock.Eq("ProjectBar"), gomock.Eq("5a0a1e7e0f2912c554080adc"), opts.newRegionUsageRestrictions(), nil, opts.newCreateProjectOptions()).Return(expected, nil). - Times(1) - - createOpts := &CreateOpts{ - store: mockStore, - name: "ProjectBar", - } - createOpts.OrgID = "5a0a1e7e0f2912c554080adc" - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.OrgID, flag.OwnerID, flag.GovCloudRegionsOnly, flag.WithoutDefaultAlertSettings}, - ) -} diff --git a/internal/cli/iam/projects/delete.go b/internal/cli/iam/projects/delete.go deleted file mode 100644 index 0febb128d1..0000000000 --- a/internal/cli/iam/projects/delete.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package projects - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.ProjectDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteProject) -} - -// mongocli iam project(s) delete [--orgId orgId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Project '%s' deleted\n", "Project not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the project.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the project with the ID 5e2211c17a3e5a48f5497de3: - %s projects delete 5e2211c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/iam/projects/delete_test.go b/internal/cli/iam/projects/delete_test.go deleted file mode 100644 index 802873017b..0000000000 --- a/internal/cli/iam/projects/delete_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package projects - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteProject(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - opts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/describe.go b/internal/cli/iam/projects/describe.go deleted file mode 100644 index 301848280b..0000000000 --- a/internal/cli/iam/projects/describe.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package projects - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const describeTemplate = `ID NAME -{{.ID}} {{.Name}} -` - -type DescribeOpts struct { - cli.OutputOpts - id string - store store.ProjectDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.Project(opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam projects(s) describe . -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"show", "get"}, - Args: require.ExactArgs(1), - Short: "Return the details for the specified project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the project.", - "output": describeTemplate, - }, - Example: fmt.Sprintf(` # Return the JSON-formatted details for the project with the ID 5e2211c17a3e5a48f5497de3: - %s projects describe 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/describe_test.go b/internal/cli/iam/projects/describe_test.go deleted file mode 100644 index 5c2f855741..0000000000 --- a/internal/cli/iam/projects/describe_test.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package projects - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectDescriber(ctrl) - - mockStore. - EXPECT(). - Project(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(&opsmngr.Project{}, nil). - Times(1) - - opts := &DescribeOpts{ - store: mockStore, - id: "5a0a1e7e0f2912c554080adc", - } - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/invitations/delete.go b/internal/cli/iam/projects/invitations/delete.go deleted file mode 100644 index 597be73c74..0000000000 --- a/internal/cli/iam/projects/invitations/delete.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - cli.GlobalOpts - store store.ProjectInvitationDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteProjectInvitation, opts.ConfigProjectID()) -} - -// mongocli iam project(s) invitation(s) delete [--force] [--projectId projectId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Invitation '%s' deleted\n", "Invitation not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified pending invitation to your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "invitationIdDesc": "Unique 24-digit string that identifies the invitation.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the pending invitation with the ID 5dd56c847a3e5a1f363d424d from the project with the ID 5f71e5255afec75a3d0f96dc: - %s projects invitations delete 5dd56c847a3e5a1f363d424d --projectId 5f71e5255afec75a3d0f96dc`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/iam/projects/invitations/delete_test.go b/internal/cli/iam/projects/invitations/delete_test.go deleted file mode 100644 index 52c6fb9c35..0000000000 --- a/internal/cli/iam/projects/invitations/delete_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectInvitationDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - GlobalOpts: cli.GlobalOpts{OrgID: "1"}, - } - - mockStore. - EXPECT(). - DeleteProjectInvitation(deleteOpts.ConfigProjectID(), deleteOpts.Entry). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force, flag.ProjectID}, - ) -} diff --git a/internal/cli/iam/projects/invitations/describe.go b/internal/cli/iam/projects/invitations/describe.go deleted file mode 100644 index b7fa534c92..0000000000 --- a/internal/cli/iam/projects/invitations/describe.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const describeTemplate = `ID USERNAME CREATED AT EXPIRES AT -{{.ID}} {{.Username}} {{.CreatedAt}} {{.ExpiresAt}} -` - -type DescribeOpts struct { - cli.OutputOpts - cli.GlobalOpts - id string - store store.ProjectInvitationDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.ProjectInvitation(opts.ConfigProjectID(), opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam project(s) invitations describe|get [--projectId projectId]. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Args: require.ExactArgs(1), - Short: "Return the details for the specified pending invitation to your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Annotations: map[string]string{ - "invitationIdDesc": "Unique 24-digit string that identifies the invitation.", - "output": describeTemplate, - }, - Example: fmt.Sprintf(` # Return the JSON-formatted details of the pending invitation with the ID 5dd56c847a3e5a1f363d424d for the project with the ID 5f71e5255afec75a3d0f96dc: - %s projects invitations describe 5dd56c847a3e5a1f363d424d --projectId 5f71e5255afec75a3d0f96dc --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/invitations/describe_test.go b/internal/cli/iam/projects/invitations/describe_test.go deleted file mode 100644 index 85fe21c45c..0000000000 --- a/internal/cli/iam/projects/invitations/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectInvitationDescriber(ctrl) - - opts := &DescribeOpts{ - store: mockStore, - id: "5a0a1e7e0f2912c554080adc", - } - - mockStore. - EXPECT(). - ProjectInvitation(opts.ConfigProjectID(), opts.id). - Return(&mongodbatlas.Invitation{}, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.ProjectID}, - ) -} diff --git a/internal/cli/iam/projects/invitations/invitations.go b/internal/cli/iam/projects/invitations/invitations.go deleted file mode 100644 index 676cc630c5..0000000000 --- a/internal/cli/iam/projects/invitations/invitations.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "invitations" - cmd := &cobra.Command{ - Use: use, - Short: "Invitation operations.", - Long: "Create, list and manage your MongoDB project invites.", - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - DeleteBuilder(), - InviteBuilder(), - UpdateBuilder()) - return cmd -} diff --git a/internal/cli/iam/projects/invitations/invitations_test.go b/internal/cli/iam/projects/invitations/invitations_test.go deleted file mode 100644 index 48b2d703f1..0000000000 --- a/internal/cli/iam/projects/invitations/invitations_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/iam/projects/invitations/invite.go b/internal/cli/iam/projects/invitations/invite.go deleted file mode 100644 index f96129cdd2..0000000000 --- a/internal/cli/iam/projects/invitations/invite.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const createTemplate = "User '{{.Username}}' invited.\n" - -type InviteOpts struct { - cli.OutputOpts - cli.GlobalOpts - username string - roles []string - teamIDs []string - store store.ProjectInviter -} - -func (opts *InviteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *InviteOpts) Run() error { - r, err := opts.store.InviteUserToProject(opts.ConfigProjectID(), opts.newInvitation()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *InviteOpts) newInvitation() *atlas.Invitation { - return &atlas.Invitation{ - Username: opts.username, - Roles: opts.roles, - TeamIDs: opts.teamIDs, - } -} - -// mongocli iam project(s) invitation(s) invite|create --role role [--teamId teamId] [--orgId orgId]. -func InviteBuilder() *cobra.Command { - opts := new(InviteOpts) - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "invite ", - Short: "Invite the specified MongoDB user to your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Aliases: []string{"create"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "emailDesc": "Email address that belongs to the user that you want to invite to the project.", - }, - Example: fmt.Sprintf(` # Invite the MongoDB user with the email user@example.com to the project with the ID 5f71e5255afec75a3d0f96dc with GROUP_READ_ONLY access: - %s projects invitations invite user@example.com --projectId 5f71e5255afec75a3d0f96dc --role GROUP_READ_ONLY --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.username = args[0] - return opts.Run() - }, - } - - if config.BinName() == config.MongoCLI { - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.MCLIProjectRole) - } else { - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.ProjectRole) - } - cmd.Flags().StringSliceVar(&opts.teamIDs, flag.TeamID, []string{}, usage.TeamID) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/projects/invitations/invite_test.go b/internal/cli/iam/projects/invitations/invite_test.go deleted file mode 100644 index 60fd8016b8..0000000000 --- a/internal/cli/iam/projects/invitations/invite_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectInviter(ctrl) - - expected := &mongodbatlas.Invitation{} - opts := &InviteOpts{ - store: mockStore, - username: "test", - } - - mockStore. - EXPECT(). - InviteUserToProject(opts.ConfigProjectID(), opts.newInvitation()).Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestInviteBuilder(t *testing.T) { - test.CmdValidator( - t, - InviteBuilder(), - 0, - []string{flag.Role, flag.TeamID, flag.ProjectID}, - ) -} diff --git a/internal/cli/iam/projects/invitations/list.go b/internal/cli/iam/projects/invitations/list.go deleted file mode 100644 index 3b5359f2c8..0000000000 --- a/internal/cli/iam/projects/invitations/list.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const listTemplate = `ID USERNAME CREATED AT EXPIRES AT{{range valueOrEmptySlice .}} -{{.ID}} {{.Username}} {{.CreatedAt}} {{.ExpiresAt}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.ProjectInvitationLister - username string -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.ProjectInvitations(opts.ConfigProjectID(), opts.newInvitationOptions()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *ListOpts) newInvitationOptions() *atlas.InvitationOptions { - return &atlas.InvitationOptions{ - Username: opts.username, - } -} - -// mongocli iam project(s) invitations list [--email email] [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all pending invitations to your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of pending invitations to the project with the ID 5f71e5255afec75a3d0f96dc: - %s projects invitations list --projectId 5f71e5255afec75a3d0f96dc --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.username, flag.Email, "", usage.Email) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/invitations/list_test.go b/internal/cli/iam/projects/invitations/list_test.go deleted file mode 100644 index 9fa5497f2a..0000000000 --- a/internal/cli/iam/projects/invitations/list_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectInvitationLister(ctrl) - - var expected []*mongodbatlas.Invitation - - listOpts := &ListOpts{store: mockStore} - - mockStore. - EXPECT(). - ProjectInvitations(listOpts.ConfigProjectID(), listOpts.newInvitationOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Email, flag.ProjectID}, - ) -} diff --git a/internal/cli/iam/projects/invitations/update.go b/internal/cli/iam/projects/invitations/update.go deleted file mode 100644 index 97ab202ed8..0000000000 --- a/internal/cli/iam/projects/invitations/update.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package invitations - -import ( - "context" - "errors" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const updateTemplate = "Invitation {{.ID}} updated.\n" - -type UpdateOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.ProjectInvitationUpdater - invitationID string - username string - roles []string -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateProjectInvitation(opts.ConfigProjectID(), opts.invitationID, opts.newInvitation()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *UpdateOpts) newInvitation() *atlas.Invitation { - return &atlas.Invitation{ - Username: opts.username, - Roles: opts.roles, - } -} - -func (opts *UpdateOpts) validate() error { - if opts.username == "" && opts.invitationID == "" { - return errors.New("you must provide the email address or the invitationId") - } - - return nil -} - -// mongocli iam project(s) invitation(s) updates [invitationId] --role role [--orgId orgId] [--email email]. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - cmd := &cobra.Command{ - Use: "update [invitationId]", - Aliases: []string{"updates"}, - Short: "Modifies the details of the specified pending invitation to your project.", - Long: `You can use either the invitation ID or the user's email address to specify the invitation. - -` + fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Annotations: map[string]string{ - "invitationIdDesc": "Unique 24-digit string that identifies the invitation.", - "output": updateTemplate, - }, - Example: fmt.Sprintf(` # Modify the pending invitation with the ID 5dd56c847a3e5a1f363d424d to grant GROUP_READ_ONLY access the project with the ID 5f71e5255afec75a3d0f96dc: - %[1]s projects invitations update 5dd56c847a3e5a1f363d424d --projectId 5f71e5255afec75a3d0f96dc --role GROUP_READ_ONLY --output json - - # Modify the invitation for the user with the email address user@example.com to grant GROUP_READ_ONLY access the project with the ID 5f71e5255afec75a3d0f96dc: - %[1]s projects invitations update --email user@example.com --projectId 5f71e5255afec75a3d0f96dc --role GROUP_READ_ONLY --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if len(args) > 0 { - opts.invitationID = args[0] - } - - return opts.PreRunE( - opts.ValidateProjectID, - opts.validate, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.username, flag.Email, "", usage.Email) - if config.BinName() == config.MongoCLI { - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.MCLIOrgRole+usage.UpdateWarning) - } else { - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.OrgRole+usage.UpdateWarning) - } - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/projects/invitations/update_test.go b/internal/cli/iam/projects/invitations/update_test.go deleted file mode 100644 index f4b4c8fcac..0000000000 --- a/internal/cli/iam/projects/invitations/update_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package invitations - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectInvitationUpdater(ctrl) - - expected := &atlas.Invitation{} - - updateOpts := &UpdateOpts{ - roles: []string{"test"}, - store: mockStore, - GlobalOpts: cli.GlobalOpts{OrgID: "1"}, - } - - mockStore. - EXPECT(). - UpdateProjectInvitation(updateOpts.ConfigProjectID(), updateOpts.invitationID, updateOpts.newInvitation()). - Return(expected, nil). - Times(1) - - if err := updateOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Email, flag.ProjectID, flag.Role}, - ) -} diff --git a/internal/cli/iam/projects/list.go b/internal/cli/iam/projects/list.go deleted file mode 100644 index 08c93593e5..0000000000 --- a/internal/cli/iam/projects/list.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package projects - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/atlas/mongodbatlas" -) - -const listTemplate = `ID NAME{{range valueOrEmptySlice .Results}} -{{.ID}} {{.Name}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.ProjectLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - var r interface{} - var err error - listOptions := opts.NewListOptions() - if opts.ConfigOrgID() != "" && config.Service() == config.OpsManagerService { - l := &mongodbatlas.ProjectsListOptions{ListOptions: *listOptions} - r, err = opts.store.GetOrgProjects(opts.ConfigOrgID(), l) - } else { - r, err = opts.store.Projects(listOptions) - } - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli iam project(s) list [--orgId orgId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all projects.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Data Access Read/Write"), - Args: require.NoArgs, - Annotations: map[string]string{ - "output": listTemplate, - }, - Example: fmt.Sprintf(` # Return a JSON-formatted list of all projects: - %s projects list --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/list_test.go b/internal/cli/iam/projects/list_test.go deleted file mode 100644 index a8a2bffee7..0000000000 --- a/internal/cli/iam/projects/list_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package projects - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectLister(ctrl) - - expected := &mongodbatlas.Projects{} - - t.Run("No ConfigOrgID is given", func(t *testing.T) { - listOpts := &ListOpts{ - store: mockStore, - } - mockStore. - EXPECT(). - Projects(listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - - t.Run("An ConfigOrgID is given for OM", func(t *testing.T) { - listOpts := &ListOpts{ - store: mockStore, - } - listOpts.OrgID = "1" - filter := &mongodbatlas.ProjectsListOptions{ListOptions: *listOpts.NewListOptions()} - mockStore. - EXPECT(). - GetOrgProjects("1", filter). - Return(expected, nil). - Times(1) - - config.SetService(config.OpsManagerService) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - - t.Run("An ConfigOrgID is given for Atlas", func(t *testing.T) { - listOpts := &ListOpts{ - store: mockStore, - } - listOpts.OrgID = "1" - - mockStore. - EXPECT(). - Projects(listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - config.SetService(config.CloudService) - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} diff --git a/internal/cli/iam/projects/projects.go b/internal/cli/iam/projects/projects.go deleted file mode 100644 index 735e3213d6..0000000000 --- a/internal/cli/iam/projects/projects.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package projects - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/projects/apikeys" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/projects/invitations" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/projects/teams" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/projects/users" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "projects" - cmd := &cobra.Command{ - Use: use, - Short: fmt.Sprintf("Manage your %s projects.", cli.DescriptionServiceName()), - Long: "Create, list and manage your MongoDB projects.", - Aliases: cli.GenerateAliases(use), - } - cmd.AddCommand( - ListBuilder(), - CreateBuilder(), - DeleteBuilder(), - DescribeBuilder(), - apikeys.Builder(), - users.Builder(), - teams.Builder(), - invitations.Builder(), - ) - - return cmd -} diff --git a/internal/cli/iam/projects/projects_test.go b/internal/cli/iam/projects/projects_test.go deleted file mode 100644 index fb9f1d64fe..0000000000 --- a/internal/cli/iam/projects/projects_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package projects - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 8, - []string{}, - ) -} diff --git a/internal/cli/iam/projects/teams/add.go b/internal/cli/iam/projects/teams/add.go deleted file mode 100644 index 428f3bf943..0000000000 --- a/internal/cli/iam/projects/teams/add.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const addTemplate = "Team added to the project.\n" - -type AddOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.ProjectTeamAdder - teamID string - roles []string -} - -func (opts *AddOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *AddOpts) Run() error { - r, err := opts.store.AddTeamsToProject(opts.ConfigProjectID(), opts.newProjectTeam()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *AddOpts) newProjectTeam() []*atlas.ProjectTeam { - return []*atlas.ProjectTeam{ - { - TeamID: opts.teamID, - RoleNames: opts.roles, - }, - } -} - -// mongocli iam project(s) team(s) add teamId --projectId projectId --role role. -func AddBuilder() *cobra.Command { - opts := &AddOpts{} - cmd := &cobra.Command{ - Use: "add ", - Args: require.ExactArgs(1), - Short: "Add the specified team to your project.", - Long: `All members of the team share the same project access. - -` + fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Annotations: map[string]string{ - "teamIdDesc": "Unique 24-digit string that identifies the team.", - }, - Example: fmt.Sprintf(` # Add the team with the ID 5dd58c647a3e5a6c5bce46c7 to the project with the ID 5e2211c17a3e5a48f5497de3 with GROUP_READ_ONLY project access: - %s projects teams add 5dd58c647a3e5a6c5bce46c7 --projectId 5e2211c17a3e5a48f5497de3 --role GROUP_READ_ONLY`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.teamID = args[0] - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), addTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.TeamRole) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/projects/teams/add_test.go b/internal/cli/iam/projects/teams/add_test.go deleted file mode 100644 index ab45c76f73..0000000000 --- a/internal/cli/iam/projects/teams/add_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package teams - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestAdd_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectTeamAdder(ctrl) - - var expected *mongodbatlas.TeamsAssigned - - opts := &AddOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - AddTeamsToProject(opts.ProjectID, opts.newProjectTeam()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/teams/delete.go b/internal/cli/iam/projects/teams/delete.go deleted file mode 100644 index d12436031f..0000000000 --- a/internal/cli/iam/projects/teams/delete.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.ProjectTeamDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteTeamFromProject, opts.ConfigProjectID()) -} - -// mongocli iam project(s) team(s) delete [--force] [--projectId projectId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Team '%s' deleted\n", "Team not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified team from your project.", - Long: `After you remove a team from your project, the team still exists in the organization in which it was created. - -` + fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "teamIdDesc": "Unique 24-digit string that identifies the team.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the team with the ID 5dd58c647a3e5a6c5bce46c7 from the project with the ID 5e2211c17a3e5a48f5497de3: - %s projects teams delete 5dd58c647a3e5a6c5bce46c7 --projectId 5e2211c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.Entry = args[0] - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.Prompt, - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/iam/projects/teams/delete_test.go b/internal/cli/iam/projects/teams/delete_test.go deleted file mode 100644 index 4736b1214b..0000000000 --- a/internal/cli/iam/projects/teams/delete_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package teams - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectTeamDeleter(ctrl) - - opts := &DeleteOpts{ - store: mockStore, - GlobalOpts: cli.GlobalOpts{ - ProjectID: "6a0a1e7e0f2912c554080adc", - }, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - - mockStore. - EXPECT(). - DeleteTeamFromProject(opts.ProjectID, opts.Entry). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/teams/list.go b/internal/cli/iam/projects/teams/list.go deleted file mode 100644 index 08d9fb3d9b..0000000000 --- a/internal/cli/iam/projects/teams/list.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID{{range valueOrEmptySlice .Results}} -{{.TeamID}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.ProjectTeamLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.ProjectTeams(opts.ConfigProjectID()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam team(s) list --orgId orgId. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all teams for a project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Args: require.NoArgs, - Annotations: map[string]string{ - "output": listTemplate, - }, - Example: fmt.Sprintf(` # Return a JSON-formatted list of all teams for the project with the ID 5e2211c17a3e5a48f5497de3: - %s projects teams list --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/teams/list_test.go b/internal/cli/iam/projects/teams/list_test.go deleted file mode 100644 index 1a84bf14d4..0000000000 --- a/internal/cli/iam/projects/teams/list_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package teams - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectTeamLister(ctrl) - - var expected []mongodbatlas.Team - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ProjectTeams(listOpts.ProjectID). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/teams/teams.go b/internal/cli/iam/projects/teams/teams.go deleted file mode 100644 index d08f84789a..0000000000 --- a/internal/cli/iam/projects/teams/teams.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "teams" - cmd := &cobra.Command{ - Use: use, - Short: fmt.Sprintf("Manage your %s teams.", cli.DescriptionServiceName()), - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - ListBuilder(), - AddBuilder(), - DeleteBuilder(), - UpdateBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/projects/teams/update.go b/internal/cli/iam/projects/teams/update.go deleted file mode 100644 index 217e067501..0000000000 --- a/internal/cli/iam/projects/teams/update.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const updateTemplate = "Team's roles updated.\n" - -type UpdateOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.TeamRolesUpdater - teamID string - roles []string -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateProjectTeamRoles(opts.ConfigProjectID(), opts.teamID, opts.newTeamUpdateRoles()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *UpdateOpts) newTeamUpdateRoles() *atlas.TeamUpdateRoles { - return &atlas.TeamUpdateRoles{ - RoleNames: opts.roles, - } -} - -// mongocli iam team(s) user(s) updates teamId --projectId projectId --role role. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - cmd := &cobra.Command{ - Use: "update ", - Aliases: []string{"updates"}, - Args: require.ExactArgs(1), - Short: "Modify the roles for the specified team for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Annotations: map[string]string{ - "teamIdDesc": "Unique 24-digit string that identifies the team.", - "output": updateTemplate, - }, - Example: fmt.Sprintf(` # Modify the roles for the team with the ID 5dd56c847a3e5a1f363d424d to grant GROUP_READ_ONLY access to the project with the ID 5f71e5255afec75a3d0f96dc: - %s projects teams update 5dd56c847a3e5a1f363d424d --projectId 5f71e5255afec75a3d0f96dc --role GROUP_READ_ONLY --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.teamID = args[0] - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.TeamRole+usage.UpdateWarning) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Role) - - return cmd -} diff --git a/internal/cli/iam/projects/teams/update_test.go b/internal/cli/iam/projects/teams/update_test.go deleted file mode 100644 index 8266f5c11d..0000000000 --- a/internal/cli/iam/projects/teams/update_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package teams - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockTeamRolesUpdater(ctrl) - - expected := []atlas.TeamRoles{} - - updateOpts := &UpdateOpts{ - roles: []string{"test"}, - store: mockStore, - } - - mockStore. - EXPECT(). - UpdateProjectTeamRoles(updateOpts.ProjectID, updateOpts.teamID, updateOpts.newTeamUpdateRoles()). - Return(expected, nil). - Times(1) - - if err := updateOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/users/delete.go b/internal/cli/iam/projects/users/delete.go deleted file mode 100644 index 2c6f83c3aa..0000000000 --- a/internal/cli/iam/projects/users/delete.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.ProjectUserDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteUserFromProject, opts.ConfigProjectID()) -} - -// mongocli iam project(s) users delete [--projectId projectId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("User '%s' deleted from the project\n", "User not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified user from your project.", - Long: `After you remove a user from your project, the user still exists in the organization in which it was created. - -` + fmt.Sprintf(usage.RequiredRole, "Project User Admin"), - Args: require.ExactArgs(1), - Example: fmt.Sprintf(` # Remove the user with the ID 5dd58c647a3e5a6c5bce46c7 from the project with the ID 5e2211c17a3e5a48f5497de3: - %s projects users delete 5dd58c647a3e5a6c5bce46c7 --projectId 5e2211c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "IDDesc": "Unique 24-digit string that identifies the user.", - "output": opts.SuccessMessage(), - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/iam/projects/users/delete_test.go b/internal/cli/iam/projects/users/delete_test.go deleted file mode 100644 index a17139580b..0000000000 --- a/internal/cli/iam/projects/users/delete_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package users - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectUserDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteUserFromProject(gomock.Eq("5a0a1e7e0f2912c554080adc"), gomock.Eq("213321ds12")). - Return(nil). - Times(1) - - opts := &DeleteOpts{ - store: mockStore, - GlobalOpts: cli.GlobalOpts{ - ProjectID: "5a0a1e7e0f2912c554080adc", - }, - DeleteOpts: &cli.DeleteOpts{ - Entry: "213321ds12", - Confirm: true, - }, - } - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/users/list.go b/internal/cli/iam/projects/users/list.go deleted file mode 100644 index 1e864c7e25..0000000000 --- a/internal/cli/iam/projects/users/list.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID FIRST NAME LAST NAME USERNAME{{range valueOrEmptySlice .}} -{{.ID}} {{.FirstName}} {{.LastName}} {{.Username}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.ProjectUsersLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - listOptions := opts.NewListOptions() - - r, err := opts.store.ProjectUsers(opts.ConfigProjectID(), listOptions) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam project(s) user(s) list --projectId. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all users for a project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of all users for the project with the ID 5e2211c17a3e5a48f5497de3: - %s projects users list --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/projects/users/list_test.go b/internal/cli/iam/projects/users/list_test.go deleted file mode 100644 index 0a89034665..0000000000 --- a/internal/cli/iam/projects/users/list_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package users - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectUsersLister(ctrl) - - var expected []mongodbatlas.AtlasUser - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ProjectUsers(listOpts.ProjectID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/projects/users/users.go b/internal/cli/iam/projects/users/users.go deleted file mode 100644 index d3baa539b8..0000000000 --- a/internal/cli/iam/projects/users/users.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "users" - cmd := &cobra.Command{ - Use: use, - Short: "Manage users for a project.", - Aliases: cli.GenerateAliases(use), - } - cmd.AddCommand( - ListBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/teams/create.go b/internal/cli/iam/teams/create.go deleted file mode 100644 index 2cf1c65fad..0000000000 --- a/internal/cli/iam/teams/create.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -var createTemplate = "Team '{{.Name}}' created.\n" - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - name string - userNames []string - store store.TeamCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateTeam(opts.ConfigOrgID(), opts.newTeam()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *CreateOpts) newTeam() *atlas.Team { - return &atlas.Team{ - Name: opts.name, - Usernames: opts.userNames, - } -} - -// mongocli iam team(s) create [--orgId orgId]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - cmd := &cobra.Command{ - Use: "create ", - Short: "Create a team for your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "nameDesc": "Label that identifies the team.", - "output": createTemplate, - }, - Example: fmt.Sprintf(` # Create a team named myTeam in the organization with ID 5e2211c17a3e5a48f5497de3: - %s teams create myTeam --username user1@example.com,user2@example.com --orgId 5e1234c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.name = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.userNames, flag.Username, []string{}, usage.TeamUsername) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Username) - - return cmd -} diff --git a/internal/cli/iam/teams/create_test.go b/internal/cli/iam/teams/create_test.go deleted file mode 100644 index 2100bf29d6..0000000000 --- a/internal/cli/iam/teams/create_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package teams - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockTeamCreator(ctrl) - - expected := &mongodbatlas.Team{} - - createOpts := &CreateOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - CreateTeam(createOpts.OrgID, createOpts.newTeam()).Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/teams/delete.go b/internal/cli/iam/teams/delete.go deleted file mode 100644 index fd77965be7..0000000000 --- a/internal/cli/iam/teams/delete.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.TeamDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteTeam, opts.ConfigOrgID()) -} - -// mongocli iam team(s) delete [--force] [--orgId orgId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Team '%s' deleted\n", "Team not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified team from your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "teamIdDesc": "Unique 24-digit string that identifies the team.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the team with the ID 5e44445ef10fab20b49c0f31 from the organization with ID 5e2211c17a3e5a48f5497de3: - %s teams delete 5e44445ef10fab20b49c0f31 --orgId 5e1234c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.Entry = args[0] - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.Prompt, - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - return cmd -} diff --git a/internal/cli/iam/teams/delete_test.go b/internal/cli/iam/teams/delete_test.go deleted file mode 100644 index d8b11db546..0000000000 --- a/internal/cli/iam/teams/delete_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package teams - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockTeamDeleter(ctrl) - - opts := &DeleteOpts{ - store: mockStore, - GlobalOpts: cli.GlobalOpts{ - OrgID: "6a0a1e7e0f2912c554080adc", - }, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - - mockStore. - EXPECT(). - DeleteTeam(opts.OrgID, opts.Entry). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/teams/describe.go b/internal/cli/iam/teams/describe.go deleted file mode 100644 index 45a7d8cdbf..0000000000 --- a/internal/cli/iam/teams/describe.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "context" - "errors" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const describeTemplate = `ID NAME -{{.ID}} {{.Name}} -` - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.TeamDescriber - name string - id string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - var r interface{} - var err error - - if opts.name != "" { - r, err = opts.store.TeamByName(opts.ConfigOrgID(), opts.name) - } - - if opts.id != "" { - r, err = opts.store.TeamByID(opts.ConfigOrgID(), opts.id) - } - - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *DescribeOpts) validate() error { - if opts.id == "" && opts.name == "" { - return errors.New("must supply one of 'id' or 'username'") - } - - if opts.id != "" && opts.name != "" { - return errors.New("cannot supply both 'id' and 'username'") - } - - return nil -} - -// mongocli iam team(s) describe --id id --name name --orgId orgId. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe", - Aliases: []string{"get"}, - Annotations: map[string]string{"output": describeTemplate}, - Example: fmt.Sprintf(` # Return the JSON-formatted details for the the team with the ID 5e44445ef10fab20b49c0f31 in the organization with ID 5e2211c17a3e5a48f5497de3: - %[1]s teams describe --id 5e44445ef10fab20b49c0f31 --projectId 5e1234c17a3e5a48f5497de3 --output json - - # Return the JSON-formatted details for the the team with the name myTeam in the organization with ID 5e2211c17a3e5a48f5497de3: - %[1]s teams describe --name myTeam --projectId 5e1234c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - Short: "Return the details for the specified team for your organization.", - Long: `You can return the details for a team using the team's ID or the team's name. You must specify either the id option or the name option. - -` + fmt.Sprintf(usage.RequiredRole, "Organization Member"), - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - opts.validate, - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.name, flag.Name, "", usage.TeamName) - cmd.Flags().StringVar(&opts.id, flag.ID, "", usage.TeamID) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/teams/describe_test.go b/internal/cli/iam/teams/describe_test.go deleted file mode 100644 index ab075ce891..0000000000 --- a/internal/cli/iam/teams/describe_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package teams - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockTeamDescriber(ctrl) - - var expected *mongodbatlas.Team - - t.Run("by ID", func(t *testing.T) { - descOpts := &DescribeOpts{ - store: mockStore, - id: "id", - } - - mockStore. - EXPECT(). - TeamByID(descOpts.OrgID, descOpts.id). - Return(expected, nil). - Times(1) - - if err := descOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - t.Run("by name", func(t *testing.T) { - descOpts := &DescribeOpts{ - store: mockStore, - name: "test", - } - - mockStore. - EXPECT(). - TeamByName(descOpts.OrgID, descOpts.name). - Return(expected, nil). - Times(1) - - if err := descOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} diff --git a/internal/cli/iam/teams/list.go b/internal/cli/iam/teams/list.go deleted file mode 100644 index 014c1ae92d..0000000000 --- a/internal/cli/iam/teams/list.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID NAME{{range valueOrEmptySlice .}} -{{.ID}} {{.Name}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.TeamLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - listOptions := opts.NewListOptions() - - r, err := opts.store.Teams(opts.ConfigOrgID(), listOptions) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam team(s) list --orgId orgId. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all teams for your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization Member"), - Example: fmt.Sprintf(` # Return a JSON-formatted list of the teams for the organization with ID 5e2211c17a3e5a48f5497de3: - %s teams list --orgId 5e1234c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/teams/list_test.go b/internal/cli/iam/teams/list_test.go deleted file mode 100644 index 9624032b76..0000000000 --- a/internal/cli/iam/teams/list_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package teams - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockTeamLister(ctrl) - - var expected []mongodbatlas.Team - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - Teams(listOpts.OrgID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/teams/teams.go b/internal/cli/iam/teams/teams.go deleted file mode 100644 index 0f6187ac05..0000000000 --- a/internal/cli/iam/teams/teams.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package teams - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam/teams/users" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - description := "Create, list and manage your Cloud Manager or Ops Manager teams." - - const use = "teams" - cmd := &cobra.Command{ - Use: use, - Short: fmt.Sprintf("Manage your %s teams.", cli.DescriptionServiceName()), - Long: description, - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - CreateBuilder(), - users.Builder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/teams/users/add.go b/internal/cli/iam/teams/users/add.go deleted file mode 100644 index 0d00d8e5b9..0000000000 --- a/internal/cli/iam/teams/users/add.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const addTemplate = "User(s) added to the team.\n" - -type AddOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.TeamAdder - teamID string - users []string -} - -func (opts *AddOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *AddOpts) Run() error { - r, err := opts.store.AddUsersToTeam(opts.ConfigOrgID(), opts.teamID, opts.users) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam team(s) user(s) add [userId]... --teamId teamId --orgId orgId. -func AddBuilder() *cobra.Command { - opts := &AddOpts{} - cmd := &cobra.Command{ - Use: "add ...", - Args: require.MinimumNObjectIDArgs(1), - Short: "Add the specified MongoDB user to a team for your organization.", - Long: `Users must be current members of your organization before you can add them to a team. - -` + fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), - Annotations: map[string]string{ - "userIdDesc": "Unique 24-digit string that identifies the user. You can add more than one user at a time by specifying multiple user IDs separated by a space.", - }, - Example: fmt.Sprintf(` # Add the users with the IDs 5dd58c647a3e5a6c5bce46c7 and 5dd56c847a3e5a1f363d424d to the team with the ID 5f6a5c6c713184005d72fe6e for the organization with ID 5e2211c17a3e5a48f5497de3: - %s teams users add 5dd58c647a3e5a6c5bce46c7 5dd56c847a3e5a1f363d424d --teamId 5f6a5c6c713184005d72fe6e --orgId 5e1234c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.users = args - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), addTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.teamID, flag.TeamID, "", usage.TeamID) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.TeamID) - - return cmd -} diff --git a/internal/cli/iam/teams/users/add_test.go b/internal/cli/iam/teams/users/add_test.go deleted file mode 100644 index ba57789ca8..0000000000 --- a/internal/cli/iam/teams/users/add_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package users - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestAdd_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockTeamAdder(ctrl) - - var expected []mongodbatlas.Team - - listOpts := &AddOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - AddUsersToTeam(listOpts.OrgID, listOpts.teamID, listOpts.users). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/teams/users/delete.go b/internal/cli/iam/teams/users/delete.go deleted file mode 100644 index 8a85d6347f..0000000000 --- a/internal/cli/iam/teams/users/delete.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.TeamUserRemover - teamID string -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.RemoveUserFromTeam, opts.ConfigOrgID(), opts.teamID) -} - -// mongocli iam team(s) users(s) delete [--force] --orgId orgId --teamId teamId. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("User '%s' deleted from the team\n", "User not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified user from a team for your organization.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization User Admin"), - Args: require.ExactArgs(1), - Example: fmt.Sprintf(` # Remove the user with the ID 5dd58c647a3e5a6c5bce46c7 from the team with the ID 5f6a5c6c713184005d72fe6e for the organization with ID 5e2211c17a3e5a48f5497de3: - %s teams users delete 5dd58c647a3e5a6c5bce46c7 --teamId 5f6a5c6c713184005d72fe6e --orgId 5e1234c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "userIdDesc": "Unique 24-digit string that identifies the user.", - "output": opts.SuccessMessage(), - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.Entry = args[0] - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.Prompt, - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.teamID, flag.TeamID, "", usage.TeamID) - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - _ = cmd.MarkFlagRequired(flag.TeamID) - - return cmd -} diff --git a/internal/cli/iam/teams/users/delete_test.go b/internal/cli/iam/teams/users/delete_test.go deleted file mode 100644 index 5d7706ced1..0000000000 --- a/internal/cli/iam/teams/users/delete_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package users - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockTeamUserRemover(ctrl) - - opts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - teamID: "213123", - GlobalOpts: cli.GlobalOpts{ - OrgID: "2a0a1e7e0f2912c554080adc", - }, - } - - mockStore. - EXPECT(). - RemoveUserFromTeam(opts.OrgID, opts.teamID, opts.Entry). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/teams/users/list.go b/internal/cli/iam/teams/users/list.go deleted file mode 100644 index 50dbaa8238..0000000000 --- a/internal/cli/iam/teams/users/list.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `ID FIRST NAME LAST NAME USERNAME EMAIL{{range valueOrEmptySlice .}} -{{.ID}} {{.FirstName}} {{.LastName}} {{.Username}} {{.EmailAddress}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.TeamUserLister - teamID string -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.TeamUsers(opts.ConfigOrgID(), opts.teamID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam team(s) user(s) list --orgId orgId --teamId teamId. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "Return all users for a team.", - Long: fmt.Sprintf(usage.RequiredRole, "Organization Member"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of the users for the team with the ID 5f6a5c6c713184005d72fe6e in the organization with ID 5e2211c17a3e5a48f5497de3: - %s teams users list --teamId 5f6a5c6c713184005d72fe6e --orgId 5e1234c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.teamID, flag.TeamID, "", usage.TeamID) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.TeamID) - - return cmd -} diff --git a/internal/cli/iam/teams/users/list_test.go b/internal/cli/iam/teams/users/list_test.go deleted file mode 100644 index d0f8d66f35..0000000000 --- a/internal/cli/iam/teams/users/list_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package users - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockTeamUserLister(ctrl) - - var expected []mongodbatlas.Team - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - TeamUsers(listOpts.OrgID, listOpts.teamID). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/teams/users/users.go b/internal/cli/iam/teams/users/users.go deleted file mode 100644 index 835e02dcf8..0000000000 --- a/internal/cli/iam/teams/users/users.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "users" - cmd := &cobra.Command{ - Use: use, - Short: fmt.Sprintf("Manage your %s users.", cli.DescriptionServiceName()), - Long: "Create, list and manage your users.", - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - ListBuilder(), - AddBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/iam/users/delete.go b/internal/cli/iam/users/delete.go deleted file mode 100644 index e09f272901..0000000000 --- a/internal/cli/iam/users/delete.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.UserDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteUser) -} - -// mongocli iam users(s) delete [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("User '%s' deleted\n", "User not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified Ops Manager user.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "userIdDesc": "Unique 24-digit string that identifies the user in Ops Manager.", - "output": opts.SuccessMessage(), - }, - Example: ` # Remove the Ops Manager user with the ID 5e44445ef10fab20b49c0f31: - mongocli iam users delete 5e44445ef10fab20b49c0f31`, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/iam/users/delete_test.go b/internal/cli/iam/users/delete_test.go deleted file mode 100644 index 997ce53986..0000000000 --- a/internal/cli/iam/users/delete_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package users - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockUserDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteUser(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - opts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator(t, - DeleteBuilder(), - 0, - []string{ - flag.Force, - }, - ) -} diff --git a/internal/cli/iam/users/describe.go b/internal/cli/iam/users/describe.go deleted file mode 100644 index 9d060f7263..0000000000 --- a/internal/cli/iam/users/describe.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - "errors" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/prerun" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const describeTemplate = `ID FIRST NAME LAST NAME USERNAME EMAIL -{{.ID}} {{.FirstName}} {{.LastName}} {{.Username}} {{.EmailAddress}} -` - -type DescribeOpts struct { - cli.OutputOpts - store store.UserDescriber - username string - id string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - var r interface{} - var err error - - if opts.username != "" { - r, err = opts.store.UserByName(opts.username) - } - - if opts.id != "" { - r, err = opts.store.UserByID(opts.id) - } - - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *DescribeOpts) validate() error { - if opts.id == "" && opts.username == "" { - return errors.New("must supply one of 'id' or 'username'") - } - - if opts.id != "" && opts.username != "" { - return errors.New("cannot supply both 'id' and 'username'") - } - - return nil -} - -// mongocli iam user(s) describe --id id --username USERNAME. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe", - Aliases: []string{"get"}, - Annotations: map[string]string{"output": describeTemplate}, - Example: fmt.Sprintf(` # Return the JSON-formatted details for the MongoDB user with the ID 5dd56c847a3e5a1f363d424d: - %[1]s users describe --id 5dd56c847a3e5a1f363d424d --output json - - # Return the JSON-formatted details for the MongoDB user with the username myUser: - %[1]s users describe --username myUser --output json`, cli.ExampleAtlasEntryPoint()), - Short: "Return the details for the specified MongoDB user.", - Long: `You can specify either the unique 24-digit ID that identifies the MongoDB user or the username for the MongoDB user. - -User accounts and API keys with any role can run this command.`, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return prerun.ExecuteE( - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - opts.validate, - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.username, flag.Username, "", usage.Username) - cmd.Flags().StringVar(&opts.id, flag.ID, "", usage.UserID) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/iam/users/describe_test.go b/internal/cli/iam/users/describe_test.go deleted file mode 100644 index a3f99543da..0000000000 --- a/internal/cli/iam/users/describe_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package users - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestDescribe_Run_ByID(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockUserDescriber(ctrl) - - var expected mongodbatlas.AtlasUser - - descOpts := &DescribeOpts{ - store: mockStore, - id: "id", - } - - mockStore. - EXPECT(). - UserByID(descOpts.id). - Return(expected, nil). - Times(1) - - if err := descOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribe_Run_ByName(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockUserDescriber(ctrl) - - var expected mongodbatlas.AtlasUser - - descOpts := &DescribeOpts{ - store: mockStore, - username: "test", - } - - mockStore. - EXPECT(). - UserByName(descOpts.username). - Return(expected, nil). - Times(1) - - if err := descOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/iam/users/invite.go b/internal/cli/iam/users/invite.go deleted file mode 100644 index 2b84b25237..0000000000 --- a/internal/cli/iam/users/invite.go +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "context" - "fmt" - "strings" - - "github.com/AlecAivazis/survey/v2" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/prerun" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -var inviteTemplate = "The user '{{.Username}}' has been invited.\nInvited users do not have access to the project until they accept the invitation.\n" - -type InviteOpts struct { - cli.OutputOpts - cli.InputOpts - username string - password string - country string - email string - mobile string - firstName string - lastName string - orgRoles []string - projectRoles []string - store store.UserCreator -} - -func (opts *InviteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *InviteOpts) newUserRequest() (*store.UserRequest, error) { - atlasRoles, err := opts.createAtlasRole() - if err != nil { - return nil, err - } - - userRoles, err := opts.createUserRole() - if err != nil { - return nil, err - } - - user := &store.UserRequest{ - AtlasRoles: atlasRoles, - User: &opsmngr.User{ - Username: opts.username, - Password: opts.password, - FirstName: opts.firstName, - LastName: opts.lastName, - EmailAddress: opts.email, - MobileNumber: opts.mobile, - Country: opts.country, - Roles: userRoles, - }, - } - - return user, nil -} - -func (opts *InviteOpts) Run() error { - user, err := opts.newUserRequest() - if err != nil { - return err - } - - r, err := opts.store.CreateUser(user) - if err != nil { - return err - } - - return opts.Print(r) -} - -const keyParts = 2 - -func (opts *InviteOpts) createAtlasRole() ([]atlas.AtlasRole, error) { - if !config.IsCloud() { - return nil, nil - } - - atlasRoles := make([]atlas.AtlasRole, len(opts.orgRoles)+len(opts.projectRoles)) - - i := 0 - for _, role := range opts.orgRoles { - atlasRole, err := newAtlasOrgRole(role) - if err != nil { - return nil, err - } - atlasRoles[i] = atlasRole - i++ - } - - for _, role := range opts.projectRoles { - atlasRole, err := newAtlasProjectRole(role) - if err != nil { - return nil, err - } - atlasRoles[i] = atlasRole - i++ - } - - return atlasRoles, nil -} - -func (opts *InviteOpts) createUserRole() ([]*opsmngr.UserRole, error) { - if config.IsCloud() { - return nil, nil - } - - roles := make([]*opsmngr.UserRole, len(opts.orgRoles)+len(opts.projectRoles)) - - i := 0 - for _, role := range opts.orgRoles { - userRole, err := newUserOrgRole(role) - if err != nil { - return nil, err - } - roles[i] = userRole - i++ - } - - for _, role := range opts.projectRoles { - userRole, err := newUserProjectRole(role) - if err != nil { - return nil, err - } - roles[i] = userRole - i++ - } - - return roles, nil -} - -func (opts *InviteOpts) Prompt() error { - if opts.password != "" { - return nil - } - - if !opts.IsTerminalInput() { - _, err := fmt.Fscanln(opts.InReader, &opts.password) - return err - } - - prompt := &survey.Password{ - Message: "Password:", - } - return telemetry.TrackAskOne(prompt, &opts.password) -} - -func splitRole(role string) ([]string, error) { - value := strings.Split(role, ":") - if len(value) != keyParts { - return nil, fmt.Errorf("unexpected role format: %s", role) - } - return value, nil -} - -func newUserOrgRole(role string) (*opsmngr.UserRole, error) { - value, err := splitRole(role) - if err != nil { - return nil, err - } - userRole := &opsmngr.UserRole{ - OrgID: value[0], - RoleName: strings.ToUpper(value[1]), - } - - return userRole, nil -} - -func newUserProjectRole(role string) (*opsmngr.UserRole, error) { - value, err := splitRole(role) - if err != nil { - return nil, err - } - userRole := &opsmngr.UserRole{ - GroupID: value[0], - RoleName: strings.ToUpper(value[1]), - } - - return userRole, nil -} - -func newAtlasProjectRole(role string) (atlas.AtlasRole, error) { - value, err := splitRole(role) - if err != nil { - return atlas.AtlasRole{}, err - } - atlasRole := atlas.AtlasRole{ - GroupID: value[0], - RoleName: strings.ToUpper(value[1]), - } - - return atlasRole, nil -} - -func newAtlasOrgRole(role string) (atlas.AtlasRole, error) { - value, err := splitRole(role) - if err != nil { - return atlas.AtlasRole{}, err - } - atlasRole := atlas.AtlasRole{ - OrgID: value[0], - RoleName: strings.ToUpper(value[1]), - } - return atlasRole, nil -} - -// mongocli iam users(s) invite --username username --password password --country country --email email -// --mobile mobile --firstName firstName --lastName lastName --team team1,team2 --orgRoles orgID:ROLE_NAME -// --projectRoles projectID:ROLE_NAME - -func InviteBuilder() *cobra.Command { - opts := &InviteOpts{} - opts.Template = inviteTemplate - cmd := &cobra.Command{ - Use: "invite", - Short: "Create a MongoDB user for your MongoDB application and invite the MongoDB user to your organizations and projects.", - Long: fmt.Sprintf(`A MongoDB user account grants access only to the the MongoDB application. To grant database access, create a database user with %s dbusers create.`, cli.ExampleAtlasEntryPoint()), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Create the MongoDB user with the username user@example.com and invite them to the organization with the ID 5dd56c847a3e5a1f363d424d with ORG_OWNER access: - %[1]s users invite --email user@example.com --username user@example.com --orgRole 5dd56c847a3e5a1f363d424d:ORG_OWNER --firstName Example --lastName User --country US --output json - - # Create the MongoDB user with the username user@example.com and invite them to the project with the ID 5f71e5255afec75a3d0f96dc with GROUP_READ_ONLY access: - %[1]s users invite --email user@example.com --username user@example.com --projectRole 5f71e5255afec75a3d0f96dc:GROUP_READ_ONLY --firstName Example --lastName User --country US --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - if config.Service() != config.OpsManagerService { - _ = cmd.MarkFlagRequired(flag.Country) - } - - return prerun.ExecuteE(opts.InitOutput(cmd.OutOrStdout(), ""), opts.InitInput(cmd.InOrStdin()), opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, _ []string) error { - if err := opts.Prompt(); err != nil { - return err - } - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.username, flag.Username, "", usage.Username) - cmd.Flags().StringVar(&opts.password, flag.Password, "", usage.Password) - cmd.Flags().StringVar(&opts.country, flag.Country, "", usage.Country) - cmd.Flags().StringVar(&opts.email, flag.Email, "", usage.Email) - cmd.Flags().StringVar(&opts.mobile, flag.Mobile, "", usage.Mobile) - cmd.Flags().StringVar(&opts.firstName, flag.FirstName, "", usage.FirstName) - cmd.Flags().StringVar(&opts.lastName, flag.LastName, "", usage.LastName) - if config.BinName() == config.MongoCLI { - cmd.Flags().StringSliceVar(&opts.orgRoles, flag.OrgRole, []string{}, usage.MCLIUserOrgRole) - cmd.Flags().StringSliceVar(&opts.projectRoles, flag.ProjectRole, []string{}, usage.MCLIUserProjectRole) - } else { - cmd.Flags().StringSliceVar(&opts.orgRoles, flag.OrgRole, []string{}, usage.UserOrgRole) - cmd.Flags().StringSliceVar(&opts.projectRoles, flag.ProjectRole, []string{}, usage.UserProjectRole) - } - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Username) - _ = cmd.MarkFlagRequired(flag.Email) - _ = cmd.MarkFlagRequired(flag.FirstName) - _ = cmd.MarkFlagRequired(flag.LastName) - - return cmd -} diff --git a/internal/cli/iam/users/invite_test.go b/internal/cli/iam/users/invite_test.go deleted file mode 100644 index 511598d35d..0000000000 --- a/internal/cli/iam/users/invite_test.go +++ /dev/null @@ -1,241 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package users - -import ( - "bytes" - "reflect" - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/stretchr/testify/require" - "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestInvite_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockUserCreator(ctrl) - - expected := &mongodbatlas.AtlasUser{ - Username: "testUser", - } - opts := &InviteOpts{ - store: mockStore, - username: "testUser", - } - - user, err := opts.newUserRequest() - if err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - mockStore. - EXPECT(). - CreateUser(user). - Return(expected, nil). - Times(1) - - if err = opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateAtlasRole(t *testing.T) { - type test struct { - name string - input InviteOpts - want []mongodbatlas.AtlasRole - } - - tests := []test{ - { - name: "one role", - input: InviteOpts{ - orgRoles: []string{"5e4e593f70dfbf1010295836:ORG_OWNER"}, - }, - want: []mongodbatlas.AtlasRole{{ - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_OWNER", - }}, - }, - { - name: "multple roles", - input: InviteOpts{ - orgRoles: []string{"5e4e593f70dfbf1010295836:ORG_OWNER", "5e4e593f70dfbf1010295836:ORG_GROUP_CREATOR"}, - }, - want: []mongodbatlas.AtlasRole{ - { - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_OWNER", - }, - { - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_GROUP_CREATOR", - }, - }, - }, - { - name: "org and project roles", - input: InviteOpts{ - orgRoles: []string{"5e4e593f70dfbf1010295836:ORG_OWNER", "5e4e593f70dfbf1010295836:ORG_GROUP_CREATOR"}, - projectRoles: []string{"5e4e593f70dfbf1010295836:GROUP_OWNER", "5e4e593f70dfbf1010295836:GROUP_CLUSTER_MANAGER"}, - }, - want: []mongodbatlas.AtlasRole{ - { - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_OWNER", - }, - { - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_GROUP_CREATOR", - }, - { - GroupID: "5e4e593f70dfbf1010295836", - RoleName: "GROUP_OWNER", - }, - { - GroupID: "5e4e593f70dfbf1010295836", - RoleName: "GROUP_CLUSTER_MANAGER", - }, - }, - }, - { - name: "empty", - input: InviteOpts{}, - want: []mongodbatlas.AtlasRole{}, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - got, err := tc.input.createAtlasRole() - if err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - - if !reflect.DeepEqual(tc.want, got) { - t.Fatalf("expected: %v, got: %v", tc.want, got) - } - }) - } -} - -func TestCreateUserRole(t *testing.T) { - type test struct { - name string - input InviteOpts - want []*opsmngr.UserRole - } - prevServ := config.Service() - config.SetService(config.OpsManagerService) - defer func() { - config.SetService(prevServ) - }() - - tests := []test{ - { - name: "one role", - input: InviteOpts{ - orgRoles: []string{"5e4e593f70dfbf1010295836:ORG_OWNER"}, - }, - want: []*opsmngr.UserRole{{ - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_OWNER", - }}, - }, - { - name: "multiple org roles", - input: InviteOpts{ - orgRoles: []string{"5e4e593f70dfbf1010295836:ORG_OWNER", "5e4e593f70dfbf1010295836:ORG_GROUP_CREATOR"}, - }, - want: []*opsmngr.UserRole{ - { - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_OWNER", - }, - { - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_GROUP_CREATOR", - }, - }, - }, - { - name: "projects and orgs", - input: InviteOpts{ - orgRoles: []string{"5e4e593f70dfbf1010295836:ORG_OWNER", "5e4e593f70dfbf1010295836:ORG_GROUP_CREATOR"}, - projectRoles: []string{"5e4e593f70dfbf1010295836:GROUP_OWNER", "5e4e593f70dfbf1010295836:GROUP_CLUSTER_MANAGER"}, - }, - want: []*opsmngr.UserRole{ - { - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_OWNER", - }, - { - OrgID: "5e4e593f70dfbf1010295836", - RoleName: "ORG_GROUP_CREATOR", - }, - { - GroupID: "5e4e593f70dfbf1010295836", - RoleName: "GROUP_OWNER", - }, - { - GroupID: "5e4e593f70dfbf1010295836", - RoleName: "GROUP_CLUSTER_MANAGER", - }, - }, - }, - { - name: "empty", - input: InviteOpts{}, - want: []*opsmngr.UserRole{}, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - got, err := tc.input.createUserRole() - if err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - - if !reflect.DeepEqual(tc.want, got) { - t.Fatalf("expected: %v, got: %v", tc.want, got) - } - }) - } -} - -func TestNewUserRequestWithPasswordStin(t *testing.T) { - password := "p@ssw0rd" - opts := &InviteOpts{ - username: "testUser", - } - - require.NoError(t, opts.InitInput(bytes.NewReader([]byte(password)))()) - require.NoError(t, opts.Prompt()) - - user, err := opts.newUserRequest() - if err != nil { - t.Fatalf("newUserRequest() unexpected error: %v", err) - } - - if user.Password != password { - t.Fatalf("failed to read password from stream") - } -} diff --git a/internal/cli/iam/users/users.go b/internal/cli/iam/users/users.go deleted file mode 100644 index a7f6a45b52..0000000000 --- a/internal/cli/iam/users/users.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package users - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - description := "Create, list and manage your Cloud Manager or Ops Manager users." - - const use = "users" - cmd := &cobra.Command{ - Use: use, - Short: fmt.Sprintf("Manage your %s users.", cli.DescriptionServiceName()), - Long: description, - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - InviteBuilder(), - DescribeBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/acknowledge.go b/internal/cli/mongocli/alerts/acknowledge.go deleted file mode 100644 index 2885dd69aa..0000000000 --- a/internal/cli/mongocli/alerts/acknowledge.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package alerts - -import ( - "context" - "fmt" - "time" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type AcknowledgeOpts struct { - cli.GlobalOpts - cli.OutputOpts - alertID string - until string - comment string - forever bool - store store.AlertAcknowledger -} - -func (opts *AcknowledgeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var ackTemplate = "Alert '{{.ID}}' acknowledged until {{.AcknowledgedUntil}}\n" - -func (opts *AcknowledgeOpts) Run() error { - body := opts.newAcknowledgeRequest() - r, err := opts.store.AcknowledgeAlert(opts.ConfigProjectID(), opts.alertID, body) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *AcknowledgeOpts) newAcknowledgeRequest() *atlas.AcknowledgeRequest { - if opts.forever { - // To acknowledge an alert “forever”, set the field value to 100 years in the future. - const years = 100 - opts.until = time.Now().AddDate(years, 1, 1).Format(time.RFC3339) - } - - return &atlas.AcknowledgeRequest{ - AcknowledgedUntil: &opts.until, - AcknowledgementComment: opts.comment, - } -} - -// mongocli atlas alerts acknowledge --projectId projectId --forever --comment comment --until until. -func AcknowledgeBuilder() *cobra.Command { - opts := new(AcknowledgeOpts) - opts.Template = ackTemplate - cmd := &cobra.Command{ - Use: "acknowledge ", - Short: "Acknowledges the specified alert for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Aliases: []string{"ack"}, - Args: require.ExactArgs(1), - PreRunE: func(cmd *cobra.Command, _ []string) error { - if opts.forever && opts.until != "" { - return fmt.Errorf("--%s and --%s are exclusive", flag.Forever, flag.Until) - } - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), ackTemplate), - ) - }, - Annotations: map[string]string{ - "alertIdDesc": "ID of the alert you want to acknowledge or unacknowledge.", - }, - Example: fmt.Sprintf(` # Acknowledge an alert with the ID 5d1113b25a115342acc2d1aa in the project with the ID 5e2211c17a3e5a48f5497de3 until January 1 2028: - %s alerts acknowledge 5d1113b25a115342acc2d1aa --until 2028-01-01T20:24:26Z --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - RunE: func(_ *cobra.Command, args []string) error { - opts.alertID = args[0] - return opts.Run() - }, - } - cmd.OutOrStdout() - cmd.Flags().BoolVarP(&opts.forever, flag.Forever, flag.ForeverShort, false, usage.Forever) - cmd.Flags().StringVar(&opts.until, flag.Until, "", usage.Until) - cmd.Flags().StringVar(&opts.comment, flag.Comment, "", usage.Comment) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/acknowledge_test.go b/internal/cli/mongocli/alerts/acknowledge_test.go deleted file mode 100644 index 4d46edde82..0000000000 --- a/internal/cli/mongocli/alerts/acknowledge_test.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package alerts - -import ( - "errors" - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/stretchr/testify/require" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestAcknowledgeBuilder(t *testing.T) { - test.CmdValidator( - t, - AcknowledgeBuilder(), - 0, - []string{ - flag.Forever, - flag.Until, - flag.Comment, - flag.ProjectID, - flag.Output, - }, - ) -} - -func TestAcknowledgeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertAcknowledger(ctrl) - - tests := []struct { - name string - opts AcknowledgeOpts - wantErr bool - }{ - { - name: "default", - opts: AcknowledgeOpts{ - alertID: "533dc40ae4b00835ff81eaee", - comment: "Test", - store: mockStore, - }, - wantErr: false, - }, - { - name: "forever", - opts: AcknowledgeOpts{ - alertID: "533dc40ae4b00835ff81eaee", - comment: "Test", - forever: true, - store: mockStore, - }, - wantErr: false, - }, - { - name: "with error", - opts: AcknowledgeOpts{ - alertID: "533dc40ae4b00835ff81eaee", - comment: "Test", - forever: true, - store: mockStore, - }, - wantErr: true, - }, - } - for _, tt := range tests { - opts := tt.opts - wantErr := tt.wantErr - t.Run(tt.name, func(t *testing.T) { - ackReq := opts.newAcknowledgeRequest() - if wantErr { - mockStore. - EXPECT(). - AcknowledgeAlert(opts.ProjectID, opts.alertID, ackReq). - Return(nil, errors.New("fake")). - Times(1) - require.Error(t, opts.Run()) - } else { - expected := &mongodbatlas.Alert{} - mockStore. - EXPECT(). - AcknowledgeAlert(opts.ProjectID, opts.alertID, ackReq). - Return(expected, nil). - Times(1) - require.NoError(t, opts.Run()) - } - }) - } -} diff --git a/internal/cli/mongocli/alerts/alerts.go b/internal/cli/mongocli/alerts/alerts.go deleted file mode 100644 index cff8bc9972..0000000000 --- a/internal/cli/mongocli/alerts/alerts.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package alerts - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/alerts/settings" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "alerts" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage alerts for your project.", - } - - cmd.AddCommand( - settings.Builder(), - DescribeBuilder(), - ListBuilder(), - AcknowledgeBuilder(), - UnacknowledgeBuilder(), - GlobalBuilder(), - ) - - return cmd -} - -func GlobalBuilder() *cobra.Command { - cmd := &cobra.Command{ - Use: "global", - Short: "Retrieves all the global alerts for the specified Ops Manager project.", - } - - cmd.AddCommand(GlobalListBuilder()) - return cmd -} diff --git a/internal/cli/mongocli/alerts/alerts_test.go b/internal/cli/mongocli/alerts/alerts_test.go deleted file mode 100644 index 06c5f5e075..0000000000 --- a/internal/cli/mongocli/alerts/alerts_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package alerts - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 6, - []string{}, - ) -} - -func TestGlobalBuilder(t *testing.T) { - test.CmdValidator( - t, - GlobalBuilder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/mongocli/alerts/describe.go b/internal/cli/mongocli/alerts/describe.go deleted file mode 100644 index 3cef458327..0000000000 --- a/internal/cli/mongocli/alerts/describe.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package alerts - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - alertID string - store store.AlertDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var describeTemplate = `ID TYPE METRIC STATUS -{{.ID}} {{.EventTypeName}} {{.MetricName}} {{.Status}} -` - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.Alert(opts.ConfigProjectID(), opts.alertID) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas alerts describe --projectId projectId. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Short: "Return the details for the specified alert for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "alertIdDesc": "Unique identifier of the alert you want to describe.", - "output": describeTemplate, - }, - Example: fmt.Sprintf(` # Return the JSON-formatted details for the alert with the ID 5d1113b25a115342acc2d1aa in the project with the ID 5e2211c17a3e5a48f5497de3: - %s alerts describe 5d1113b25a115342acc2d1aa --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.alertID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/describe_test.go b/internal/cli/mongocli/alerts/describe_test.go deleted file mode 100644 index f21ca5ef89..0000000000 --- a/internal/cli/mongocli/alerts/describe_test.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package alerts - -import ( - "bytes" - "errors" - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{ - flag.ProjectID, - flag.Output, - }, - ) -} - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertDescriber(ctrl) - - expected := &mongodbatlas.Alert{ - ID: "test", - EventTypeName: "test", - Status: "test", - MetricName: "test", - } - buf := new(bytes.Buffer) - - tests := []struct { - name string - cmd *DescribeOpts - wantErr bool - }{ - { - name: "default", - cmd: &DescribeOpts{ - OutputOpts: cli.OutputOpts{ - Template: describeTemplate, - OutWriter: buf, - }, - alertID: "533dc40ae4b00835ff81eaee", - store: mockStore, - }, - - wantErr: false, - }, - { - name: "default", - cmd: &DescribeOpts{ - alertID: "533dc40ae4b00835ff81eaee", - store: mockStore, - OutputOpts: cli.OutputOpts{ - Template: describeTemplate, - OutWriter: buf, - }, - }, - wantErr: true, - }, - } - for _, tt := range tests { - cmd := tt.cmd - wantErr := tt.wantErr - t.Run(tt.name, func(t *testing.T) { - if wantErr { - mockStore. - EXPECT(). - Alert(cmd.ProjectID, cmd.alertID). - Return(nil, errors.New("fake")). - Times(1) - require.Error(t, cmd.Run()) - } else { - mockStore. - EXPECT(). - Alert(cmd.ProjectID, cmd.alertID). - Return(expected, nil). - Times(1) - require.NoError(t, cmd.Run()) - assert.Equal(t, `ID TYPE METRIC STATUS -test test test test -`, buf.String()) - t.Log(buf.String()) - } - }) - } -} diff --git a/internal/cli/mongocli/alerts/global_list.go b/internal/cli/mongocli/alerts/global_list.go deleted file mode 100644 index 55b7a7bb26..0000000000 --- a/internal/cli/mongocli/alerts/global_list.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package alerts - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type GlobalListOpts struct { - cli.ListOpts - cli.OutputOpts - status string - store store.GlobalAlertLister -} - -func (opts *GlobalListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *GlobalListOpts) Run() error { - alertOpts := opts.newAlertsListOptions() - r, err := opts.store.GlobalAlerts(alertOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *GlobalListOpts) newAlertsListOptions() *atlas.AlertsListOptions { - return &atlas.AlertsListOptions{ - Status: opts.status, - ListOptions: *opts.NewListOptions(), - } -} - -// mongocli om|cm alert(s) global list [--status status]. -func GlobalListBuilder() *cobra.Command { - opts := &GlobalListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Short: "Returns all global alerts for the specified Ops Manager project.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - cmd.Flags().StringVar(&opts.status, flag.Status, "", usage.Status) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/global_list_test.go b/internal/cli/mongocli/alerts/global_list_test.go deleted file mode 100644 index 7ed47da7a1..0000000000 --- a/internal/cli/mongocli/alerts/global_list_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package alerts - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestGlobalList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockGlobalAlertLister(ctrl) - - expected := &opsmngr.GlobalAlerts{} - - opts := &GlobalListOpts{ - store: mockStore, - status: "OPEN", - } - - mockStore. - EXPECT().GlobalAlerts(opts.newAlertsListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - test.VerifyOutputTemplate(t, listTemplate, expected) -} diff --git a/internal/cli/mongocli/alerts/list.go b/internal/cli/mongocli/alerts/list.go deleted file mode 100644 index b3d1345631..0000000000 --- a/internal/cli/mongocli/alerts/list.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package alerts - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - status string - store store.AlertLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `ID TYPE STATUS{{range valueOrEmptySlice .Results}} -{{.ID}} {{.EventTypeName}} {{.Status}}{{end}} -` - -func (opts *ListOpts) Run() error { - listOpts := opts.newAlertsListOptions() - r, err := opts.store.Alerts(opts.ConfigProjectID(), listOpts) - - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *ListOpts) newAlertsListOptions() *atlas.AlertsListOptions { - o := &atlas.AlertsListOptions{ - Status: opts.status, - ListOptions: *opts.NewListOptions(), - } - - return o -} - -// mongocli atlas alerts list [--status status] [--projectId projectId] [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list", - Short: "Return all alerts for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Example: fmt.Sprintf(` # Return a JSON-formatted list of all alerts for the project with the ID 5e2211c17a3e5a48f5497de3: - %s alerts list --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - Aliases: []string{"ls"}, - Annotations: map[string]string{ - "output": listTemplate, - }, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - cmd.Flags().StringVar(&opts.status, flag.Status, "", usage.Status) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - return cmd -} diff --git a/internal/cli/mongocli/alerts/list_test.go b/internal/cli/mongocli/alerts/list_test.go deleted file mode 100644 index c2e4a28c93..0000000000 --- a/internal/cli/mongocli/alerts/list_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package alerts - -import ( - "bytes" - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertLister(ctrl) - - expected := &mongodbatlas.AlertsResponse{ - Links: nil, - Results: []mongodbatlas.Alert{ - { - ID: "test", - EventTypeName: "test", - Status: "test", - MetricName: "test"}, - }, - TotalCount: 0, - } - - buf := new(bytes.Buffer) - - listOpts := &ListOpts{ - store: mockStore, - status: "OPEN", - OutputOpts: cli.OutputOpts{ - Template: listTemplate, - OutWriter: buf, - }, - } - - mockStore. - EXPECT(). - Alerts(listOpts.ProjectID, listOpts.newAlertsListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - - assert.Equal(t, `ID TYPE STATUS -test test test -`, buf.String()) - t.Log(buf.String()) -} diff --git a/internal/cli/mongocli/alerts/settings/create.go b/internal/cli/mongocli/alerts/settings/create.go deleted file mode 100644 index e930314044..0000000000 --- a/internal/cli/mongocli/alerts/settings/create.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - ConfigOpts - store store.AlertConfigurationCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var createTemplate = "Alert configuration {{.ID}} created.\n" - -func (opts *CreateOpts) Run() error { - alert := opts.NewAlertConfiguration(opts.ConfigProjectID()) - r, err := opts.store.CreateAlertConfiguration(alert) - if err != nil { - return err - } - - return opts.Print(r) -} - -// CreateBuilder mongocli atlas alerts config(s) create -// -// [--event event] -// [--enabled enabled] -// [--matcherField fieldName --matcherOperator operator --matcherValue value] -// [--notificationType type --notificationDelayMin min --notificationEmailEnabled --notificationSmsEnabled --notificationUsername username --notificationTeamID id -// [--notificationEmailAddress email --notificationMobileNumber number --notificationChannelName channel --notificationApiToken --notificationRegion region] -// [--projectId projectId]. -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "create", - Short: "Create an alert configuration for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Annotations: map[string]string{ - "output": createTemplate, - }, - Example: fmt.Sprintf(` # Create an alert configuration that notifies a user when they join a group for the project with the ID 5df90590f10fab5e33de2305: - %s alerts settings create --event JOINED_GROUP --enabled \ - --notificationType USER --notificationEmailEnabled \ - --notificationUsername john@example.com \ - --output json --projectId 5df90590f10fab5e33de2305`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.event, flag.Event, "", usage.EventCMOM) - cmd.Flags().BoolVar(&opts.enabled, flag.Enabled, false, usage.Enabled) - cmd.Flags().StringVar(&opts.matcherFieldName, flag.MatcherFieldName, "", usage.MCLIMatcherFieldName) - cmd.Flags().StringVar(&opts.matcherOperator, flag.MatcherOperator, "", usage.MatcherOperator) - cmd.Flags().StringVar(&opts.matcherValue, flag.MatcherValue, "", usage.MatcherValue) - cmd.Flags().StringVar(&opts.metricThresholdMetricName, flag.MetricName, "", usage.MetricName) - cmd.Flags().StringVar(&opts.metricThresholdOperator, flag.MetricOperator, "", usage.MetricOperator) - cmd.Flags().Float64Var(&opts.metricThresholdThreshold, flag.MetricThreshold, 0, usage.MetricThreshold) - cmd.Flags().StringVar(&opts.metricThresholdUnits, flag.MetricUnits, "", usage.MetricUnits) - cmd.Flags().StringVar(&opts.metricThresholdMode, flag.MetricMode, "", usage.MetricMode) - cmd.Flags().StringVar(&opts.notificationToken, flag.NotificationToken, "", usage.NotificationToken) - cmd.Flags().StringVar(&opts.notificationChannelName, flag.NotificationChannelName, "", usage.NotificationsChannelName) - cmd.Flags().StringVar(&opts.apiKey, flag.APIKey, "", usage.AlertConfigAPIKey) - cmd.Flags().StringVar(&opts.notificationRegion, flag.NotificationRegion, "", usage.NotificationRegion) - cmd.Flags().IntVar(&opts.notificationDelayMin, flag.NotificationDelayMin, 0, usage.NotificationDelayMin) - cmd.Flags().StringVar(&opts.notificationEmailAddress, flag.NotificationEmailAddress, "", usage.NotificationEmailAddress) - cmd.Flags().BoolVar(&opts.notificationEmailEnabled, flag.NotificationEmailEnabled, false, usage.NotificationEmailEnabled) - cmd.Flags().IntVar(&opts.notificationIntervalMin, flag.NotificationIntervalMin, 0, usage.NotificationIntervalMin) - cmd.Flags().StringVar(&opts.notificationMobileNumber, flag.NotificationMobileNumber, "", usage.NotificationMobileNumber) - cmd.Flags().StringVar(&opts.notificationServiceKey, flag.NotificationServiceKey, "", usage.NotificationServiceKey) - cmd.Flags().BoolVar(&opts.notificationSmsEnabled, flag.NotificationSmsEnabled, false, usage.NotificationSmsEnabled) - cmd.Flags().StringVar(&opts.notificationTeamID, flag.NotificationTeamID, "", usage.NotificationTeamID) - cmd.Flags().StringVar(&opts.notificationType, flag.NotificationType, "", usage.NotificationType) - cmd.Flags().StringVar(&opts.notificationUsername, flag.NotificationUsername, "", usage.NotificationUsername) - cmd.Flags().StringVar(&opts.notificationVictorOpsRoutingKey, flag.NotificationVictorOpsRoutingKey, "", usage.NotificationVictorOpsRoutingKey) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/create_test.go b/internal/cli/mongocli/alerts/settings/create_test.go deleted file mode 100644 index cdfb54064b..0000000000 --- a/internal/cli/mongocli/alerts/settings/create_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package settings - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertConfigurationCreator(ctrl) - - expected := &mongodbatlas.AlertConfiguration{} - - createOpts := &CreateOpts{ - ConfigOpts: ConfigOpts{ - event: "OUTSIDE_METRIC_THRESHOLD", - enabled: true, - matcherFieldName: "HOSTNAME_AND_PORT", - matcherOperator: "EQUALS", - matcherValue: "mongo.example.com:27017", - metricThresholdMetricName: "ASSERT_REGULAR", - metricThresholdOperator: "LESS_THAN", - metricThresholdThreshold: 99, - metricThresholdUnits: "RAW", - metricThresholdMode: "RAW", - notificationDelayMin: 0, - notificationIntervalMin: 5, - notificationMobileNumber: "2343454567", - notificationType: "sms", - }, - store: mockStore} - - alert := createOpts.NewAlertConfiguration(createOpts.ConfigProjectID()) - mockStore. - EXPECT(). - CreateAlertConfiguration(alert). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestAcknowledgeBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{ - flag.Event, - flag.Enabled, - flag.MatcherFieldName, - flag.MatcherOperator, - flag.Output, - }, - ) -} diff --git a/internal/cli/mongocli/alerts/settings/delete.go b/internal/cli/mongocli/alerts/settings/delete.go deleted file mode 100644 index 4e4cc16b96..0000000000 --- a/internal/cli/mongocli/alerts/settings/delete.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.AlertConfigurationDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteAlertConfiguration, opts.ConfigProjectID()) -} - -// mongocli atlas alerts config(s) delete --projectId projectId [--confirm]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Alert config '%s' deleted\n", "Alert config not deleted"), - } - - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified alert configuration for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "alertConfigIdDesc": "Unique identifier of the alert configuration to delete.", - "output": opts.SuccessMessage(), - }, - Example: fmt.Sprintf(` # Remove the alert configuration with the ID 5d1113b25a115342acc2d1aa in the project with the ID 5e2211c17a3e5a48f5497de3: - %s alerts settings delete 5d1113b25a115342acc2d1aa --projectId 5e2211c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/delete_test.go b/internal/cli/mongocli/alerts/settings/delete_test.go deleted file mode 100644 index d6ed199dc9..0000000000 --- a/internal/cli/mongocli/alerts/settings/delete_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package settings - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestConfigsDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertConfigurationDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{Confirm: true, Entry: "testAlert"}, - } - - mockStore. - EXPECT(). - DeleteAlertConfiguration(deleteOpts.ProjectID, deleteOpts.Entry). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/alerts/settings/disable.go b/internal/cli/mongocli/alerts/settings/disable.go deleted file mode 100644 index 47ba26a4dc..0000000000 --- a/internal/cli/mongocli/alerts/settings/disable.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DisableOpts struct { - cli.GlobalOpts - cli.OutputOpts - alertID string - store store.AlertConfigurationDisabler -} - -func (opts *DisableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var disableTemplate = "Alert configuration '{{.ID}}' disabled\n" - -func (opts *DisableOpts) Run() error { - r, err := opts.store.DisableAlertConfiguration(opts.ConfigProjectID(), opts.alertID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas alerts disable --projectId projectId. -func DisableBuilder() *cobra.Command { - opts := new(DisableOpts) - cmd := &cobra.Command{ - Use: "disable ", - Short: "Disables one alert configuration for the specified project.", - Args: require.ExactArgs(1), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), disableTemplate), - ) - }, - Example: fmt.Sprintf(` # Disable the alert configuration with the ID 5d1113b25a115342acc2d1aa in the project with the ID 5e2211c17a3e5a48f5497de3: - %s alerts settings disable 5d1113b25a115342acc2d1aa --projectId 5e2211c17a3e5a48f5497de3`, cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "alertConfigIdDesc": "ID of the alert configuration you want to disable.", - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.alertID = args[0] - return opts.Run() - }, - } - cmd.OutOrStdout() - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/disable_test.go b/internal/cli/mongocli/alerts/settings/disable_test.go deleted file mode 100644 index 887297db48..0000000000 --- a/internal/cli/mongocli/alerts/settings/disable_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package settings - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/stretchr/testify/require" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestDisableBuilder(t *testing.T) { - test.CmdValidator( - t, - EnableBuilder(), - 0, - []string{ - flag.ProjectID, - flag.Output, - }, - ) -} - -func TestDisableOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertConfigurationDisabler(ctrl) - - opts := &DisableOpts{ - alertID: "alertID", - GlobalOpts: cli.GlobalOpts{ - ProjectID: "projectID", - }, - store: mockStore, - } - expected := &mongodbatlas.AlertConfiguration{} - mockStore. - EXPECT(). - DisableAlertConfiguration(opts.ProjectID, opts.alertID). - Return(expected, nil). - Times(1) - require.NoError(t, opts.Run()) -} diff --git a/internal/cli/mongocli/alerts/settings/enable.go b/internal/cli/mongocli/alerts/settings/enable.go deleted file mode 100644 index 5cd7d58fb0..0000000000 --- a/internal/cli/mongocli/alerts/settings/enable.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type EnableOpts struct { - cli.GlobalOpts - cli.OutputOpts - alertID string - store store.AlertConfigurationEnabler -} - -func (opts *EnableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var enableTemplate = "Alert configuration '{{.ID}}' enabled\n" - -func (opts *EnableOpts) Run() error { - r, err := opts.store.EnableAlertConfiguration(opts.ConfigProjectID(), opts.alertID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas alerts enable --projectId projectId. -func EnableBuilder() *cobra.Command { - opts := new(EnableOpts) - cmd := &cobra.Command{ - Use: "enable ", - Short: "Enables one alert configuration for the specified project.", - Args: require.ExactArgs(1), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), enableTemplate), - ) - }, - Annotations: map[string]string{ - "alertConfigIdDesc": "ID of the alert you want to enable.", - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.alertID = args[0] - return opts.Run() - }, - } - cmd.OutOrStdout() - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/enable_test.go b/internal/cli/mongocli/alerts/settings/enable_test.go deleted file mode 100644 index e3f2d8313f..0000000000 --- a/internal/cli/mongocli/alerts/settings/enable_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package settings - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/stretchr/testify/require" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestEnableBuilder(t *testing.T) { - test.CmdValidator( - t, - EnableBuilder(), - 0, - []string{ - flag.ProjectID, - flag.Output, - }, - ) -} - -func TestEnableOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertConfigurationEnabler(ctrl) - - opts := &EnableOpts{ - alertID: "alertID", - GlobalOpts: cli.GlobalOpts{ - ProjectID: "projectID", - }, - store: mockStore, - } - expected := &mongodbatlas.AlertConfiguration{} - mockStore. - EXPECT(). - EnableAlertConfiguration(opts.ProjectID, opts.alertID). - Return(expected, nil). - Times(1) - require.NoError(t, opts.Run()) -} diff --git a/internal/cli/mongocli/alerts/settings/fields.go b/internal/cli/mongocli/alerts/settings/fields.go deleted file mode 100644 index 056c20fed5..0000000000 --- a/internal/cli/mongocli/alerts/settings/fields.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func FieldsBuilder() *cobra.Command { - const use = "fields" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manages alert configuration fields for your project.", - } - - cmd.AddCommand(FieldsTypeBuilder()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/fields_type.go b/internal/cli/mongocli/alerts/settings/fields_type.go deleted file mode 100644 index 85e7438322..0000000000 --- a/internal/cli/mongocli/alerts/settings/fields_type.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type FieldsTypeOpts struct { - cli.OutputOpts - store store.MatcherFieldsLister -} - -func (opts *FieldsTypeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var matcherFieldsTemplate = "{{range valueOrEmptySlice .}}{{.}}\n{{end}}" - -func (opts *FieldsTypeOpts) Run() error { - r, err := opts.store.MatcherFields() - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas alerts config(s) fields type. -func FieldsTypeBuilder() *cobra.Command { - opts := &FieldsTypeOpts{} - opts.Template = matcherFieldsTemplate - cmd := &cobra.Command{ - Use: "type", - Short: "Return all available field types that the matcherFieldName option accepts when you create or update an alert configuration.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Aliases: []string{"types"}, - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of accepted field types for the matchersFieldName option: - %s alerts settings fields type --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/fields_type_test.go b/internal/cli/mongocli/alerts/settings/fields_type_test.go deleted file mode 100644 index 07156c28d4..0000000000 --- a/internal/cli/mongocli/alerts/settings/fields_type_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package settings - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestFieldsType_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockMatcherFieldsLister(ctrl) - - var expected []string - - listOpts := &FieldsTypeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - MatcherFields(). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - test.VerifyOutputTemplate(t, matcherFieldsTemplate, expected) -} diff --git a/internal/cli/mongocli/alerts/settings/list.go b/internal/cli/mongocli/alerts/settings/list.go deleted file mode 100644 index d994fa5a28..0000000000 --- a/internal/cli/mongocli/alerts/settings/list.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.AlertConfigurationLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var settingsListTemplate = `ID TYPE ENABLED{{range valueOrEmptySlice .}} -{{.ID}} {{.EventTypeName}} {{.Enabled}}{{end}} -` - -func (opts *ListOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.AlertConfigurations(opts.ConfigProjectID(), listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas alerts config(s) list --projectId projectId [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list", - Short: "Returns all alert configurations for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Example: fmt.Sprintf(` # Return a JSON-formatted list of all alert configurations for the project with the ID 5df90590f10fab5e33de2305: - %s alerts settings list --projectId 5df90590f10fab5e33de2305 --output json`, cli.ExampleAtlasEntryPoint()), - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), settingsListTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/list_test.go b/internal/cli/mongocli/alerts/settings/list_test.go deleted file mode 100644 index 3688c44ec0..0000000000 --- a/internal/cli/mongocli/alerts/settings/list_test.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package settings - -import ( - "bytes" - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/pointer" - "github.com/stretchr/testify/assert" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestConfigList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertConfigurationLister(ctrl) - - expected := []mongodbatlas.AlertConfiguration{ - { - ID: "test", - GroupID: "test", - AlertConfigID: "test", - EventTypeName: "test", - Created: "test", - Status: "test", - AcknowledgedUntil: "test", - AcknowledgementComment: "test", - AcknowledgingUsername: "test", - Updated: "test", - Resolved: "test", - LastNotified: "test", - HostnameAndPort: "test", - HostID: "test", - ReplicaSetName: "test", - MetricName: "test", - Enabled: pointer.Get(true), - ClusterID: "test", - ClusterName: "test", - SourceTypeName: "test", - CurrentValue: &mongodbatlas.CurrentValue{ - Number: pointer.Get(1.2), - Units: "test", - }, - Matchers: nil, - MetricThreshold: nil, - Threshold: nil, - Notifications: nil, - }, - } - - buf := new(bytes.Buffer) - - listOpts := &ListOpts{ - store: mockStore, - OutputOpts: cli.OutputOpts{ - Template: settingsListTemplate, - OutWriter: buf, - }, - } - - mockStore. - EXPECT(). - AlertConfigurations(listOpts.ProjectID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - - assert.Equal(t, `ID TYPE ENABLED -test test true -`, buf.String()) - t.Log(buf.String()) -} diff --git a/internal/cli/mongocli/alerts/settings/settings.go b/internal/cli/mongocli/alerts/settings/settings.go deleted file mode 100644 index 747096beb6..0000000000 --- a/internal/cli/mongocli/alerts/settings/settings.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "strings" - - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const ( - datadog = "DATADOG" - slack = "SLACK" - victor = "VICTOR_OPS" - email = "EMAIL" - ops = "OPS_GENIE" - pager = "PAGER_DUTY" - sms = "SMS" - group = "GROUP" - user = "USER" - org = "ORG" -) - -// ConfigOpts contains all the information and functions to manage an alert configuration. -type ConfigOpts struct { - event string - matcherFieldName string - matcherOperator string - matcherValue string - metricThresholdMetricName string - metricThresholdOperator string - metricThresholdUnits string - metricThresholdMode string - notificationToken string // notificationsApiToken, notificationsFlowdockApiToken - notificationChannelName string - apiKey string // notificationsDatadogApiKey, notificationsOpsGenieApiKey, notificationsVictorOpsApiKey - notificationEmailAddress string - notificationMobileNumber string - notificationRegion string // notificationsOpsGenieRegion, notificationsDatadogRegion - notificationServiceKey string - notificationTeamID string - notificationType string - notificationUsername string - notificationVictorOpsRoutingKey string - notificationDelayMin int - notificationIntervalMin int - notificationSmsEnabled bool - enabled bool - notificationEmailEnabled bool - metricThresholdThreshold float64 -} - -func (opts *ConfigOpts) NewAlertConfiguration(projectID string) *atlas.AlertConfiguration { - out := new(atlas.AlertConfiguration) - - out.GroupID = projectID - out.EventTypeName = strings.ToUpper(opts.event) - out.Enabled = &opts.enabled - - if opts.matcherFieldName != "" { - out.Matchers = []atlas.Matcher{*opts.newMatcher()} - } - - if opts.metricThresholdMetricName != "" { - out.MetricThreshold = opts.newMetricThreshold() - } - - out.Notifications = []atlas.Notification{*opts.newNotification()} - - return out -} - -func (opts *ConfigOpts) newNotification() *atlas.Notification { - out := new(atlas.Notification) - out.TypeName = strings.ToUpper(opts.notificationType) - out.DelayMin = &opts.notificationDelayMin - out.IntervalMin = opts.notificationIntervalMin - out.TeamID = opts.notificationTeamID - out.Username = opts.notificationUsername - out.ChannelName = opts.notificationChannelName - - switch out.TypeName { - case victor: - out.VictorOpsAPIKey = opts.apiKey - out.VictorOpsRoutingKey = opts.notificationVictorOpsRoutingKey - - case slack: - out.VictorOpsAPIKey = opts.apiKey - out.VictorOpsRoutingKey = opts.notificationVictorOpsRoutingKey - out.APIToken = opts.notificationToken - - case datadog: - out.DatadogAPIKey = opts.apiKey - out.DatadogRegion = strings.ToUpper(opts.notificationRegion) - - case email: - out.EmailAddress = opts.notificationEmailAddress - - case sms: - out.MobileNumber = opts.notificationMobileNumber - - case group, user, org: - out.SMSEnabled = &opts.notificationSmsEnabled - out.EmailEnabled = &opts.notificationEmailEnabled - - case ops: - out.OpsGenieAPIKey = opts.apiKey - out.OpsGenieRegion = opts.notificationRegion - - case pager: - out.ServiceKey = opts.notificationServiceKey - } - - return out -} - -func (opts *ConfigOpts) newMetricThreshold() *atlas.MetricThreshold { - return &atlas.MetricThreshold{ - MetricName: strings.ToUpper(opts.metricThresholdMetricName), - Operator: strings.ToUpper(opts.metricThresholdOperator), - Threshold: opts.metricThresholdThreshold, - Units: strings.ToUpper(opts.metricThresholdUnits), - Mode: strings.ToUpper(opts.metricThresholdMode), - } -} - -func (opts *ConfigOpts) newMatcher() *atlas.Matcher { - return &atlas.Matcher{ - FieldName: strings.ToUpper(opts.matcherFieldName), - Operator: strings.ToUpper(opts.matcherOperator), - Value: strings.ToUpper(opts.matcherValue), - } -} - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "settings", - Aliases: []string{"config"}, - Short: "Manages alerts configuration for your project.", - Long: `Use this command to list, create, edit, delete, enable and disable alert configurations.`, - } - - cmd.AddCommand( - CreateBuilder(), - ListBuilder(), - DeleteBuilder(), - FieldsBuilder(), - UpdateBuilder(), - EnableBuilder(), - DisableBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/settings_test.go b/internal/cli/mongocli/alerts/settings/settings_test.go deleted file mode 100644 index c4c2f837ae..0000000000 --- a/internal/cli/mongocli/alerts/settings/settings_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package settings - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 7, - []string{}, - ) -} diff --git a/internal/cli/mongocli/alerts/settings/update.go b/internal/cli/mongocli/alerts/settings/update.go deleted file mode 100644 index 617de1b80a..0000000000 --- a/internal/cli/mongocli/alerts/settings/update.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package settings - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type UpdateOpts struct { - cli.GlobalOpts - cli.OutputOpts - ConfigOpts - store store.AlertConfigurationUpdater - alertID string -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var updateTemplate = "Alert configuration '{{.ID}}' updated.\n" - -func (opts *UpdateOpts) Run() error { - alert := opts.NewAlertConfiguration(opts.ConfigProjectID()) - alert.ID = opts.alertID - r, err := opts.store.UpdateAlertConfiguration(alert) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas alerts config(s) update [--event event] [--enabled enabled][--matcherField fieldName --matcherOperator operator --matcherValue value] -// [--notificationType type --notificationDelayMin min --notificationEmailEnabled --notificationSmsEnabled --notificationUsername username --notificationTeamID id -// [--notificationEmailAddress email --notificationMobileNumber number --notificationChannelName channel --notificationApiToken --notificationRegion region] -// [--projectId projectId]. -func UpdateBuilder() *cobra.Command { - opts := new(UpdateOpts) - cmd := &cobra.Command{ - Use: "update ", - Short: "Modify the details of the specified alert configuration for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "alertConfigIdDesc": "Unique identifier of the alert configuration you want to update.", - "output": updateTemplate, - }, - Example: fmt.Sprintf(` # Modify the alert configuration with the ID 5d1113b25a115342acc2d1aa so that it notifies a user when they join a group for the project with the ID 5df90590f10fab5e33de2305: - %s alerts settings update 5d1113b25a115342acc2d1aa --event JOINED_GROUP --enabled \ - --notificationType USER --notificationEmailEnabled \ - --notificationUsername john@example.com \ - --output json --projectId 5df90590f10fab5e33de2305`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.alertID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.event, flag.Event, "", usage.EventCMOM) - cmd.Flags().BoolVar(&opts.enabled, flag.Enabled, false, usage.Enabled) - cmd.Flags().StringVar(&opts.matcherFieldName, flag.MatcherFieldName, "", usage.MCLIMatcherFieldName) - cmd.Flags().StringVar(&opts.matcherOperator, flag.MatcherOperator, "", usage.MatcherOperator) - cmd.Flags().StringVar(&opts.matcherValue, flag.MatcherValue, "", usage.MatcherValue) - cmd.Flags().StringVar(&opts.metricThresholdMetricName, flag.MetricName, "", usage.MetricName) - cmd.Flags().StringVar(&opts.metricThresholdOperator, flag.MetricOperator, "", usage.MetricOperator) - cmd.Flags().Float64Var(&opts.metricThresholdThreshold, flag.MetricThreshold, 0, usage.MetricThreshold) - cmd.Flags().StringVar(&opts.metricThresholdUnits, flag.MetricUnits, "", usage.MetricUnits) - cmd.Flags().StringVar(&opts.metricThresholdMode, flag.MetricMode, "", usage.MetricMode) - cmd.Flags().StringVar(&opts.notificationToken, flag.NotificationToken, "", usage.NotificationToken) - cmd.Flags().StringVar(&opts.notificationChannelName, flag.NotificationChannelName, "", usage.NotificationsChannelName) - cmd.Flags().StringVar(&opts.apiKey, flag.APIKey, "", usage.AlertConfigAPIKey) - cmd.Flags().StringVar(&opts.notificationRegion, flag.NotificationRegion, "", usage.NotificationRegion) - cmd.Flags().IntVar(&opts.notificationDelayMin, flag.NotificationDelayMin, 0, usage.NotificationDelayMin) - cmd.Flags().StringVar(&opts.notificationEmailAddress, flag.NotificationEmailAddress, "", usage.NotificationEmailAddress) - cmd.Flags().BoolVar(&opts.notificationEmailEnabled, flag.NotificationEmailEnabled, false, usage.NotificationEmailEnabled) - cmd.Flags().IntVar(&opts.notificationIntervalMin, flag.NotificationIntervalMin, 0, usage.NotificationIntervalMin) - cmd.Flags().StringVar(&opts.notificationMobileNumber, flag.NotificationMobileNumber, "", usage.NotificationMobileNumber) - cmd.Flags().StringVar(&opts.notificationServiceKey, flag.NotificationServiceKey, "", usage.NotificationServiceKey) - cmd.Flags().BoolVar(&opts.notificationSmsEnabled, flag.NotificationSmsEnabled, false, usage.NotificationSmsEnabled) - cmd.Flags().StringVar(&opts.notificationTeamID, flag.NotificationTeamID, "", usage.NotificationTeamID) - cmd.Flags().StringVar(&opts.notificationType, flag.NotificationType, "", usage.NotificationType) - cmd.Flags().StringVar(&opts.notificationUsername, flag.NotificationUsername, "", usage.NotificationUsername) - cmd.Flags().StringVar(&opts.notificationVictorOpsRoutingKey, flag.NotificationVictorOpsRoutingKey, "", usage.NotificationVictorOpsRoutingKey) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/settings/update_test.go b/internal/cli/mongocli/alerts/settings/update_test.go deleted file mode 100644 index 5967b36e36..0000000000 --- a/internal/cli/mongocli/alerts/settings/update_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package settings - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestUpdates_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertConfigurationUpdater(ctrl) - - expected := &mongodbatlas.AlertConfiguration{} - - updateOpts := &UpdateOpts{ - ConfigOpts: ConfigOpts{ - event: "OUTSIDE_METRIC_THRESHOLD", - enabled: true, - matcherFieldName: "HOSTNAME_AND_PORT", - matcherOperator: "EQUALS", - matcherValue: "mongo.example.com:27017", - metricThresholdMetricName: "ASSERT_REGULAR", - metricThresholdOperator: "LESS_THAN", - metricThresholdThreshold: 99, - metricThresholdUnits: "RAW", - metricThresholdMode: "RAW", - notificationDelayMin: 0, - notificationIntervalMin: 5, - notificationMobileNumber: "2343454567", - notificationType: "sms", - }, - store: mockStore, - alertID: "1", - } - - alert := updateOpts.NewAlertConfiguration(updateOpts.ConfigProjectID()) - alert.ID = updateOpts.alertID - mockStore. - EXPECT(). - UpdateAlertConfiguration(alert). - Return(expected, nil). - Times(1) - if err := updateOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/alerts/unacknowledge.go b/internal/cli/mongocli/alerts/unacknowledge.go deleted file mode 100644 index bb965b7f0e..0000000000 --- a/internal/cli/mongocli/alerts/unacknowledge.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package alerts - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type UnacknowledgeOpts struct { - cli.GlobalOpts - cli.OutputOpts - alertID string - comment string - store store.AlertAcknowledger -} - -func (opts *UnacknowledgeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var unackTemplate = "Alert '{{.ID}}' unacknowledged\n" - -func (opts *UnacknowledgeOpts) Run() error { - body := opts.newAcknowledgeRequest() - r, err := opts.store.AcknowledgeAlert(opts.ConfigProjectID(), opts.alertID, body) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *UnacknowledgeOpts) newAcknowledgeRequest() *atlas.AcknowledgeRequest { - return &atlas.AcknowledgeRequest{ - AcknowledgedUntil: nil, - AcknowledgementComment: opts.comment, - } -} - -// mongocli atlas alerts unacknowledge --projectId projectId --comment comment. -func UnacknowledgeBuilder() *cobra.Command { - opts := new(UnacknowledgeOpts) - cmd := &cobra.Command{ - Use: "unacknowledge ", - Short: "Unacknowledge the specified alert for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Aliases: []string{"unack"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "alertIdDesc": "Unique ID of the alert you want to unacknowledge.", - }, - Example: fmt.Sprintf(` # Unacknowledge the alert with the ID 5d1113b25a115342acc2d1aa in the project with the ID 5e2211c17a3e5a48f5497de3: - %s alerts unacknowledge 5d1113b25a115342acc2d1aa --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), unackTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.alertID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.comment, flag.Comment, "", usage.Comment) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/alerts/unacknowledge_test.go b/internal/cli/mongocli/alerts/unacknowledge_test.go deleted file mode 100644 index fd5f8b209e..0000000000 --- a/internal/cli/mongocli/alerts/unacknowledge_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package alerts - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestUnacknowledge_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAlertAcknowledger(ctrl) - - expected := &mongodbatlas.Alert{} - - acknowledgeOpts := &UnacknowledgeOpts{ - alertID: "533dc40ae4b00835ff81eaee", - comment: "Test", - store: mockStore, - } - - ackReq := acknowledgeOpts.newAcknowledgeRequest() - - mockStore. - EXPECT(). - AcknowledgeAlert(acknowledgeOpts.ProjectID, acknowledgeOpts.alertID, ackReq). - Return(expected, nil). - Times(1) - - if err := acknowledgeOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/backup/backup.go b/internal/cli/mongocli/backup/backup.go deleted file mode 100644 index 6dbf38b356..0000000000 --- a/internal/cli/mongocli/backup/backup.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/backup/restores" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/backup/snapshots" - "github.com/spf13/cobra" -) - -func baseCommand() *cobra.Command { - const use = "backups" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage cloud backups for your project.", - } - - return cmd -} - -func Builder() *cobra.Command { - cmd := baseCommand() - - cmd.AddCommand( - snapshots.Builder(), - restores.Builder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/backup/backup_test.go b/internal/cli/mongocli/backup/backup_test.go deleted file mode 100644 index b494323458..0000000000 --- a/internal/cli/mongocli/backup/backup_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package backup - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/mongocli/backup/restores/list.go b/internal/cli/mongocli/backup/restores/list.go deleted file mode 100644 index 384e93dee7..0000000000 --- a/internal/cli/mongocli/backup/restores/list.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - clusterName string - store store.RestoreJobsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var restoreListTemplate = `ID SNAPSHOT CLUSTER TYPE EXPIRES AT{{range valueOrEmptySlice .Results}} -{{.Id}} {{.SnapshotId}} {{.TargetClusterName}} {{.DeliveryType}} {{.ExpiresAt}}{{end}} -` - -func (opts *ListOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.RestoreJobs(opts.ConfigProjectID(), opts.clusterName, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas backup(s) restore(s) job(s) list [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list ", - Aliases: []string{"ls"}, - Short: "Return all cloud backup restore jobs for your project and cluster.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Name of the Atlas cluster for which you want to retrieve restore jobs.", - "output": restoreListTemplate, - }, - Example: fmt.Sprintf(` # Return all continuous backup restore jobs for the cluster Cluster0: - %s backup restore list Cluster0`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), restoreListTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.clusterName = args[0] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/backup/restores/list_test.go b/internal/cli/mongocli/backup/restores/list_test.go deleted file mode 100644 index 7a1c19ac6e..0000000000 --- a/internal/cli/mongocli/backup/restores/list_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package restores - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockRestoreJobsLister(ctrl) - - expected := &atlasv2.PaginatedCloudBackupRestoreJob{} - - listOpts := &ListOpts{ - store: mockStore, - clusterName: "Cluster0", - } - - mockStore. - EXPECT(). - RestoreJobs(listOpts.ProjectID, "Cluster0", listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{ - flag.Page, - flag.Limit, - flag.ProjectID, - flag.Output, - }, - ) -} diff --git a/internal/cli/mongocli/backup/restores/restores.go b/internal/cli/mongocli/backup/restores/restores.go deleted file mode 100644 index 4257876c27..0000000000 --- a/internal/cli/mongocli/backup/restores/restores.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "restores" - cmd := &cobra.Command{ - Use: use, - Short: "Manage cloud backup restore jobs for your project.", - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - ListBuilder(), - StartBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/backup/restores/restores_test.go b/internal/cli/mongocli/backup/restores/restores_test.go deleted file mode 100644 index 810e571d90..0000000000 --- a/internal/cli/mongocli/backup/restores/restores_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/mongocli/backup/restores/start.go b/internal/cli/mongocli/backup/restores/start.go deleted file mode 100644 index 96815ff587..0000000000 --- a/internal/cli/mongocli/backup/restores/start.go +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/commonerrors" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -const ( - automatedRestore = "automated" - downloadRestore = "download" - pointInTimeRestore = "pointInTime" -) - -type StartOpts struct { - cli.GlobalOpts - cli.OutputOpts - method string - clusterName string - targetProjectID string - targetClusterName string - oplogTS int - oplogInc int - snapshotID string - pointInTimeUTCMillis int - store store.RestoreJobsCreator -} - -func (opts *StartOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var startTemplate = "Restore job '{{.ID}}' successfully started\n" - -func (opts *StartOpts) Run() error { - request := opts.newCloudProviderSnapshotRestoreJob() - r, err := opts.store.CreateRestoreJobs(opts.ConfigProjectID(), opts.clusterName, request) - - if err != nil { - return commonerrors.Check(err) - } - - return opts.Print(r) -} - -func (opts *StartOpts) newCloudProviderSnapshotRestoreJob() *admin.DiskBackupSnapshotRestoreJob { - request := new(admin.DiskBackupSnapshotRestoreJob) - request.DeliveryType = opts.method - - if opts.targetProjectID != "" { - request.TargetGroupId = &opts.targetProjectID - } - - if opts.targetClusterName != "" { - request.TargetClusterName = &opts.targetClusterName - } - - if opts.snapshotID != "" { - request.SnapshotId = &opts.snapshotID - } - - // Set only in pointInTimeRestore - if opts.oplogTS != 0 && opts.oplogInc != 0 { - request.OplogTs = &opts.oplogTS - request.OplogInc = &opts.oplogInc - } else if opts.pointInTimeUTCMillis != 0 { - // Set only when oplogTS and oplogInc are not set - request.PointInTimeUTCSeconds = &opts.pointInTimeUTCMillis - } - - return request -} - -func (opts *StartOpts) isAutomatedRestore() bool { - return opts.method == automatedRestore -} - -func (opts *StartOpts) isPointInTimeRestore() bool { - return opts.method == pointInTimeRestore -} - -func (opts *StartOpts) isDownloadRestore() bool { - return opts.method == downloadRestore -} - -func markRequiredAutomatedRestoreFlags(cmd *cobra.Command) error { - if err := cmd.MarkFlagRequired(flag.TargetProjectID); err != nil { - return err - } - - if err := cmd.MarkFlagRequired(flag.SnapshotID); err != nil { - return err - } - - if err := cmd.MarkFlagRequired(flag.TargetClusterName); err != nil { - return err - } - - return cmd.MarkFlagRequired(flag.ClusterName) -} - -func markRequiredPointInTimeRestoreFlags(cmd *cobra.Command) error { - if err := cmd.MarkFlagRequired(flag.TargetProjectID); err != nil { - return err - } - - return cmd.MarkFlagRequired(flag.TargetClusterName) -} - -// mongocli atlas backup(s) restore(s) job(s) start . -func StartBuilder() *cobra.Command { - opts := new(StartOpts) - cmd := &cobra.Command{ - Use: fmt.Sprintf("start <%s|%s|%s>", automatedRestore, downloadRestore, pointInTimeRestore), - Short: "Start a restore job for your project and cluster.", - Long: `If you create an automated or pointInTime restore job, Atlas removes all existing data on the target cluster prior to the restore. - -` + fmt.Sprintf("%s\n%s", fmt.Sprintf(usage.RequiredRole, "Project Owner"), "Atlas supports this command only for M10+ clusters."), - Args: require.ExactValidArgs(1), - ValidArgs: []string{automatedRestore, downloadRestore, pointInTimeRestore}, - Annotations: map[string]string{ - "automated|download|pointInTimeDesc": "Type of restore job to create. Valid values include: automated, download, pointInTime. To learn more about types of restore jobs, see https://www.mongodb.com/docs/atlas/backup-restore-cluster/.", - }, - Example: fmt.Sprintf(` # Create an automated restore: - %[1]s backup restore start automated \ - --clusterName myDemo \ - --snapshotId 5e7e00128f8ce03996a47179 \ - --targetClusterName myDemo2 \ - --targetProjectId 1a2345b67c8e9a12f3456de7 - - # Create a point-in-time restore: - %[1]s backup restore start pointInTime \ - --clusterName myDemo \ - --pointInTimeUTCMillis 1588523147 \ - --targetClusterName myDemo2 \ - --targetProjectId 1a2345b67c8e9a12f3456de7 - - # Create a download restore: - %[1]s backup restore start download \ - --clusterName myDemo \ - --snapshotId 5e7e00128f8ce03996a47179`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.method = args[0] - - if opts.isAutomatedRestore() { - if err := markRequiredAutomatedRestoreFlags(cmd); err != nil { - return err - } - } - - if opts.isPointInTimeRestore() { - if err := markRequiredPointInTimeRestoreFlags(cmd); err != nil { - return err - } - } - - if opts.isDownloadRestore() { - if err := cmd.MarkFlagRequired(flag.SnapshotID); err != nil { - return err - } - } - - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), startTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.snapshotID, flag.SnapshotID, "", usage.RestoreSnapshotID) - // Atlas uses cluster name - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - - cmd.Flags().StringVar(&opts.targetProjectID, flag.TargetProjectID, "", usage.TargetProjectID) - // Atlas uses cluster name - cmd.Flags().StringVar(&opts.targetClusterName, flag.TargetClusterName, "", usage.TargetClusterName) - cmd.Flags().IntVar(&opts.oplogTS, flag.OplogTS, 0, usage.OplogTS) - cmd.Flags().IntVar(&opts.oplogInc, flag.OplogInc, 0, usage.OplogInc) - cmd.Flags().IntVar(&opts.pointInTimeUTCMillis, flag.PointInTimeUTCMillis, 0, usage.PointInTimeUTCMillis) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - - return cmd -} diff --git a/internal/cli/mongocli/backup/restores/start_test.go b/internal/cli/mongocli/backup/restores/start_test.go deleted file mode 100644 index 8e3268aa2d..0000000000 --- a/internal/cli/mongocli/backup/restores/start_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package restores - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestStart_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockRestoreJobsCreator(ctrl) - - expected := &atlasv2.DiskBackupSnapshotRestoreJob{} - - t.Run(automatedRestore, func(t *testing.T) { - listOpts := &StartOpts{ - store: mockStore, - method: automatedRestore, - clusterName: "Cluster0", - targetClusterName: "Cluster1", - targetProjectID: "1", - } - - mockStore. - EXPECT(). - CreateRestoreJobs(listOpts.ProjectID, "Cluster0", listOpts.newCloudProviderSnapshotRestoreJob()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - - t.Run(pointInTimeRestore, func(t *testing.T) { - listOpts := &StartOpts{ - store: mockStore, - method: pointInTimeRestore, - clusterName: "Cluster0", - targetClusterName: "Cluster1", - targetProjectID: "1", - } - - mockStore. - EXPECT(). - CreateRestoreJobs(listOpts.ProjectID, "Cluster0", listOpts.newCloudProviderSnapshotRestoreJob()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - - t.Run(downloadRestore, func(t *testing.T) { - listOpts := &StartOpts{ - store: mockStore, - method: downloadRestore, - clusterName: "Cluster0", - } - - mockStore. - EXPECT(). - CreateRestoreJobs(listOpts.ProjectID, "Cluster0", listOpts.newCloudProviderSnapshotRestoreJob()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} - -func TestStartBuilder(t *testing.T) { - test.CmdValidator( - t, - StartBuilder(), - 0, - []string{ - flag.SnapshotID, - flag.ClusterName, - flag.TargetProjectID, - flag.TargetClusterName, - flag.OplogTS, - flag.OplogInc, - flag.ProjectID, - flag.Output, - }, - ) -} diff --git a/internal/cli/mongocli/backup/snapshots/create.go b/internal/cli/mongocli/backup/snapshots/create.go deleted file mode 100644 index 126bc9a9e2..0000000000 --- a/internal/cli/mongocli/backup/snapshots/create.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/commonerrors" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.SnapshotsCreator - clusterName string - desc string - retentionInDays int -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var createTemplate = "Snapshot '{{.Id}}' created.\n" - -func (opts *CreateOpts) Run() error { - createRequest := opts.newCloudProviderSnapshot() - - r, err := opts.store.CreateSnapshot(opts.ConfigProjectID(), opts.clusterName, createRequest) - if err != nil { - return commonerrors.Check(err) - } - return opts.Print(r) -} - -func (opts *CreateOpts) newCloudProviderSnapshot() *atlasv2.DiskBackupOnDemandSnapshotRequest { - createRequest := &atlasv2.DiskBackupOnDemandSnapshotRequest{ - RetentionInDays: &opts.retentionInDays, - Description: &opts.desc, - } - return createRequest -} - -// mongocli atlas backup snapshots create|take clusterName --desc description --retention days [--projectId projectId]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - cmd := &cobra.Command{ - Use: "create ", - Aliases: []string{"take"}, - Short: "Create a backup snapshot for your project and cluster.", - Long: `You can create on-demand backup snapshots for Atlas cluster tiers M10 and larger. - -` + fmt.Sprintf("%s\n%s", fmt.Sprintf(usage.RequiredRole, "Project Owner"), "Atlas supports this command only for M10+ clusters."), - Args: require.ExactArgs(1), - Example: fmt.Sprintf(` # Create a backup snapshot for the cluster named myDemo that Atlas retains for 30 days: - %s backups snapshots create myDemo --desc "test" --retention 30`, cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "clusterNameDesc": "Name of the Atlas cluster whose snapshot you want to restore.", - "output": createTemplate, - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.clusterName = args[0] - return opts.Run() - }, - } - cmd.Flags().StringVar(&opts.desc, flag.Description, "", usage.SnapshotDescription) - cmd.Flags().IntVar(&opts.retentionInDays, flag.Retention, 1, usage.RetentionInDays) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Description) - - return cmd -} diff --git a/internal/cli/mongocli/backup/snapshots/create_test.go b/internal/cli/mongocli/backup/snapshots/create_test.go deleted file mode 100644 index 8e05dab739..0000000000 --- a/internal/cli/mongocli/backup/snapshots/create_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestCreateOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSnapshotsCreator(ctrl) - - expected := &atlasv2.DiskBackupSnapshot{} - - createOpts := &CreateOpts{ - store: mockStore, - clusterName: "", - desc: "", - retentionInDays: 0, - } - - mockStore. - EXPECT(). - CreateSnapshot(createOpts.ProjectID, createOpts.clusterName, createOpts.newCloudProviderSnapshot()).Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/backup/snapshots/delete.go b/internal/cli/mongocli/backup/snapshots/delete.go deleted file mode 100644 index 49b6783bea..0000000000 --- a/internal/cli/mongocli/backup/snapshots/delete.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/commonerrors" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - clusterName string - store store.SnapshotsDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return commonerrors.Check(opts.Delete(opts.store.DeleteSnapshot, opts.ConfigProjectID(), opts.clusterName)) -} - -// mongocli atlas snapshot(s) delete --force --clusterName [--projectId projectId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Snapshot '%s' deleted\n", "Snapshot not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove the specified backup snapshot.", - Long: fmt.Sprintf("%s\n%s", fmt.Sprintf(usage.RequiredRole, "Project Owner"), "Atlas supports this command only for M10+ clusters."), - Args: require.ExactArgs(1), - Example: fmt.Sprintf(` # Remove the backup snapshot with the ID 5f4007f327a3bd7b6f4103c5 for the cluster named myDemo: - %s backups snapshots delete 5f4007f327a3bd7b6f4103c5 --clusterName myDemo`, cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "snapshotIdDesc": "Unique identifier of the snapshot you want to delete.", - "output": opts.SuccessMessage(), - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.Entry = args[0] - if err := opts.Prompt(); err != nil { - return err - } - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - - return cmd -} diff --git a/internal/cli/mongocli/backup/snapshots/delete_test.go b/internal/cli/mongocli/backup/snapshots/delete_test.go deleted file mode 100644 index ed1ac8af30..0000000000 --- a/internal/cli/mongocli/backup/snapshots/delete_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSnapshotsDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "test", - }, - clusterName: "cluster", - store: mockStore, - } - - mockStore. - EXPECT(). - DeleteSnapshot(deleteOpts.ConfigProjectID(), deleteOpts.clusterName, deleteOpts.Entry). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/backup/snapshots/describe.go b/internal/cli/mongocli/backup/snapshots/describe.go deleted file mode 100644 index dd75315f7d..0000000000 --- a/internal/cli/mongocli/backup/snapshots/describe.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const describeTemplate = `ID SNAPSHOT TYPE TYPE DESCRIPTION EXPIRES AT -{{.Id}} {{.SnapshotType}} {{.Type}} {{.Description}} {{.ExpiresAt}} -` - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.SnapshotsDescriber - snapshot string - clusterName string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.Snapshot(opts.ConfigProjectID(), opts.clusterName, opts.snapshot) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas backup snapshots describe snapshotId --clusterName clusterName --projectId projectId. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe ", - Short: "Return the details for the specified snapshot for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Args: require.ExactArgs(1), - Example: fmt.Sprintf(` # Return the details for the backup snapshot with the ID 5f4007f327a3bd7b6f4103c5 for the cluster named myDemo: - %s backups snapshots describe 5f4007f327a3bd7b6f4103c5 --clusterName myDemo`, cli.ExampleAtlasEntryPoint()), - Annotations: map[string]string{ - "snapshotIdDesc": "Unique identifier of the snapshot you want to retrieve.", - "output": describeTemplate, - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.snapshot = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - return cmd -} diff --git a/internal/cli/mongocli/backup/snapshots/describe_test.go b/internal/cli/mongocli/backup/snapshots/describe_test.go deleted file mode 100644 index b2cebd8960..0000000000 --- a/internal/cli/mongocli/backup/snapshots/describe_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSnapshotsDescriber(ctrl) - - var expected atlasv2.DiskBackupReplicaSet - - describeOpts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - Snapshot(describeOpts.ProjectID, describeOpts.clusterName, describeOpts.snapshot). - Return(&expected, nil). - Times(1) - - if err := describeOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/backup/snapshots/list.go b/internal/cli/mongocli/backup/snapshots/list.go deleted file mode 100644 index 184d72cb45..0000000000 --- a/internal/cli/mongocli/backup/snapshots/list.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - clusterName string - store store.SnapshotsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `ID TYPE STATUS CREATED AT EXPIRES AT{{range valueOrEmptySlice .Results}} -{{.Id}} {{.SnapshotType}} {{.Status}} {{.CreatedAt}} {{.ExpiresAt}}{{end}} -` - -func (opts *ListOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.Snapshots(opts.ConfigProjectID(), opts.clusterName, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas backups snapshots list [--projectId projectId] [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list ", - Short: "Return all cloud backup snapshots for your project and cluster.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Aliases: []string{"ls"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Name of the Atlas cluster that contains the snapshots you want to retrieve.", - "output": listTemplate, - }, - Example: fmt.Sprintf(` # Return a JSON-formatted list of snapshots for the cluster named myDemo - %s backups snapshots list myDemo --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.clusterName = args[0] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/backup/snapshots/list_test.go b/internal/cli/mongocli/backup/snapshots/list_test.go deleted file mode 100644 index 51241ee5e3..0000000000 --- a/internal/cli/mongocli/backup/snapshots/list_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSnapshotsLister(ctrl) - - expected := &atlasv2.PaginatedCloudBackupReplicaSet{} - - listOpts := &ListOpts{ - store: mockStore, - clusterName: "Cluster0", - } - - mockStore. - EXPECT(). - Snapshots(listOpts.ProjectID, "Cluster0", listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/backup/snapshots/snapshots.go b/internal/cli/mongocli/backup/snapshots/snapshots.go deleted file mode 100644 index 9fefeaa4ef..0000000000 --- a/internal/cli/mongocli/backup/snapshots/snapshots.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "snapshots" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage cloud backup snapshots for your project.", - } - - cmd.AddCommand( - ListBuilder(), - CreateBuilder(), - DescribeBuilder(), - WatchBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/backup/snapshots/snapshots_test.go b/internal/cli/mongocli/backup/snapshots/snapshots_test.go deleted file mode 100644 index 9a5375780a..0000000000 --- a/internal/cli/mongocli/backup/snapshots/snapshots_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/mongocli/backup/snapshots/watch.go b/internal/cli/mongocli/backup/snapshots/watch.go deleted file mode 100644 index 3b6101f8f0..0000000000 --- a/internal/cli/mongocli/backup/snapshots/watch.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type WatchOpts struct { - cli.GlobalOpts - cli.WatchOpts - id string - clusterName string - store store.SnapshotsDescriber -} - -func (opts *WatchOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *WatchOpts) watcher() (any, bool, error) { - result, err := opts.store.Snapshot(opts.ConfigProjectID(), opts.clusterName, opts.id) - if err != nil { - return nil, false, err - } - return nil, result.GetStatus() == "completed" || result.GetStatus() == "failed", nil -} - -func (opts *WatchOpts) Run() error { - if _, err := opts.Watch(opts.watcher); err != nil { - return err - } - - return opts.Print(nil) -} - -// mongocli atlas snapshot(s) watch --clusterName clusterName [--projectId projectId]. -func WatchBuilder() *cobra.Command { - opts := &WatchOpts{} - cmd := &cobra.Command{ - Use: "watch ", - Short: "Watch the specified snapshot in your project until it becomes available.", - Long: `This command checks the snapshot's status periodically until it reaches a completed or failed status. -Once the snapshot reaches the expected status, the command prints "Snapshot changes completed." -If you run the command in the terminal, it blocks the terminal session until the resource status completes or fails. -You can interrupt the command's polling at any time with CTRL-C. - -` + fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Example: fmt.Sprintf(` # Watch the backup snapshot with the ID 5f4007f327a3bd7b6f4103c5 in the cluster named myDemo until it becomes available: - %s backups snapshots watch 5f4007f327a3bd7b6f4103c5 --clusterName myDemo`, cli.ExampleAtlasEntryPoint()), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "snapshotIdDesc": "Unique identifier of the snapshot you want to watch.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), "\nSnapshot changes completed.\n"), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - - return cmd -} diff --git a/internal/cli/mongocli/backup/snapshots/watch_test.go b/internal/cli/mongocli/backup/snapshots/watch_test.go deleted file mode 100644 index 45f6bd454f..0000000000 --- a/internal/cli/mongocli/backup/snapshots/watch_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/pointer" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestWatch_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSnapshotsDescriber(ctrl) - - watchOpts := &WatchOpts{ - id: "test", - store: mockStore, - clusterName: "cluster", - } - - expected := &atlasv2.DiskBackupReplicaSet{Status: pointer.Get("completed")} - - mockStore. - EXPECT(). - Snapshot(watchOpts.ProjectID, watchOpts.clusterName, watchOpts.id). - Return(expected, nil). - Times(1) - - if err := watchOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/events/events.go b/internal/cli/mongocli/events/events.go deleted file mode 100644 index 5b479cc9e4..0000000000 --- a/internal/cli/mongocli/events/events.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "events" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage events for your organization or project.", - } - - cmd.AddCommand( - ListBuilder(), - OrgsBuilder(), - ProjectsBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/events/events_test.go b/internal/cli/mongocli/events/events_test.go deleted file mode 100644 index 4018ea28eb..0000000000 --- a/internal/cli/mongocli/events/events_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} diff --git a/internal/cli/mongocli/events/list.go b/internal/cli/mongocli/events/list.go deleted file mode 100644 index f3ead96d2c..0000000000 --- a/internal/cli/mongocli/events/list.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type EventListOpts struct { - cli.ListOpts - EventType []string - MinDate string - MaxDate string -} - -func (opts *EventListOpts) newEventListOptions() *atlas.EventListOptions { - return &atlas.EventListOptions{ - ListOptions: atlas.ListOptions{ - PageNum: opts.PageNum, - ItemsPerPage: opts.ItemsPerPage, - }, - EventType: opts.EventType, - MinDate: opts.MinDate, - MaxDate: opts.MaxDate, - } -} - -type ListOpts struct { - EventListOpts - cli.OutputOpts - orgID string - projectID string - store store.EventLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `ID TYPE CREATED{{range valueOrEmptySlice .Results}} -{{.ID}} {{.EventTypeName}} {{.Created}}{{end}} -` - -func (opts *ListOpts) Run() error { - listOpts := opts.newEventListOptions() - - var r *atlas.EventResponse - var err error - - if opts.orgID != "" { - r, err = opts.store.OrganizationEvents(opts.orgID, listOpts) - } else if opts.projectID != "" { - r, err = opts.store.ProjectEvents(opts.projectID, listOpts) - } - if err != nil { - return err - } - - return opts.Print(r) -} - -// ListBuilder -// -// mongocli atlas event(s) list -// -// [--projectId projectId] -// [--orgId orgId] -// [--page N] -// [--limit N] -// [--minDate minDate] -// [--maxDate maxDate]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Short: "Return all events for an organization or project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Deprecated: ` - To return project events prefer - mongocli atlas|ops-manager|cloud-manager events projects list [--projectId ] - - To return organization events prefer - mongocli atlas|ops-manager|cloud-manager events organizations list [--orgId ] -`, - Aliases: []string{"ls"}, - Args: require.NoArgs, - Annotations: map[string]string{ - "output": listTemplate, - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - if opts.orgID != "" && opts.projectID != "" { - return fmt.Errorf("both --%s and --%s set", flag.ProjectID, flag.OrgID) - } - if opts.orgID == "" && opts.projectID == "" { - return fmt.Errorf("--%s or --%s must be set", flag.ProjectID, flag.OrgID) - } - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringSliceVar(&opts.EventType, flag.TypeFlag, nil, usage.Event) - cmd.Flags().StringVar(&opts.MaxDate, flag.MaxDate, "", usage.MaxDate) - cmd.Flags().StringVar(&opts.MinDate, flag.MinDate, "", usage.MinDate) - - cmd.Flags().StringVar(&opts.projectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVar(&opts.orgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/events/list_test.go b/internal/cli/mongocli/events/list_test.go deleted file mode 100644 index fd7087e0e8..0000000000 --- a/internal/cli/mongocli/events/list_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package events - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockEventLister(ctrl) - - expected := &mongodbatlas.EventResponse{} - - t.Run("for a project", func(t *testing.T) { - listOpts := &ListOpts{ - store: mockStore, - } - listOpts.orgID = "1" - - mockStore. - EXPECT().OrganizationEvents(listOpts.orgID, listOpts.newEventListOptions()). - Return(expected, nil). - Times(1) - - err := listOpts.Run() - if err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - t.Run("for an org", func(t *testing.T) { - listOpts := &ListOpts{ - store: mockStore, - } - - listOpts.projectID = "1" - mockStore. - EXPECT().ProjectEvents(listOpts.projectID, listOpts.newEventListOptions()). - Return(expected, nil). - Times(1) - - err := listOpts.Run() - if err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{ - flag.Limit, - flag.Page, - flag.Output, - flag.ProjectID, - flag.OrgID, - flag.TypeFlag, - flag.MaxDate, - flag.MinDate, - }, - ) -} diff --git a/internal/cli/mongocli/events/orgs_list.go b/internal/cli/mongocli/events/orgs_list.go deleted file mode 100644 index b778754514..0000000000 --- a/internal/cli/mongocli/events/orgs_list.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type orgListOpts struct { - cli.OutputOpts - EventListOpts - cli.GlobalOpts - store store.OrganizationEventLister -} - -func (opts *orgListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *orgListOpts) Run() error { - listOpts := opts.newEventListOptions() - - var r *atlas.EventResponse - var err error - r, err = opts.store.OrganizationEvents(opts.ConfigOrgID(), listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// OrgListBuilder -// -// mongocli atlas event(s) list -// -// [--orgId orgId] -// [--page N] -// [--limit N] -// [--minDate minDate] -// [--maxDate maxDate]. -func OrgListBuilder() *cobra.Command { - opts := &orgListOpts{} - cmd := &cobra.Command{ - Use: "list", - Short: "Return all events for the specified organization.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of events for the organization with the ID 5dd5a6b6f10fab1d71a58495: - %s events organizations list --orgId 5dd5a6b6f10fab1d71a58495 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringSliceVar(&opts.EventType, flag.TypeFlag, nil, usage.EventCMOM) - cmd.Flags().StringVar(&opts.MaxDate, flag.MaxDate, "", usage.MaxDate) - cmd.Flags().StringVar(&opts.MinDate, flag.MinDate, "", usage.MinDate) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} - -func OrgsBuilder() *cobra.Command { - const use = "organizations" - cmd := &cobra.Command{ - Use: use, - Short: "Organization operations.", - Long: "List organization events.", - Aliases: cli.GenerateAliases(use, "orgs", "org"), - } - cmd.AddCommand( - OrgListBuilder(), - ) - return cmd -} diff --git a/internal/cli/mongocli/events/orgs_list_test.go b/internal/cli/mongocli/events/orgs_list_test.go deleted file mode 100644 index b114f7ce61..0000000000 --- a/internal/cli/mongocli/events/orgs_list_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func Test_orgListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationEventLister(ctrl) - - expected := &mongodbatlas.EventResponse{} - listOpts := &orgListOpts{ - store: mockStore, - } - listOpts.OrgID = "1" - - mockStore. - EXPECT().OrganizationEvents(listOpts.OrgID, listOpts.newEventListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestOrgListBuilder(t *testing.T) { - test.CmdValidator( - t, - OrgListBuilder(), - 0, - []string{ - flag.Limit, - flag.Page, - flag.Output, - flag.OrgID, - flag.TypeFlag, - flag.MaxDate, - flag.MinDate, - }, - ) -} - -func TestOrgsBuilder(t *testing.T) { - test.CmdValidator( - t, - OrgsBuilder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/mongocli/events/projects_list.go b/internal/cli/mongocli/events/projects_list.go deleted file mode 100644 index 6f590c990d..0000000000 --- a/internal/cli/mongocli/events/projects_list.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -type projectListOpts struct { - EventListOpts - cli.GlobalOpts - cli.OutputOpts - store store.ProjectEventLister -} - -func (opts *projectListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *projectListOpts) Run() error { - listOpts := opts.newEventListOptions() - - var r *atlas.EventResponse - var err error - r, err = opts.store.ProjectEvents(opts.ConfigProjectID(), listOpts) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// ProjectListBuilder -// -// mongocli atlas event(s) list -// -// [--page N] -// [--limit N] -// [--minDate minDate] -// [--maxDate maxDate]. -func ProjectListBuilder() *cobra.Command { - opts := &projectListOpts{} - cmd := &cobra.Command{ - Use: "list", - Short: "Return all events for the specified project.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of events for the project with the ID 5e2211c17a3e5a48f5497de3: - %s events projects list --Id 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringSliceVar(&opts.EventType, flag.TypeFlag, nil, usage.EventCMOM) - cmd.Flags().StringVar(&opts.MaxDate, flag.MaxDate, "", usage.MaxDate) - cmd.Flags().StringVar(&opts.MinDate, flag.MinDate, "", usage.MinDate) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} - -func ProjectsBuilder() *cobra.Command { - const use = "projects" - cmd := &cobra.Command{ - Use: use, - Short: "Project operations.", - Long: "List projects events.", - Aliases: cli.GenerateAliases(use), - } - cmd.AddCommand( - ProjectListBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/events/projects_list_test.go b/internal/cli/mongocli/events/projects_list_test.go deleted file mode 100644 index 2543870eb0..0000000000 --- a/internal/cli/mongocli/events/projects_list_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func Test_projectListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectEventLister(ctrl) - - expected := &mongodbatlas.EventResponse{} - listOpts := &projectListOpts{ - store: mockStore, - } - listOpts.ProjectID = "1" - - mockStore. - EXPECT().ProjectEvents(listOpts.ProjectID, listOpts.newEventListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestProjectListBuilder(t *testing.T) { - test.CmdValidator( - t, - ProjectListBuilder(), - 0, - []string{ - flag.Limit, - flag.Page, - flag.Output, - flag.ProjectID, - flag.TypeFlag, - flag.MaxDate, - flag.MinDate, - }, - ) -} - -func TestProjectsBuilder(t *testing.T) { - test.CmdValidator( - t, - ProjectsBuilder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/namespaces/list.go b/internal/cli/mongocli/performanceadvisor/namespaces/list.go deleted file mode 100644 index b3ee1ad026..0000000000 --- a/internal/cli/mongocli/performanceadvisor/namespaces/list.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package namespaces - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const listTemplate = `NAMESPACE TYPE{{range valueOrEmptySlice .Namespaces}} -{{.Namespace}} {{.Type}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.PerformanceAdvisorOpts - store store.PerformanceAdvisorNamespacesLister - since int64 - duration int64 -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - host, err := opts.Host() - if err != nil { - return err - } - r, err := opts.store.PerformanceAdvisorNamespaces(opts.ConfigProjectID(), host, opts.newNamespaceOptions()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *ListOpts) newNamespaceOptions() *atlas.NamespaceOptions { - return &atlas.NamespaceOptions{ - Since: opts.since, - Duration: opts.duration, - } -} - -// mongocli atlas performanceAdvisor namespace(s) list --processName processName --since since --duration duration --projectId projectId. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list", - Short: "Return up to 20 namespaces for collections experiencing slow queries on the specified host.", - Long: `Namespaces appear in the following format: {database}.{collection}. - -If you don't set the duration option or the since option, this command returns data from the last 24 hours. - -` + fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Aliases: []string{"ls"}, - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of namespaces for collections with slow queries for the atlas-111ggi-shard-00-00.111xx.mongodb.net:27017 host in the project with the ID 5e2211c17a3e5a48f5497de3: - %s performanceAdvisor namespaces list --processName atlas-111ggi-shard-00-00.111xx.mongodb.net:27017 --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - opts.MarkRequiredFlagsByService(cmd), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.HostID, flag.HostID, "", usage.HostID) - cmd.Flags().StringVar(&opts.ProcessName, flag.ProcessName, "", usage.ProcessName) - cmd.Flags().Int64Var(&opts.since, flag.Since, 0, usage.Since) - cmd.Flags().Int64Var(&opts.duration, flag.Duration, 0, usage.Duration) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/namespaces/list_test.go b/internal/cli/mongocli/performanceadvisor/namespaces/list_test.go deleted file mode 100644 index 53f2cb5605..0000000000 --- a/internal/cli/mongocli/performanceadvisor/namespaces/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package namespaces - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestNamespacesList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockPerformanceAdvisorNamespacesLister(ctrl) - - var expected *mongodbatlas.Namespaces - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - PerformanceAdvisorNamespaces(listOpts.ProjectID, listOpts.ProcessName, listOpts.newNamespaceOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Duration, flag.Since, flag.ProcessName, flag.HostID}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/namespaces/namespaces.go b/internal/cli/mongocli/performanceadvisor/namespaces/namespaces.go deleted file mode 100644 index d0c4ff4d4d..0000000000 --- a/internal/cli/mongocli/performanceadvisor/namespaces/namespaces.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package namespaces - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "namespaces" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Retrieve namespaces for collections experiencing slow queries", - } - cmd.AddCommand( - ListBuilder()) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/namespaces/namespaces_test.go b/internal/cli/mongocli/performanceadvisor/namespaces/namespaces_test.go deleted file mode 100644 index 69adfdd93d..0000000000 --- a/internal/cli/mongocli/performanceadvisor/namespaces/namespaces_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package namespaces - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/performance_advisor.go b/internal/cli/mongocli/performanceadvisor/performance_advisor.go deleted file mode 100644 index ebd25a95ba..0000000000 --- a/internal/cli/mongocli/performanceadvisor/performance_advisor.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package performanceadvisor - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/performanceadvisor/namespaces" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/performanceadvisor/slowoperationthreshold" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/performanceadvisor/slowquerylogs" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/performanceadvisor/suggestedindexes" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "performanceAdvisor" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Learn more about slow queries and get suggestions to improve database performance.", - } - cmd.AddCommand( - namespaces.Builder(), - slowquerylogs.Builder(), - suggestedindexes.Builder(), - slowoperationthreshold.Builder()) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/performance_advisor_test.go b/internal/cli/mongocli/performanceadvisor/performance_advisor_test.go deleted file mode 100644 index aa8cd2da51..0000000000 --- a/internal/cli/mongocli/performanceadvisor/performance_advisor_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package performanceadvisor - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 4, - []string{}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/disable.go b/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/disable.go deleted file mode 100644 index 67e7daf70b..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/disable.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package slowoperationthreshold - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const DisableTemplate = `Atlas management of the slow operation disabled -` - -type DisableOpts struct { - cli.GlobalOpts - store store.PerformanceAdvisorSlowOperationThresholdDisabler -} - -func (opts *DisableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DisableOpts) Run() error { - if err := opts.store.DisablePerformanceAdvisorSlowOperationThreshold(opts.ConfigProjectID()); err != nil { - return err - } - - fmt.Print(DisableTemplate) - return nil -} - -// mongocli atlas performanceAdvisor sot disable [--projectId projectId]. -func DisableBuilder() *cobra.Command { - opts := new(DisableOpts) - cmd := &cobra.Command{ - Use: "disable", - Short: "Disable the application-managed slow operation threshold for your project.", - Long: `The slow operation threshold determines which operations are flagged by the Performance Advisor and Query Profiler. When disabled, the application considers any operation that takes longer than 100 milliseconds to be slow. - -` + fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/disable_test.go b/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/disable_test.go deleted file mode 100644 index 00adbbbec4..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/disable_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package slowoperationthreshold - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDisable_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockPerformanceAdvisorSlowOperationThresholdDisabler(ctrl) - - opts := &DisableOpts{ - store: mockStore, - } - - mockStore. - EXPECT().DisablePerformanceAdvisorSlowOperationThreshold(opts.ConfigProjectID()). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDisableBuilder(t *testing.T) { - test.CmdValidator( - t, - DisableBuilder(), - 0, - []string{flag.ProjectID}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/enable.go b/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/enable.go deleted file mode 100644 index 1c0e5ed18b..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/enable.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package slowoperationthreshold - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const EnableTemplate = `Atlas management of the slow operation enabled -` - -type EnableOpts struct { - cli.GlobalOpts - store store.PerformanceAdvisorSlowOperationThresholdEnabler -} - -func (opts *EnableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *EnableOpts) Run() error { - if err := opts.store.EnablePerformanceAdvisorSlowOperationThreshold(opts.ConfigProjectID()); err != nil { - return err - } - - fmt.Print(EnableTemplate) - return nil -} - -// mongocli atlas performanceAdvisor sot enable [--projectId projectId]. -func EnableBuilder() *cobra.Command { - opts := new(EnableOpts) - cmd := &cobra.Command{ - Use: "enable", - Short: "Enable the application-managed slow operation threshold for your project.", - Long: `The slow operation threshold determines which operations are flagged by the Performance Advisor and Query Profiler. When enabled, the application uses the average execution time for operations on your cluster to determine slow-running queries. As a result, the threshold is more pertinent to your cluster workload. Application-managed slow operation threshold is enabled by default for dedicated clusters (M10+). - -` + fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/enable_test.go b/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/enable_test.go deleted file mode 100644 index c28f96e5b6..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/enable_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package slowoperationthreshold - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestEnable_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockPerformanceAdvisorSlowOperationThresholdEnabler(ctrl) - - opts := &EnableOpts{ - store: mockStore, - } - - mockStore. - EXPECT().EnablePerformanceAdvisorSlowOperationThreshold(opts.ConfigProjectID()). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestEnableBuilder(t *testing.T) { - test.CmdValidator( - t, - EnableBuilder(), - 0, - []string{flag.ProjectID}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/slow_operation_threshold.go b/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/slow_operation_threshold.go deleted file mode 100644 index 2c41efa35f..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/slow_operation_threshold.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package slowoperationthreshold - -import ( - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "slowOperationThreshold" - cmd := &cobra.Command{ - Use: use, - Aliases: []string{"slowOT", "sot", "slowMS"}, - Short: "Enable or disable management of the slow operation threshold for your cluster.", - } - cmd.AddCommand( - EnableBuilder(), - DisableBuilder()) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/slow_operation_threshold_test.go b/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/slow_operation_threshold_test.go deleted file mode 100644 index f2e703236e..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowoperationthreshold/slow_operation_threshold_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package slowoperationthreshold - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/slowquerylogs/list.go b/internal/cli/mongocli/performanceadvisor/slowquerylogs/list.go deleted file mode 100644 index c4e31ebfdc..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowquerylogs/list.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package slowquerylogs - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const listTemplate = `NAMESPACE LINE{{range valueOrEmptySlice .SlowQuery}} -{{.Namespace}} {{.Line}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.PerformanceAdvisorOpts - store store.PerformanceAdvisorSlowQueriesLister - since int64 - duration int64 - namespaces string - nLog int64 -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - host, err := opts.Host() - if err != nil { - return err - } - r, err := opts.store.PerformanceAdvisorSlowQueries(opts.ConfigProjectID(), host, opts.newSlowQueryOptions()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *ListOpts) newSlowQueryOptions() *atlas.SlowQueryOptions { - return &atlas.SlowQueryOptions{ - Namespaces: opts.namespaces, - NLogs: opts.nLog, - NamespaceOptions: atlas.NamespaceOptions{ - Since: opts.since, - Duration: opts.duration, - }, - } -} - -// mongocli atlas performanceAdvisor slowQueryLogs list --processName processName --since since --duration duration --projectId projectId. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Short: "Return log lines for slow queries that the Performance Advisor and Query Profiler identified.", - Long: `The Performance Advisor monitors queries that MongoDB considers slow and suggests new indexes to improve query performance. The threshold for slow queries varies based on the average time of operations on your cluster to provide recommendations pertinent to your workload. - -If you don't set the duration option or the since option, this command returns data from the last 24 hours. - -` + fmt.Sprintf(usage.RequiredRole, "Project Data Access Read/Write"), - Aliases: []string{"ls"}, - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of log lines for collections with slow queries for the atlas-111ggi-shard-00-00.111xx.mongodb.net:27017 host in the project with the ID 5e2211c17a3e5a48f5497de3: - %s performanceAdvisor slowQueryLogs list --processName atlas-111ggi-shard-00-00.111xx.mongodb.net:27017 --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - opts.MarkRequiredFlagsByService(cmd), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - const defaultLogLines = 20000 - - cmd.Flags().StringVar(&opts.HostID, flag.HostID, "", usage.HostID) - cmd.Flags().StringVar(&opts.ProcessName, flag.ProcessName, "", usage.ProcessName) - cmd.Flags().Int64Var(&opts.since, flag.Since, 0, usage.Since) - cmd.Flags().Int64Var(&opts.duration, flag.Duration, 0, usage.Duration) - cmd.Flags().Int64Var(&opts.nLog, flag.NLog, defaultLogLines, usage.NLog) - cmd.Flags().StringVar(&opts.namespaces, flag.Namespaces, "", usage.SlowQueryNamespaces) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/slowquerylogs/list_test.go b/internal/cli/mongocli/performanceadvisor/slowquerylogs/list_test.go deleted file mode 100644 index 3a55c0449b..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowquerylogs/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package slowquerylogs - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestSlowQueryLogsList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockPerformanceAdvisorSlowQueriesLister(ctrl) - - var expected *mongodbatlas.SlowQueries - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - PerformanceAdvisorSlowQueries(listOpts.ProjectID, listOpts.ProcessName, listOpts.newSlowQueryOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Duration, flag.Since, flag.HostID, flag.ProcessName, flag.Namespaces, flag.NLog}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/slowquerylogs/slow_query_logs.go b/internal/cli/mongocli/performanceadvisor/slowquerylogs/slow_query_logs.go deleted file mode 100644 index 5ddc1b6e32..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowquerylogs/slow_query_logs.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package slowquerylogs - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "slowQueryLogs" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Get log lines for slow queries for a specified host", - } - cmd.AddCommand( - ListBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/slowquerylogs/slow_query_logs_test.go b/internal/cli/mongocli/performanceadvisor/slowquerylogs/slow_query_logs_test.go deleted file mode 100644 index 341eacc5de..0000000000 --- a/internal/cli/mongocli/performanceadvisor/slowquerylogs/slow_query_logs_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package slowquerylogs - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/suggestedindexes/list.go b/internal/cli/mongocli/performanceadvisor/suggestedindexes/list.go deleted file mode 100644 index 984fb711c9..0000000000 --- a/internal/cli/mongocli/performanceadvisor/suggestedindexes/list.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package suggestedindexes - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" -) - -const listTemplate = `ID NAMESPACE SUGGESTED INDEX{{range valueOrEmptySlice .SuggestedIndexes}} -{{ .ID }} {{ .Namespace}} { {{range $i, $element := .Index}}{{range $key, $value := .}}{{if $i}}, {{end}}{{ $key }}: {{ $value }}{{end}}{{end}} }{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.PerformanceAdvisorOpts - store store.PerformanceAdvisorIndexesLister - since int64 - duration int64 - namespaces string - nIndexes int64 - nExamples int64 -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - host, err := opts.Host() - if err != nil { - return err - } - r, err := opts.store.PerformanceAdvisorIndexes(opts.ConfigProjectID(), host, opts.newSuggestedIndexOptions()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *ListOpts) newSuggestedIndexOptions() *atlas.SuggestedIndexOptions { - return &atlas.SuggestedIndexOptions{ - Namespaces: opts.namespaces, - NIndexes: opts.nIndexes, - NExamples: opts.nExamples, - NamespaceOptions: atlas.NamespaceOptions{ - Since: opts.since, - Duration: opts.duration, - }, - } -} - -// mongocli atlas performanceAdvisor suggestedIndexes list --processName processName --nIndexes nIndexes --nExamples nExamples --namespaces namespaces --since since --duration duration --projectId projectId. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list", - Short: "Return the suggested indexes for collections experiencing slow queries.", - Long: `The Performance Advisor monitors queries that MongoDB considers slow and suggests new indexes to improve query performance. - -` + fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Aliases: []string{"ls"}, - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return a JSON-formatted list of suggested indexes for the atlas-111ggi-shard-00-00.111xx.mongodb.net:27017 host in the project with the ID 5e2211c17a3e5a48f5497de3: - %s performanceAdvisor suggestedIndexes list --processName atlas-111ggi-shard-00-00.111xx.mongodb.net:27017 --projectId 5e2211c17a3e5a48f5497de3 --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - opts.MarkRequiredFlagsByService(cmd), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.HostID, flag.HostID, "", usage.HostID) - cmd.Flags().StringVar(&opts.ProcessName, flag.ProcessName, "", usage.ProcessName) - cmd.Flags().Int64Var(&opts.since, flag.Since, 0, usage.Since) - cmd.Flags().Int64Var(&opts.duration, flag.Duration, 0, usage.Duration) - cmd.Flags().StringVar(&opts.namespaces, flag.Namespaces, "", usage.SuggestedIndexNamespaces) - cmd.Flags().Int64Var(&opts.nExamples, flag.NExamples, 0, usage.NExamples) - cmd.Flags().Int64Var(&opts.nIndexes, flag.NIndexes, 0, usage.NIndexes) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/suggestedindexes/list_test.go b/internal/cli/mongocli/performanceadvisor/suggestedindexes/list_test.go deleted file mode 100644 index 7df430a88f..0000000000 --- a/internal/cli/mongocli/performanceadvisor/suggestedindexes/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package suggestedindexes - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/atlas/mongodbatlas" -) - -func TestNamespacesList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockPerformanceAdvisorIndexesLister(ctrl) - - var expected *mongodbatlas.SuggestedIndexes - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - PerformanceAdvisorIndexes(listOpts.ProjectID, listOpts.ProcessName, listOpts.newSuggestedIndexOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Duration, flag.Since, flag.Namespaces, flag.NExamples, flag.NIndexes}, - ) -} diff --git a/internal/cli/mongocli/performanceadvisor/suggestedindexes/suggestedindexes.go b/internal/cli/mongocli/performanceadvisor/suggestedindexes/suggestedindexes.go deleted file mode 100644 index cb0b9fd55f..0000000000 --- a/internal/cli/mongocli/performanceadvisor/suggestedindexes/suggestedindexes.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package suggestedindexes - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "suggestedIndexes" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Get suggested indexes for collections experiencing slow queries", - } - cmd.AddCommand( - ListBuilder()) - - return cmd -} diff --git a/internal/cli/mongocli/performanceadvisor/suggestedindexes/suggestedindexes_test.go b/internal/cli/mongocli/performanceadvisor/suggestedindexes/suggestedindexes_test.go deleted file mode 100644 index 64779d201a..0000000000 --- a/internal/cli/mongocli/performanceadvisor/suggestedindexes/suggestedindexes_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package suggestedindexes - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/mongocli/serverless/backup/backup.go b/internal/cli/mongocli/serverless/backup/backup.go deleted file mode 100644 index 6519083b20..0000000000 --- a/internal/cli/mongocli/serverless/backup/backup.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/serverless/backup/restores" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/serverless/backup/snapshots" - "github.com/spf13/cobra" -) - -func baseCommand() *cobra.Command { - const use = "backups" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage cloud backups for your project.", - } - - return cmd -} - -func Builder() *cobra.Command { - cmd := baseCommand() - - cmd.AddCommand( - snapshots.Builder(), - restores.Builder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/backup_test.go b/internal/cli/mongocli/serverless/backup/backup_test.go deleted file mode 100644 index b494323458..0000000000 --- a/internal/cli/mongocli/serverless/backup/backup_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package backup - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/mongocli/serverless/backup/restores/create.go b/internal/cli/mongocli/serverless/backup/restores/create.go deleted file mode 100644 index e8a824b583..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/create.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas/commonerrors" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -const ( - automatedRestore = "automated" - downloadRestore = "download" - pointInTimeRestore = "pointInTime" -) - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - deliveryType string - clusterName string - targetProjectID string - targetClusterName string - oplogTS int - oplogInc int - snapshotID string - pointInTimeUTCMillis int - store store.ServerlessRestoreJobsCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var createTemplate = "Restore job '{{.ID}}' successfully started\n" - -var ErrInvalidDeliveryType = fmt.Errorf("delivery type invalid, choose 'automated', 'download' or 'pointInTime'") - -func (opts *CreateOpts) Run() error { - request := opts.newCloudProviderSnapshotRestoreJob() - r, err := opts.store.ServerlessCreateRestoreJobs(opts.ConfigProjectID(), opts.clusterName, request) - - if err != nil { - return commonerrors.Check(err) - } - - return opts.Print(r) -} - -func (opts *CreateOpts) newCloudProviderSnapshotRestoreJob() *atlasv2.ServerlessBackupRestoreJob { - request := new(atlasv2.ServerlessBackupRestoreJob) - request.DeliveryType = opts.deliveryType - - if opts.targetProjectID != "" { - request.TargetGroupId = opts.targetProjectID - } - - if opts.targetClusterName != "" { - request.TargetClusterName = opts.targetClusterName - } - - if opts.snapshotID != "" { - request.SnapshotId = &opts.snapshotID - } - - // Set only in pointInTimeRestore - if opts.oplogTS != 0 && opts.oplogInc != 0 { - request.OplogTs = &opts.oplogTS - request.OplogInc = &opts.oplogInc - } else if opts.pointInTimeUTCMillis != 0 { - // Set only when oplogTS and oplogInc are not set - request.PointInTimeUTCSeconds = &opts.pointInTimeUTCMillis - } - - return request -} - -func (opts *CreateOpts) isAutomatedRestore() bool { - return opts.deliveryType == automatedRestore -} - -func (opts *CreateOpts) isPointInTimeRestore() bool { - return opts.deliveryType == pointInTimeRestore -} - -func (opts *CreateOpts) isDownloadRestore() bool { - return opts.deliveryType == downloadRestore -} - -func markRequiredAutomatedRestoreFlags(cmd *cobra.Command) error { - if err := cmd.MarkFlagRequired(flag.TargetProjectID); err != nil { - return err - } - - if err := cmd.MarkFlagRequired(flag.SnapshotID); err != nil { - return err - } - - if err := cmd.MarkFlagRequired(flag.TargetClusterName); err != nil { - return err - } - - return cmd.MarkFlagRequired(flag.ClusterName) -} - -func markRequiredPointInTimeRestoreFlags(cmd *cobra.Command) error { - if err := cmd.MarkFlagRequired(flag.TargetProjectID); err != nil { - return err - } - - return cmd.MarkFlagRequired(flag.TargetClusterName) -} - -// atlas serverless backup(s) restore(s) job(s) create . -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - cmd := &cobra.Command{ - Use: "create", - Short: "Start a restore job for your serverless instance.", - Long: `If you create an automated or pointInTime restore job, Atlas removes all existing data on the target cluster prior to the restore. - -` + fmt.Sprintf("%s\n%s", fmt.Sprintf(usage.RequiredRole, "Project Owner"), "Atlas supports this command only for M10+ clusters."), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Create an automated restore: - %[1]s serverless backup restore create \ - --deliveryType automated \ - --clusterName myDemo \ - --snapshotId 5e7e00128f8ce03996a47179 \ - --targetClusterName myDemo2 \ - --targetProjectId 1a2345b67c8e9a12f3456de7 - - # Create a point-in-time restore: - %[1]s serverless backup restore create \ - --deliveryType pointInTime \ - --clusterName myDemo \ - --pointInTimeUTCMillis 1588523147 \ - --targetClusterName myDemo2 \ - --targetProjectId 1a2345b67c8e9a12f3456de7 - - # Create a download restore: - %[1]s serverless backup restore create \ - --deliveryType download \ - --clusterName myDemo \ - --snapshotId 5e7e00128f8ce03996a47179`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - set := false - - if opts.isAutomatedRestore() { - set = true - if err := markRequiredAutomatedRestoreFlags(cmd); err != nil { - return err - } - } - - if opts.isPointInTimeRestore() { - set = true - if err := markRequiredPointInTimeRestoreFlags(cmd); err != nil { - return err - } - } - - if opts.isDownloadRestore() { - set = true - if err := cmd.MarkFlagRequired(flag.SnapshotID); err != nil { - return err - } - } - - if !set { - return ErrInvalidDeliveryType - } - - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.snapshotID, flag.SnapshotID, "", usage.SnapshotID) - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - cmd.Flags().StringVar(&opts.deliveryType, flag.DeliveryType, "", usage.DeliveryType) - cmd.Flags().StringVar(&opts.targetProjectID, flag.TargetProjectID, "", usage.TargetProjectID) - cmd.Flags().StringVar(&opts.targetClusterName, flag.TargetClusterName, "", usage.TargetClusterName) - cmd.Flags().IntVar(&opts.oplogTS, flag.OplogTS, 0, usage.OplogTS) - cmd.Flags().IntVar(&opts.oplogInc, flag.OplogInc, 0, usage.OplogInc) - cmd.Flags().IntVar(&opts.pointInTimeUTCMillis, flag.PointInTimeUTCMillis, 0, usage.PointInTimeUTCMillis) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - _ = cmd.MarkFlagRequired(flag.DeliveryType) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/restores/create_test.go b/internal/cli/mongocli/serverless/backup/restores/create_test.go deleted file mode 100644 index 78180330b1..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/create_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package restores - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessRestoreJobsCreator(ctrl) - - expected := &atlasv2.ServerlessBackupRestoreJob{} - - t.Run(automatedRestore, func(t *testing.T) { - listOpts := &CreateOpts{ - store: mockStore, - deliveryType: automatedRestore, - clusterName: "Cluster0", - targetClusterName: "Cluster1", - targetProjectID: "1", - } - - mockStore. - EXPECT(). - ServerlessCreateRestoreJobs(listOpts.ProjectID, "Cluster0", listOpts.newCloudProviderSnapshotRestoreJob()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - - t.Run(pointInTimeRestore, func(t *testing.T) { - listOpts := &CreateOpts{ - store: mockStore, - deliveryType: pointInTimeRestore, - clusterName: "Cluster0", - targetClusterName: "Cluster1", - targetProjectID: "1", - } - - mockStore. - EXPECT(). - ServerlessCreateRestoreJobs(listOpts.ProjectID, "Cluster0", listOpts.newCloudProviderSnapshotRestoreJob()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - - t.Run(downloadRestore, func(t *testing.T) { - listOpts := &CreateOpts{ - store: mockStore, - deliveryType: downloadRestore, - clusterName: "Cluster0", - } - - mockStore. - EXPECT(). - ServerlessCreateRestoreJobs(listOpts.ProjectID, "Cluster0", listOpts.newCloudProviderSnapshotRestoreJob()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{ - flag.DeliveryType, - flag.SnapshotID, - flag.ClusterName, - flag.TargetProjectID, - flag.TargetClusterName, - flag.OplogTS, - flag.OplogInc, - flag.ProjectID, - flag.Output, - }, - ) -} diff --git a/internal/cli/mongocli/serverless/backup/restores/describe.go b/internal/cli/mongocli/serverless/backup/restores/describe.go deleted file mode 100644 index 02e10a4b7b..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/describe.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - id string - clusterName string - store store.ServerlessRestoreJobsDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var restoreDescribeTemplate = `ID SNAPSHOT CLUSTER TYPE EXPIRES AT URLs -{{.Id}} {{.SnapshotId}} {{.TargetClusterName}} {{.DeliveryType}} {{.ExpiresAt}} {{range $index, $element := .DeliveryUrl}}{{if $index}}; {{end}}{{$element}}{{end}} -` - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.ServerlessRestoreJob(opts.ConfigProjectID(), opts.clusterName, opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// atlas serverless backup(s) restore(s) job(s) describe. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe", - Short: "Describe a cloud backup restore job.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return the details for the continuous backup restore job with the ID 507f1f77bcf86cd799439011 for the serverless isntance named Cluster0: - %s serverless backup restore describe --restoreJobId 507f1f77bcf86cd799439011 --clusterName Cluster0`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), restoreDescribeTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.id, flag.RestoreJobID, "", usage.RestoreJobID) - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - _ = cmd.MarkFlagRequired(flag.RestoreJobID) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/restores/describe_test.go b/internal/cli/mongocli/serverless/backup/restores/describe_test.go deleted file mode 100644 index d0d518311a..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/describe_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package restores - -import ( - "bytes" - "testing" - "time" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/pointer" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessRestoreJobsDescriber(ctrl) - - expiresAt, _ := time.Parse("01-02-2006", "01-01-2023") - expected := &atlasv2.ServerlessBackupRestoreJob{ - Id: pointer.Get("test"), - SnapshotId: pointer.Get("test2"), - TargetClusterName: "ClusterTest", - DeliveryType: "test type", - ExpiresAt: pointer.Get(expiresAt), - DeliveryUrl: &[]string{"test url"}, - } - - buf := new(bytes.Buffer) - - describeOpts := &DescribeOpts{ - store: mockStore, - clusterName: "Cluster0", - id: "1", - OutputOpts: cli.OutputOpts{ - Template: restoreDescribeTemplate, - OutWriter: buf, - }, - } - - mockStore. - EXPECT(). - ServerlessRestoreJob(describeOpts.ProjectID, describeOpts.clusterName, describeOpts.id). - Return(expected, nil). - Times(1) - - require.NoError(t, describeOpts.Run()) - - assert.Equal(t, `ID SNAPSHOT CLUSTER TYPE EXPIRES AT URLs -test test2 ClusterTest test type 2023-01-01 00:00:00 +0000 UTC test url -`, buf.String()) -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{ - flag.ClusterName, - flag.ProjectID, - flag.Output, - }, - ) -} diff --git a/internal/cli/mongocli/serverless/backup/restores/list.go b/internal/cli/mongocli/serverless/backup/restores/list.go deleted file mode 100644 index 068bb59607..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/list.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - clusterName string - store store.ServerlessRestoreJobsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var restoreListTemplate = `ID SNAPSHOT CLUSTER TYPE EXPIRES AT{{range valueOrEmptySlice .Results}} -{{.Id}} {{.SnapshotId}} {{.TargetClusterName}} {{.DeliveryType}} {{.ExpiresAt}}{{end}} -` - -func (opts *ListOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.ServerlessRestoreJobs(opts.ConfigProjectID(), opts.clusterName, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas backup(s) restore(s) job(s) list [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list ", - Aliases: []string{"ls"}, - Short: "Return all cloud backup restore jobs for the specified serverless instance in your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Label that identifies the Atlas serverless instance for which you want to return restore jobs.", - "output": restoreListTemplate, - }, - Example: fmt.Sprintf(` # Return all continuous backup restore jobs for the serverless instance Instance0: - %s serverless backup restore list Instance0`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), restoreListTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.clusterName = args[0] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/restores/list_test.go b/internal/cli/mongocli/serverless/backup/restores/list_test.go deleted file mode 100644 index 72f027e689..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/list_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package restores - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessRestoreJobsLister(ctrl) - defer ctrl.Finish() - - expected := &atlasv2.PaginatedApiAtlasServerlessBackupRestoreJob{} - - listOpts := &ListOpts{ - store: mockStore, - clusterName: "Cluster0", - } - - mockStore. - EXPECT(). - ServerlessRestoreJobs(listOpts.ProjectID, "Cluster0", listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{ - flag.Page, - flag.Limit, - flag.ProjectID, - flag.Output, - }, - ) -} diff --git a/internal/cli/mongocli/serverless/backup/restores/restores.go b/internal/cli/mongocli/serverless/backup/restores/restores.go deleted file mode 100644 index 62a6f27500..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/restores.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "restores" - cmd := &cobra.Command{ - Use: use, - Short: "Manage cloud backup restore jobs for your project.", - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - WatchBuilder(), - CreateBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/restores/restores_test.go b/internal/cli/mongocli/serverless/backup/restores/restores_test.go deleted file mode 100644 index 3a3c3e481c..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/restores_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 4, - []string{}, - ) -} diff --git a/internal/cli/mongocli/serverless/backup/restores/watch.go b/internal/cli/mongocli/serverless/backup/restores/watch.go deleted file mode 100644 index ef155786a5..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/watch.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package restores - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -type WatchOpts struct { - cli.GlobalOpts - cli.WatchOpts - id string - clusterName string - store store.ServerlessRestoreJobsDescriber -} - -var result *atlasv2.ServerlessBackupRestoreJob - -func (opts *WatchOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *WatchOpts) watcher() (any, bool, error) { - var err error - result, err = opts.store.ServerlessRestoreJob(opts.ConfigProjectID(), opts.clusterName, opts.id) - if err != nil { - return nil, false, err - } - return nil, result.GetExpired() || result.GetCancelled() || result.GetFailed() || result.HasFinishedAt(), nil -} - -func (opts *WatchOpts) Run() error { - if _, err := opts.Watch(opts.watcher); err != nil { - return err - } - - return opts.Print(result) -} - -// WatchBuilder atlas serverless backup(s) restore(s) watch. -func WatchBuilder() *cobra.Command { - opts := new(WatchOpts) - cmd := &cobra.Command{ - Use: "watch", - Short: "Watch the specified backup restore job until it completes.", - Long: `This command checks the restore job's status periodically until it reaches a completed, failed or canceled status. -Command finishes once one of the expected statuses are reached. -If you run the command in the terminal, it blocks the terminal session until the resource status completes or fails. -You can interrupt the command's polling at any time with CTRL-C. -` + fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Watch the continuous backup restore job with the ID 507f1f77bcf86cd799439011 for the cluster named Cluster0 until it becomes available: - %s serverless backup restore watch --restoreJobId 507f1f77bcf86cd799439011 --clusterName Cluster0`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), "\nRestore completed.\n"), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVar(&opts.id, flag.RestoreJobID, "", usage.RestoreJobID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - _ = cmd.MarkFlagRequired(flag.RestoreJobID) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/restores/watch_test.go b/internal/cli/mongocli/serverless/backup/restores/watch_test.go deleted file mode 100644 index aa8c53f812..0000000000 --- a/internal/cli/mongocli/serverless/backup/restores/watch_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package restores - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/pointer" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestWatchBuilder(t *testing.T) { - test.CmdValidator( - t, - WatchBuilder(), - 0, - []string{ - flag.ClusterName, - flag.ProjectID, - flag.Output, - }, - ) -} - -func TestWatchOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessRestoreJobsDescriber(ctrl) - - expected := &atlasv2.ServerlessBackupRestoreJob{ - Failed: pointer.Get(true), - } - - describeOpts := &WatchOpts{ - store: mockStore, - clusterName: "Cluster0", - id: "1", - } - - mockStore. - EXPECT(). - ServerlessRestoreJob(describeOpts.ProjectID, describeOpts.clusterName, describeOpts.id). - Return(expected, nil). - Times(1) - - if err := describeOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/serverless/backup/snapshots/describe.go b/internal/cli/mongocli/serverless/backup/snapshots/describe.go deleted file mode 100644 index b6cbe683dc..0000000000 --- a/internal/cli/mongocli/serverless/backup/snapshots/describe.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package snapshots - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const describeTemplate = `ID SNAPSHOT TYPE EXPIRES AT -{{.ID}} {{.SnapshotType}} {{.ExpiresAt}} -` - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.ServerlessSnapshotsDescriber - snapshot string - clusterName string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.ServerlessSnapshot(opts.ConfigProjectID(), opts.clusterName, opts.snapshot) - if err != nil { - return err - } - - return opts.Print(r) -} - -// atlas backup snapshots describe --snapshotId snapshotId --clusterName clusterName --projectId projectId. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe", - Short: "Return the details for the specified snapshot for your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Args: require.NoArgs, - Example: fmt.Sprintf(` # Return the details for the backup snapshot with the ID 5f4007f327a3bd7b6f4103c5 for the instance named myDemo: - %s serverless backups snapshots describe --snapshotId 5f4007f327a3bd7b6f4103c5 --clusterName myDemo`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - cmd.Flags().StringVar(&opts.snapshot, flag.SnapshotID, "", usage.SnapshotID) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - _ = cmd.MarkFlagRequired(flag.SnapshotID) - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/snapshots/describe_test.go b/internal/cli/mongocli/serverless/backup/snapshots/describe_test.go deleted file mode 100644 index e081ed9d08..0000000000 --- a/internal/cli/mongocli/serverless/backup/snapshots/describe_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessSnapshotsDescriber(ctrl) - - var expected atlasv2.ServerlessBackupSnapshot - - describeOpts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ServerlessSnapshot(describeOpts.ProjectID, describeOpts.clusterName, describeOpts.snapshot). - Return(&expected, nil). - Times(1) - - if err := describeOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/serverless/backup/snapshots/list.go b/internal/cli/mongocli/serverless/backup/snapshots/list.go deleted file mode 100644 index 7879ffb14c..0000000000 --- a/internal/cli/mongocli/serverless/backup/snapshots/list.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - clusterName string - store store.ServerlessSnapshotsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `ID TYPE STATUS CREATED AT EXPIRES AT{{range valueOrEmptySlice .Results}} -{{.ID}} {{.SnapshotType}} {{.Status}} {{.CreatedAt}} {{.ExpiresAt}}{{end}} -` - -func (opts *ListOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.ServerlessSnapshots(opts.ConfigProjectID(), opts.clusterName, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// atlas serverless backups snapshots list [--projectId projectId] [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list ", - Short: "Return all cloud backup snapshots for the specified serverless instance in your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Aliases: []string{"ls"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Label that identifies the Atlas serverless instance that contains the snapshots you want to return.", - "output": listTemplate, - }, - Example: fmt.Sprintf(` # Return a JSON-formatted list of snapshots for the instance named myDemo - %s serverless backups snapshots list myDemo --output json`, cli.ExampleAtlasEntryPoint()), - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.clusterName = args[0] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/snapshots/list_test.go b/internal/cli/mongocli/serverless/backup/snapshots/list_test.go deleted file mode 100644 index b2c2c9f156..0000000000 --- a/internal/cli/mongocli/serverless/backup/snapshots/list_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessSnapshotsLister(ctrl) - - expected := &atlasv2.PaginatedApiAtlasServerlessBackupSnapshot{} - - listOpts := &ListOpts{ - store: mockStore, - clusterName: "Cluster0", - } - - mockStore. - EXPECT(). - ServerlessSnapshots(listOpts.ProjectID, "Cluster0", listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/serverless/backup/snapshots/snapshots.go b/internal/cli/mongocli/serverless/backup/snapshots/snapshots.go deleted file mode 100644 index b387671afb..0000000000 --- a/internal/cli/mongocli/serverless/backup/snapshots/snapshots.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "snapshots" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage cloud backup snapshots for your project.", - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - WatchBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/snapshots/snapshots_test.go b/internal/cli/mongocli/serverless/backup/snapshots/snapshots_test.go deleted file mode 100644 index 637d50c9fb..0000000000 --- a/internal/cli/mongocli/serverless/backup/snapshots/snapshots_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} diff --git a/internal/cli/mongocli/serverless/backup/snapshots/watch.go b/internal/cli/mongocli/serverless/backup/snapshots/watch.go deleted file mode 100644 index 77e513a588..0000000000 --- a/internal/cli/mongocli/serverless/backup/snapshots/watch.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type WatchOpts struct { - cli.GlobalOpts - cli.WatchOpts - id string - clusterName string - store store.ServerlessSnapshotsDescriber -} - -func (opts *WatchOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *WatchOpts) watcher() (any, bool, error) { - result, err := opts.store.ServerlessSnapshot(opts.ConfigProjectID(), opts.clusterName, opts.id) - if err != nil { - return nil, false, err - } - return nil, result.GetStatus() == "completed" || result.GetStatus() == "failed", nil -} - -func (opts *WatchOpts) Run() error { - if _, err := opts.Watch(opts.watcher); err != nil { - return err - } - - return opts.Print(nil) -} - -// atlas serverless snapshot(s) watch --snapshotId --clusterName clusterName [--projectId projectId]. -func WatchBuilder() *cobra.Command { - opts := &WatchOpts{} - cmd := &cobra.Command{ - Use: "watch", - Short: "Watch the specified snapshot in your project until it reaches a completed or failed status.", - Long: `This command checks the snapshot's status periodically until it reaches a completed or failed status. -Command finishes once one of the expected statuses are reached. -If you run the command in the terminal, it blocks the terminal session until the resource status completes or fails. -You can interrupt the command's polling at any time with CTRL-C. -` + fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Example: fmt.Sprintf(` # Watch the backup snapshot with the ID 5f4007f327a3bd7b6f4103c5 in the cluster named myDemo until it becomes available: - %s backups snapshots watch 5f4007f327a3bd7b6f4103c5 --clusterName myDemo`, cli.ExampleAtlasEntryPoint()), - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), "\nSnapshot changes completed.\n"), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName) - cmd.Flags().StringVar(&opts.id, flag.SnapshotID, "", usage.SnapshotID) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.ClusterName) - _ = cmd.MarkFlagRequired(flag.SnapshotID) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/backup/snapshots/watch_test.go b/internal/cli/mongocli/serverless/backup/snapshots/watch_test.go deleted file mode 100644 index d57328b827..0000000000 --- a/internal/cli/mongocli/serverless/backup/snapshots/watch_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/pointer" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestWatch_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessSnapshotsDescriber(ctrl) - - watchOpts := &WatchOpts{ - id: "test", - store: mockStore, - clusterName: "cluster", - } - - expected := &atlasv2.ServerlessBackupSnapshot{Status: pointer.Get("completed")} - - mockStore. - EXPECT(). - ServerlessSnapshot(watchOpts.ProjectID, watchOpts.clusterName, watchOpts.id). - Return(expected, nil). - Times(1) - - if err := watchOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/serverless/create.go b/internal/cli/mongocli/serverless/create.go deleted file mode 100644 index 48d3a6a314..0000000000 --- a/internal/cli/mongocli/serverless/create.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package serverless - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/pointer" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -const providerName = "SERVERLESS" - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - instanceName string - provider string - region string - store store.ServerlessInstanceCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var createTemplate = "Serverless instance {{.Name}} created.\n" - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateServerlessInstance(opts.ConfigProjectID(), opts.newServerlessCreateRequestParams()) - target, ok := atlasv2.AsError(err) - if ok && target.GetErrorCode() == "INVALID_REGION" { - return cli.ErrNoRegionExistsTryCommand - } else if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *CreateOpts) newServerlessCreateRequestParams() *atlasv2.ServerlessInstanceDescriptionCreate { - return &atlasv2.ServerlessInstanceDescriptionCreate{ - Name: opts.instanceName, - ProviderSettings: atlasv2.ServerlessProviderSettings{ - BackingProviderName: opts.provider, - ProviderName: pointer.Get(providerName), - RegionName: opts.region, - }, - } -} - -// mongocli atlas serverless|sl create --backingProviderName backingProviderName --providerName providerName --regionName regionName [--projectId projectId]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - cmd := &cobra.Command{ - Use: "create ", - Short: "Creates one serverless instance in the specified project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "instanceNameDesc": "Human-readable label that identifies your serverless instance.", - "output": createTemplate, - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.instanceName = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.provider, flag.Provider, "", usage.ServerlessProvider) - cmd.Flags().StringVar(&opts.region, flag.Region, "", usage.ServerlessRegion) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Provider) - _ = cmd.MarkFlagRequired(flag.Region) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/create_test.go b/internal/cli/mongocli/serverless/create_test.go deleted file mode 100644 index 8c4c2f9632..0000000000 --- a/internal/cli/mongocli/serverless/create_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverless - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestCreateOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessInstanceCreator(ctrl) - - opts := &CreateOpts{ - store: mockStore, - } - - expected := &atlasv2.ServerlessInstanceDescription{} - mockStore. - EXPECT(). - CreateServerlessInstance(opts.ProjectID, opts.newServerlessCreateRequestParams()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Provider, flag.Region}, - ) -} diff --git a/internal/cli/mongocli/serverless/delete.go b/internal/cli/mongocli/serverless/delete.go deleted file mode 100644 index 1e14b20d0f..0000000000 --- a/internal/cli/mongocli/serverless/delete.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package serverless - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.ServerlessInstanceDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteServerlessInstance, opts.ConfigProjectID()) -} - -// mongocli atlas serverless|sl delete --projectId projectId [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Serverless instance '%s' deleted\n", "Serverless instance not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Remove a serverless instance from your project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "instanceNameDesc": "Name of the instance to delete.", - "output": opts.SuccessMessage(), - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/delete_test.go b/internal/cli/mongocli/serverless/delete_test.go deleted file mode 100644 index 9694f5bddb..0000000000 --- a/internal/cli/mongocli/serverless/delete_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverless - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessInstanceDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "test", - }, - store: mockStore, - } - - mockStore. - EXPECT(). - DeleteServerlessInstance(deleteOpts.ProjectID, deleteOpts.Entry). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force, flag.ProjectID}, - ) -} diff --git a/internal/cli/mongocli/serverless/describe.go b/internal/cli/mongocli/serverless/describe.go deleted file mode 100644 index 4f7817a646..0000000000 --- a/internal/cli/mongocli/serverless/describe.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package serverless - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var describeTemplate = `ID NAME MDB VER STATE -{{.Id}} {{.Name}} {{.MongoDBVersion}} {{.StateName}} -` - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.ServerlessInstanceDescriber - instanceName string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GetServerlessInstance(opts.ConfigProjectID(), opts.instanceName) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas serverless|sl describe --projectId projectId. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe ", - Short: "Return one serverless instance in the specified project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "instanceNameDesc": "Human-readable label that identifies your serverless instance.", - "output": describeTemplate, - }, - Aliases: []string{"get"}, - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.instanceName = args[0] - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/describe_test.go b/internal/cli/mongocli/serverless/describe_test.go deleted file mode 100644 index ba3c32c2a6..0000000000 --- a/internal/cli/mongocli/serverless/describe_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverless - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessInstanceDescriber(ctrl) - - var expected atlasv2.ServerlessInstanceDescription - - describeOpts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GetServerlessInstance(describeOpts.ConfigProjectID(), describeOpts.instanceName). - Return(&expected, nil). - Times(1) - - if err := describeOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.ProjectID, flag.Output}, - ) -} diff --git a/internal/cli/mongocli/serverless/list.go b/internal/cli/mongocli/serverless/list.go deleted file mode 100644 index 53a50e5c57..0000000000 --- a/internal/cli/mongocli/serverless/list.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package serverless - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var listTemplate = `ID NAME MDB VER STATE{{range valueOrEmptySlice .Results}} -{{.Id}} {{.Name}} {{.MongoDBVersion}} {{.StateName}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.ServerlessInstanceLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.ServerlessInstances(opts.ConfigProjectID(), listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas serverless|sl list [--projectId projectId] [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Short: "Return all serverless instances in the specified project.", - Long: fmt.Sprintf(usage.RequiredRole, "Project Read Only"), - Aliases: []string{"ls"}, - Annotations: map[string]string{ - "output": listTemplate, - }, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/list_test.go b/internal/cli/mongocli/serverless/list_test.go deleted file mode 100644 index 5be18b53c6..0000000000 --- a/internal/cli/mongocli/serverless/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverless - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Limit, flag.Page, flag.Output, flag.ProjectID}, - ) -} - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessInstanceLister(ctrl) - - var expected *atlasv2.PaginatedServerlessInstanceDescription - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ServerlessInstances(listOpts.ProjectID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/mongocli/serverless/serverless.go b/internal/cli/mongocli/serverless/serverless.go deleted file mode 100644 index aae7ba372e..0000000000 --- a/internal/cli/mongocli/serverless/serverless.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package serverless - -import ( - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "serverless" - cmd := &cobra.Command{ - Use: use, - Aliases: []string{"sl"}, - Short: "Manage serverless instances for your project.", - Long: `The serverless command provides access to your serverless instance configurations. You can create, edit, and delete serverless instances.`, - } - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - DeleteBuilder(), - CreateBuilder(), - WatchBuilder(), - ) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/serverless_test.go b/internal/cli/mongocli/serverless/serverless_test.go deleted file mode 100644 index 75cbbc46ee..0000000000 --- a/internal/cli/mongocli/serverless/serverless_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverless - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/mongocli/serverless/watch.go b/internal/cli/mongocli/serverless/watch.go deleted file mode 100644 index e38e22277e..0000000000 --- a/internal/cli/mongocli/serverless/watch.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package serverless - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type WatchOpts struct { - cli.GlobalOpts - cli.WatchOpts - name string - store store.ServerlessInstanceDescriber -} - -func (opts *WatchOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *WatchOpts) watcher() (any, bool, error) { - result, err := opts.store.GetServerlessInstance(opts.ConfigProjectID(), opts.name) - if err != nil { - return nil, false, err - } - const desiredState = "IDLE" - return nil, *result.StateName == desiredState, nil -} - -func (opts *WatchOpts) Run() error { - if _, err := opts.Watch(opts.watcher); err != nil { - return err - } - - return opts.Print(nil) -} - -// mongocli atlas serverless|sl watch [--projectId projectId]. -func WatchBuilder() *cobra.Command { - opts := &WatchOpts{} - cmd := &cobra.Command{ - Use: "watch ", - Short: "Monitor the status of serverless instance.", - Long: `This command checks the serverless instance's state periodically until the instance reaches an IDLE state. -Once the instance reaches the expected state, the command prints "Instance available." -If you run the command in the terminal, it blocks the terminal session until the resource becomes idle. -You can interrupt the command's polling at any time with CTRL-C. - -` + fmt.Sprintf(usage.RequiredRole, "Project Owner"), - Example: fmt.Sprintf(` %s serverless watch instanceNameSample`, cli.ExampleAtlasEntryPoint()), - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "instanceNameDesc": "Name of the instance to watch.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), "\nInstance available.\n"), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.name = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/mongocli/serverless/watch_test.go b/internal/cli/mongocli/serverless/watch_test.go deleted file mode 100644 index 589c26a62d..0000000000 --- a/internal/cli/mongocli/serverless/watch_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverless - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -func TestWatch_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerlessInstanceDescriber(ctrl) - - state := "IDLE" - expected := &atlasv2.ServerlessInstanceDescription{StateName: &state} - - opts := &WatchOpts{ - name: "test", - store: mockStore, - } - - mockStore. - EXPECT(). - GetServerlessInstance(opts.ProjectID, opts.name). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestWatchBuilder(t *testing.T) { - test.CmdValidator( - t, - WatchBuilder(), - 0, - []string{flag.ProjectID}, - ) -} diff --git a/internal/cli/opsmanager/admin/admin.go b/internal/cli/opsmanager/admin/admin.go deleted file mode 100644 index 641184c3f6..0000000000 --- a/internal/cli/opsmanager/admin/admin.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package admin - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup/blockstore" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup/filesystem" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup/oplog" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup/s3" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup/sync" - "github.com/spf13/cobra" -) - -func BackupBuilder() *cobra.Command { - const use = "backups" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup administration.", - } - - cmd.AddCommand( - blockstore.Builder(), - filesystem.Builder(), - s3.Builder(), - oplog.Builder(), - sync.Builder(), - ) - - return cmd -} - -func Builder() *cobra.Command { - const use = "admin" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup administration.", - } - - cmd.AddCommand( - BackupBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/admin_test.go b/internal/cli/opsmanager/admin/admin_test.go deleted file mode 100644 index 4457725d3a..0000000000 --- a/internal/cli/opsmanager/admin/admin_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package admin - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} - -func TestBackupBuilder(t *testing.T) { - test.CmdValidator( - t, - BackupBuilder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/backup.go b/internal/cli/opsmanager/admin/backup/backup.go deleted file mode 100644 index 5df454c0c1..0000000000 --- a/internal/cli/opsmanager/admin/backup/backup.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "go.mongodb.org/ops-manager/opsmngr" -) - -type AdminOpts struct { - Assignment bool - EncryptedCredentials bool - SSL bool - WriteConcern string - URI string - LoadFactor int64 - MaxCapacityGB int64 - ID string - Label []string -} - -func (opts *AdminOpts) NewBackupStore() *opsmngr.BackupStore { - backupStore := &opsmngr.BackupStore{ - AdminBackupConfig: opsmngr.AdminBackupConfig{ - ID: opts.ID, - URI: opts.URI, - WriteConcern: opts.WriteConcern, - Labels: opts.Label, - }, - } - - if opts.SSL { - backupStore.SSL = &opts.SSL - } - - if opts.EncryptedCredentials { - backupStore.EncryptedCredentials = &opts.EncryptedCredentials - } - - if opts.Assignment { - backupStore.AssignmentEnabled = &opts.Assignment - } - - if opts.MaxCapacityGB != 0 { - backupStore.MaxCapacityGB = &opts.MaxCapacityGB - } - - if opts.LoadFactor != 0 { - backupStore.LoadFactor = &opts.LoadFactor - } - - return backupStore -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/blockstore.go b/internal/cli/opsmanager/admin/backup/blockstore/blockstore.go deleted file mode 100644 index bb56ee5231..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/blockstore.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package blockstore - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "blockstores" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup blockstore configurations.", - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - CreateBuilder(), - UpdateBuilder(), - DeleteBuilder(), - ) - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/blockstore_test.go b/internal/cli/opsmanager/admin/backup/blockstore/blockstore_test.go deleted file mode 100644 index 64e6c47e56..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/blockstore_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package blockstore - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/create.go b/internal/cli/opsmanager/admin/backup/blockstore/create.go deleted file mode 100644 index ca611c6664..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/create.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package blockstore - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var createTemplate = "Blockstore configuration '{{.ID}}' created.\n" - -type CreateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.BlockstoresCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateBlockstore(opts.NewBackupStore()) - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli ops-manager admin backup blockstore(s) create [--assignment][--encryptedCredentials][--name name] -// [--label label][--loadFactor loadFactor][--maxCapacityGB maxCapacityGB][--uri uri][--ssl][--writeConcern writeConcern]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "create", - Short: "Create a backup blockstore configuration.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.BlockstoreAssignment) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - cmd.Flags().StringVar(&opts.ID, flag.Name, "", usage.BlockstoreName) - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label) - cmd.Flags().Int64Var(&opts.LoadFactor, flag.LoadFactor, 0, usage.LoadFactor) - cmd.Flags().Int64Var(&opts.MaxCapacityGB, flag.MaxCapacityGB, 0, usage.MaxCapacityGB) - cmd.Flags().StringVar(&opts.URI, flag.URI, "", usage.BlockstoreURI) - cmd.Flags().BoolVar(&opts.SSL, flag.SSL, false, usage.BlockstoreSSL) - cmd.Flags().StringVar(&opts.WriteConcern, flag.WriteConcern, "", usage.WriteConcern) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Name) - _ = cmd.MarkFlagRequired(flag.URI) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/create_test.go b/internal/cli/opsmanager/admin/backup/blockstore/create_test.go deleted file mode 100644 index 6292cf84bd..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/create_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package blockstore - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockBlockstoresCreator(ctrl) - - expected := &opsmngr.BackupStore{} - - createOpts := &CreateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().CreateBlockstore(createOpts.NewBackupStore()). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Output, flag.Name, flag.SSL, flag.EncryptedCredentials, flag.LoadFactor, - flag.MaxCapacityGB, flag.Assignment, flag.Label, flag.URI, flag.WriteConcern}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/delete.go b/internal/cli/opsmanager/admin/backup/blockstore/delete.go deleted file mode 100644 index f2cbb846ea..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/delete.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package blockstore - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.BlockstoresDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteBlockstore) -} - -// mongocli ops-manager admin backup blockstore(s) delete [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Blockstore configuration '%s' deleted\n", "Blockstore configuration not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Delete a backup blockstore configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Blockstore identifier.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/delete_test.go b/internal/cli/opsmanager/admin/backup/blockstore/delete_test.go deleted file mode 100644 index db23aed23a..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/delete_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package blockstore - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockBlockstoresDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteBlockstore(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - opts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/describe.go b/internal/cli/opsmanager/admin/backup/blockstore/describe.go deleted file mode 100644 index 485ba97565..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/describe.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package blockstore - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var describeTemplate = `NAME URI SSL LOAD FACTOR -{{.ID}} {{.URI}} {{.SSL}} {{.LoadFactor}} -` - -type DescribeOpts struct { - cli.OutputOpts - store store.BlockstoresDescriber - blockstoreID string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.DescribeBlockstore(opts.blockstoreID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup blockstore(s) describe . -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Short: "Get a backup blockstore configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Blockstore identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.blockstoreID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/describe_test.go b/internal/cli/opsmanager/admin/backup/blockstore/describe_test.go deleted file mode 100644 index 7e93c2fa0e..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package blockstore - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockBlockstoresDescriber(ctrl) - - expected := &opsmngr.BackupStore{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT().DescribeBlockstore(opts.blockstoreID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/list.go b/internal/cli/opsmanager/admin/backup/blockstore/list.go deleted file mode 100644 index e8227b3162..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/list.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package blockstore - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var listTemplate = `NAME URI SSL LOAD FACTOR{{range valueOrEmptySlice .Results}} -{{.ID}} {{.URI}} {{.SSL}} {{.LoadFactor}}{{end}} -` - -type ListOpts struct { - cli.OutputOpts - cli.ListOpts - store store.BlockstoresLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.ListBlockstores(opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup blockstore(s) lists. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Short: "List backup blockstore configurations.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/list_test.go b/internal/cli/opsmanager/admin/backup/blockstore/list_test.go deleted file mode 100644 index 68c8b8048c..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package blockstore - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockBlockstoresLister(ctrl) - - expected := &opsmngr.BackupStores{} - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ListBlockstores(opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/update.go b/internal/cli/opsmanager/admin/backup/blockstore/update.go deleted file mode 100644 index 389a69e9d8..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/update.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package blockstore - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var updateTemplate = "Blockstore configuration '{{.ID}}' updated.\n" - -type UpdateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.BlockstoresUpdater -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateBlockstore(opts.NewBackupStore()) - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli ops-manager admin backup blockstore(s) update [--assignment][--encryptedCredentials] -// [--label label][--loadFactor loadFactor][--maxCapacityGB maxCapacityGB][--uri uri][--ssl][--writeConcern writeConcern]. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update ", - Short: "Update a backup blockstore configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Blockstore identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.ID = args[0] - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.BlockstoreAssignment) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label+usage.UpdateWarning) - cmd.Flags().Int64Var(&opts.LoadFactor, flag.LoadFactor, 0, usage.LoadFactor) - cmd.Flags().Int64Var(&opts.MaxCapacityGB, flag.MaxCapacityGB, 0, usage.MaxCapacityGB) - cmd.Flags().StringVar(&opts.URI, flag.URI, "", usage.BlockstoreURI) - cmd.Flags().BoolVar(&opts.SSL, flag.SSL, false, usage.BlockstoreSSL) - cmd.Flags().StringVar(&opts.WriteConcern, flag.WriteConcern, "", usage.WriteConcern) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/blockstore/update_test.go b/internal/cli/opsmanager/admin/backup/blockstore/update_test.go deleted file mode 100644 index 4a9394ac09..0000000000 --- a/internal/cli/opsmanager/admin/backup/blockstore/update_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package blockstore - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockBlockstoresUpdater(ctrl) - - expected := &opsmngr.BackupStore{} - - opts := &UpdateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateBlockstore(opts.NewBackupStore()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Output, flag.SSL, flag.EncryptedCredentials, flag.LoadFactor, - flag.MaxCapacityGB, flag.Assignment, flag.Label, flag.URI, flag.WriteConcern}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/create.go b/internal/cli/opsmanager/admin/backup/filesystem/create.go deleted file mode 100644 index 996acf1d65..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/create.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filesystem - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -var createTemplate = "File System configuration '{{.ID}}' created.\n" - -type CreateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.FileSystemsCreator - mmapv1CompressionSetting string - storePath string - wtCompressionSetting string -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateFileSystems(opts.newFileSystemConfiguration()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *CreateOpts) newFileSystemConfiguration() *opsmngr.FileSystemStoreConfiguration { - return &opsmngr.FileSystemStoreConfiguration{ - BackupStore: *opts.NewBackupStore(), - MMAPV1CompressionSetting: opts.mmapv1CompressionSetting, - StorePath: opts.storePath, - WTCompressionSetting: opts.wtCompressionSetting, - } -} - -// mongocli ops-manager admin backup fileSystem(s) create [--assignment][--encryptedCredentials] -// [--label label][--loadFactor loadFactor][--name name][--storePath storePath][--mmapv1CompressionSetting mmapv1CompressionSetting] -// [--wtCompressionSetting wtCompressionSetting]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "create", - Short: "Create a file system configuration.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.FileSystemAssignment) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - cmd.Flags().StringVar(&opts.ID, flag.Name, "", usage.FileSystemName) - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label) - cmd.Flags().Int64Var(&opts.LoadFactor, flag.LoadFactor, 0, usage.LoadFactor) - cmd.Flags().StringVar(&opts.mmapv1CompressionSetting, flag.MMAPV1CompressionSetting, "", usage.MMAPV1CompressionSetting) - cmd.Flags().StringVar(&opts.wtCompressionSetting, flag.WTCompressionSetting, "", usage.WTCompressionSetting) - cmd.Flags().StringVar(&opts.storePath, flag.StorePath, "", usage.StorePath) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Name) - _ = cmd.MarkFlagRequired(flag.StorePath) - _ = cmd.MarkFlagRequired(flag.MMAPV1CompressionSetting) - _ = cmd.MarkFlagRequired(flag.WTCompressionSetting) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/create_test.go b/internal/cli/opsmanager/admin/backup/filesystem/create_test.go deleted file mode 100644 index cb3a99bfbe..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/create_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package filesystem - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockFileSystemsCreator(ctrl) - - expected := &opsmngr.FileSystemStoreConfiguration{} - - createOpts := &CreateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().CreateFileSystems(createOpts.newFileSystemConfiguration()). - Return(expected, nil). - Times(1) - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Output, flag.Name, flag.EncryptedCredentials, flag.LoadFactor, - flag.WTCompressionSetting, flag.StorePath, flag.Label, flag.MMAPV1CompressionSetting, flag.Assignment}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/delete.go b/internal/cli/opsmanager/admin/backup/filesystem/delete.go deleted file mode 100644 index bb714988aa..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/delete.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filesystem - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.FileSystemsDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteFileSystem) -} - -// // mongocli ops-manager admin backup fileSystem(s) delete [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("File system configuration '%s' deleted\n", "File system configuration not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Delete a file system configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Configuration identifier.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/delete_test.go b/internal/cli/opsmanager/admin/backup/filesystem/delete_test.go deleted file mode 100644 index 58b149ce8b..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/delete_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package filesystem - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockFileSystemsDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteFileSystem(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - opts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/describe.go b/internal/cli/opsmanager/admin/backup/filesystem/describe.go deleted file mode 100644 index 038ebed0ee..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/describe.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filesystem - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var describeTemplate = `NAME PATH WT COMPRESSION MMAPV1 COMPRESSION -{{.ID}} {{.StorePath}} {{.WTCompressionSetting}} {{.MMAPV1CompressionSetting}} -` - -type DescribeOpts struct { - cli.OutputOpts - store store.FileSystemsDescriber - ID string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.DescribeFileSystem(opts.ID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup fileSystem(s) describe . -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Short: "Get a file system configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Configuration identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.ID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/describe_test.go b/internal/cli/opsmanager/admin/backup/filesystem/describe_test.go deleted file mode 100644 index 5c1f82bbdf..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package filesystem - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockFileSystemsDescriber(ctrl) - - expected := &opsmngr.FileSystemStoreConfiguration{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT().DescribeFileSystem(opts.ID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/file_system.go b/internal/cli/opsmanager/admin/backup/filesystem/file_system.go deleted file mode 100644 index 21b6a5d6ed..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/file_system.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filesystem - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "fileSystems" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage file system configurations.", - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - DeleteBuilder(), - CreateBuilder(), - UpdateBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/file_system_test.go b/internal/cli/opsmanager/admin/backup/filesystem/file_system_test.go deleted file mode 100644 index 14631bac4c..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/file_system_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package filesystem - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/list.go b/internal/cli/opsmanager/admin/backup/filesystem/list.go deleted file mode 100644 index b5ff58c2cb..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/list.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filesystem - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var listTemplate = `NAME PATH WT COMPRESSION MMAPV1 COMPRESSION{{range valueOrEmptySlice .Results}} -{{.ID}} {{.StorePath}} {{.WTCompressionSetting}} {{.MMAPV1CompressionSetting}}{{end}} -` - -type ListOpts struct { - cli.OutputOpts - cli.ListOpts - store store.FileSystemsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.ListFileSystems(opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup fileSystem(s) lists. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Short: "List file system configurations.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/list_test.go b/internal/cli/opsmanager/admin/backup/filesystem/list_test.go deleted file mode 100644 index 0401bb3a67..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package filesystem - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockFileSystemsLister(ctrl) - - expected := &opsmngr.FileSystemStoreConfigurations{} - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ListFileSystems(opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/update.go b/internal/cli/opsmanager/admin/backup/filesystem/update.go deleted file mode 100644 index 79618d80d1..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/update.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package filesystem - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -var updateTemplate = "File System configuration '{{.ID}}' updated.\n" - -type UpdateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.FileSystemsUpdater - mmapv1CompressionSetting string - storePath string - wtCompressionSetting string -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateFileSystems(opts.newFileSystemConfiguration()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *UpdateOpts) newFileSystemConfiguration() *opsmngr.FileSystemStoreConfiguration { - return &opsmngr.FileSystemStoreConfiguration{ - BackupStore: *opts.NewBackupStore(), - MMAPV1CompressionSetting: opts.mmapv1CompressionSetting, - StorePath: opts.storePath, - WTCompressionSetting: opts.wtCompressionSetting, - } -} - -// mongocli ops-manager admin backup fileSystem(s) update [--assignment][--encryptedCredentials] -// [--label label][--loadFactor loadFactor][--id ID][--storePath storePath][--mmapv1CompressionSetting mmapv1CompressionSetting] -// [--wtCompressionSetting wtCompressionSetting]. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update ", - Short: "Update a file system configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Configuration identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.ID = args[0] - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.FileSystemAssignment) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label+usage.UpdateWarning) - cmd.Flags().Int64Var(&opts.LoadFactor, flag.LoadFactor, 0, usage.LoadFactor) - cmd.Flags().StringVar(&opts.mmapv1CompressionSetting, flag.MMAPV1CompressionSetting, "", usage.MMAPV1CompressionSetting) - cmd.Flags().StringVar(&opts.wtCompressionSetting, flag.WTCompressionSetting, "", usage.WTCompressionSetting) - cmd.Flags().StringVar(&opts.storePath, flag.StorePath, "", usage.StorePath) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.StorePath) - _ = cmd.MarkFlagRequired(flag.MMAPV1CompressionSetting) - _ = cmd.MarkFlagRequired(flag.WTCompressionSetting) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/filesystem/update_test.go b/internal/cli/opsmanager/admin/backup/filesystem/update_test.go deleted file mode 100644 index a3aecec55b..0000000000 --- a/internal/cli/opsmanager/admin/backup/filesystem/update_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package filesystem - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockFileSystemsUpdater(ctrl) - - expected := &opsmngr.FileSystemStoreConfiguration{} - - opts := &UpdateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateFileSystems(opts.newFileSystemConfiguration()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Output, flag.EncryptedCredentials, flag.LoadFactor, - flag.WTCompressionSetting, flag.StorePath, flag.Label, flag.MMAPV1CompressionSetting, flag.Assignment}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/create.go b/internal/cli/opsmanager/admin/backup/oplog/create.go deleted file mode 100644 index c5048e8800..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/create.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oplog - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var createTemplate = "Oplog configuration '{{.ID}}' created.\n" - -type CreateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.OplogsCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateOplog(opts.NewBackupStore()) - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli ops-manager admin backup oplog(s) create [--assignment][--name name] -// [--label label][--loadFactor loadFactor][--uri uri][--ssl][--writeConcern writeConcern] -// [--encryptedCredentials encryptedCredentials]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "create", - Short: "Create a backup oplog configuration.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ID, flag.Name, "", usage.OplogName) - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label) - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.OplogAssignment) - cmd.Flags().Int64Var(&opts.MaxCapacityGB, flag.MaxCapacityGB, 0, usage.MaxCapacityGB) - cmd.Flags().StringVar(&opts.URI, flag.URI, "", usage.BlockstoreURI) - cmd.Flags().StringVar(&opts.WriteConcern, flag.WriteConcern, "", usage.WriteConcern) - cmd.Flags().BoolVar(&opts.SSL, flag.SSL, false, usage.OplogSSL) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Name) - _ = cmd.MarkFlagRequired(flag.URI) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/create_test.go b/internal/cli/opsmanager/admin/backup/oplog/create_test.go deleted file mode 100644 index 306f205706..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/create_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package oplog - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOplogsCreator(ctrl) - - expected := &opsmngr.BackupStore{} - - createOpts := &CreateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().CreateOplog(createOpts.NewBackupStore()). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Output, flag.Name, flag.EncryptedCredentials, flag.MaxCapacityGB, - flag.Assignment, flag.Label, flag.URI, flag.WriteConcern, - flag.EncryptedCredentials, flag.SSL, - }, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/delete.go b/internal/cli/opsmanager/admin/backup/oplog/delete.go deleted file mode 100644 index 66f56cd573..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/delete.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oplog - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.OplogsDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteOplog) -} - -// // mongocli ops-manager admin backup oplog(s) delete [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Oplog configuration '%s' deleted\n", "Oplog configuration not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Delete a backup oplog configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "nameDesc": "Oplog name.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/delete_test.go b/internal/cli/opsmanager/admin/backup/oplog/delete_test.go deleted file mode 100644 index b3dac05985..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/delete_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package oplog - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOplogsDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteOplog(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - opts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/describe.go b/internal/cli/opsmanager/admin/backup/oplog/describe.go deleted file mode 100644 index 6f707256cf..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/describe.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oplog - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var describeTemplate = `NAME URI SSL LOAD FACTOR MAX CAPACITY GB -{{.ID}} {{.URI}} {{.SSL}} {{.LoadFactor}} {{.MaxCapacityGB}} -` - -type DescribeOpts struct { - cli.OutputOpts - store store.OplogsDescriber - oplogID string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GetOplog(opts.oplogID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup oplog(s) describe . -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Short: "Get a backup oplog configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "nameDesc": "Oplog name.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.oplogID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/describe_test.go b/internal/cli/opsmanager/admin/backup/oplog/describe_test.go deleted file mode 100644 index 0cc2f16a9c..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package oplog - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOplogsDescriber(ctrl) - - expected := &opsmngr.BackupStore{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT().GetOplog(opts.oplogID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/list.go b/internal/cli/opsmanager/admin/backup/oplog/list.go deleted file mode 100644 index e80ec1607c..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/list.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oplog - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var listTemplate = `NAME URI SSL LOAD FACTOR MAX CAPACITY GB{{range valueOrEmptySlice .Results}} -{{.ID}} {{.URI}} {{.SSL}} {{.LoadFactor}} {{.MaxCapacityGB}}{{end}} -` - -type ListOpts struct { - cli.OutputOpts - cli.ListOpts - store store.OplogsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.ListOplogs(opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup oplog(s) lists. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Short: "List backup oplog configurations.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/list_test.go b/internal/cli/opsmanager/admin/backup/oplog/list_test.go deleted file mode 100644 index 1323e4666c..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package oplog - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOplogsLister(ctrl) - - expected := &opsmngr.BackupStores{} - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ListOplogs(opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/oplog.go b/internal/cli/opsmanager/admin/backup/oplog/oplog.go deleted file mode 100644 index 75002bd3cb..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/oplog.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oplog - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "oplog" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup oplog configurations.", - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - CreateBuilder(), - UpdateBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/oplog_test.go b/internal/cli/opsmanager/admin/backup/oplog/oplog_test.go deleted file mode 100644 index 1b39cf123e..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/oplog_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package oplog - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/update.go b/internal/cli/opsmanager/admin/backup/oplog/update.go deleted file mode 100644 index da16b87b4f..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/update.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oplog - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var updateTemplate = "Oplog configuration '{{.ID}}' updated.\n" - -type UpdateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.OplogsUpdater - ID string -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateOplog(opts.ID, opts.NewBackupStore()) - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli ops-manager admin backup oplog(s) update [--assignment] -// [--label label][--loadFactor loadFactor][--uri uri][--ssl][--writeConcern writeConcern] -// [--encryptedCredentials encryptedCredentials] - -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update ", - Short: "Update a backup oplog configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Oplog identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.ID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label+usage.UpdateWarning) - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.OplogAssignment) - cmd.Flags().Int64Var(&opts.MaxCapacityGB, flag.MaxCapacityGB, 0, usage.MaxCapacityGB) - cmd.Flags().StringVar(&opts.URI, flag.URI, "", usage.BlockstoreURI) - cmd.Flags().StringVar(&opts.WriteConcern, flag.WriteConcern, "", usage.WriteConcern) - cmd.Flags().BoolVar(&opts.SSL, flag.SSL, false, usage.OplogSSL) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Name) - _ = cmd.MarkFlagRequired(flag.URI) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/oplog/update_test.go b/internal/cli/opsmanager/admin/backup/oplog/update_test.go deleted file mode 100644 index 594cf069c0..0000000000 --- a/internal/cli/opsmanager/admin/backup/oplog/update_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package oplog - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOplogsUpdater(ctrl) - - expected := &opsmngr.BackupStore{} - - opts := &UpdateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateOplog(opts.ID, opts.NewBackupStore()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Output, flag.EncryptedCredentials, flag.MaxCapacityGB, - flag.Assignment, flag.Label, flag.URI, flag.WriteConcern, - flag.EncryptedCredentials, flag.SSL}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/s3/create.go b/internal/cli/opsmanager/admin/backup/s3/create.go deleted file mode 100644 index d26e4a6471..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/create.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package s3 - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -var createTemplate = "S3 blockstore configuration '{{.ID}}' created.\n" - -type CreateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.S3BlockstoresCreator - awsAccessKey string - awsSecretKey string - s3AuthMethod string - s3BucketEndpoint string - s3BucketName string - s3MaxConnections int64 - disableProxyS3 bool - acceptedTos bool - sseEnabled bool - pathStyleAccessEnabled bool -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateS3Blockstores(opts.newS3Blockstore()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *CreateOpts) newS3Blockstore() *opsmngr.S3Blockstore { - return &opsmngr.S3Blockstore{ - BackupStore: *opts.NewBackupStore(), - AWSAccessKey: opts.awsAccessKey, - AWSSecretKey: opts.awsSecretKey, - S3AuthMethod: opts.s3AuthMethod, - S3BucketEndpoint: opts.s3BucketEndpoint, - S3BucketName: opts.s3BucketName, - S3MaxConnections: opts.s3MaxConnections, - AcceptedTos: &opts.acceptedTos, - SSEEnabled: &opts.sseEnabled, - DisableProxyS3: &opts.disableProxyS3, - PathStyleAccessEnabled: &opts.pathStyleAccessEnabled, - } -} - -// mongocli ops-manager admin backup blockstore(s) create [--assignment][--encryptedCredentials][--name name] -// [--label label][--loadFactor loadFactor][--uri uri][--ssl][--writeConcern writeConcern] [--awsAccessKey awsAccessKey] -// [--awsSecretKey awsSecretKey] [--s3AuthMethod s3AuthMethod] [--s3BucketEndpoint s3BucketEndpoint] [--s3BucketName s3BucketName] -// [--s3MaxConnections s3MaxConnections] [--disableProxyS3 disableProxyS3] [--acceptedTos acceptedTos] [--sseEnabled sseEnabled] -// [--pathStyleAccessEnabled pathStyleAccessEnabled] - -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "create", - Short: "Create a backup S3 blockstore configuration.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ID, flag.Name, "", usage.BlockstoreName) - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label) - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.BlockstoreAssignment) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - cmd.Flags().Int64Var(&opts.LoadFactor, flag.LoadFactor, 0, usage.LoadFactor) - cmd.Flags().StringVar(&opts.URI, flag.URI, "", usage.BlockstoreURI) - cmd.Flags().StringVar(&opts.WriteConcern, flag.WriteConcern, "", usage.WriteConcern) - cmd.Flags().StringVar(&opts.awsAccessKey, flag.AWSAccessKey, "", usage.AWSAccessKey) - cmd.Flags().StringVar(&opts.awsSecretKey, flag.AWSSecretKey, "", usage.AWSSecretKey) - cmd.Flags().StringVar(&opts.s3AuthMethod, flag.S3AuthMethod, "", usage.S3AuthMethod) - cmd.Flags().StringVar(&opts.s3BucketEndpoint, flag.S3BucketEndpoint, "", usage.S3BucketEndpoint) - cmd.Flags().StringVar(&opts.s3BucketName, flag.S3BucketName, "", usage.S3BucketName) - cmd.Flags().Int64Var(&opts.s3MaxConnections, flag.S3MaxConnections, 0, usage.S3MaxConnections) - cmd.Flags().BoolVar(&opts.disableProxyS3, flag.DisableProxyS3, false, usage.DisableProxyS3) - cmd.Flags().BoolVar(&opts.acceptedTos, flag.AcceptedTos, false, usage.AcceptedTos) - cmd.Flags().BoolVar(&opts.sseEnabled, flag.SSEEnabled, false, usage.SSEEnabled) - cmd.Flags().BoolVar(&opts.pathStyleAccessEnabled, flag.PathStyleAccessEnabled, false, usage.PathStyleAccessEnabled) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Name) - _ = cmd.MarkFlagRequired(flag.URI) - _ = cmd.MarkFlagRequired(flag.AcceptedTos) - _ = cmd.MarkFlagRequired(flag.S3BucketName) - _ = cmd.MarkFlagRequired(flag.S3BucketEndpoint) - _ = cmd.MarkFlagRequired(flag.S3AuthMethod) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/s3/create_test.go b/internal/cli/opsmanager/admin/backup/s3/create_test.go deleted file mode 100644 index 162fd57c6b..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/create_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package s3 - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockS3BlockstoresCreator(ctrl) - - expected := &opsmngr.S3Blockstore{} - - createOpts := &CreateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().CreateS3Blockstores(createOpts.newS3Blockstore()). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Output, flag.Name, flag.EncryptedCredentials, flag.LoadFactor, - flag.Assignment, flag.Label, flag.URI, flag.WriteConcern, - flag.AWSAccessKey, flag.AWSSecretKey, flag.S3BucketName, flag.S3BucketEndpoint, - flag.SSEEnabled, flag.DisableProxyS3, flag.PathStyleAccessEnabled, flag.AcceptedTos, - }, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/s3/delete.go b/internal/cli/opsmanager/admin/backup/s3/delete.go deleted file mode 100644 index 28e5807d8b..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/delete.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package s3 - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.S3BlockstoresDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteS3Blockstore) -} - -// mongocli ops-manager admin backup s3 delete [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("S3 blockstore configuration '%s' deleted\n", "S3 blockstore configuration not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Delete a backup s3 blockstore configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Blockstore identifier.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/s3/delete_test.go b/internal/cli/opsmanager/admin/backup/s3/delete_test.go deleted file mode 100644 index 9a23d3a53d..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/delete_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package s3 - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockS3BlockstoresDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteS3Blockstore(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - opts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/s3/describe.go b/internal/cli/opsmanager/admin/backup/s3/describe.go deleted file mode 100644 index 39152daadd..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/describe.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package s3 - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var describeTemplate = `NAME URI SSL LOAD FACTOR AUTH METHOD -{{.ID}} {{.URI}} {{.SSL}} {{.LoadFactor}} {{.S3AuthMethod}} -` - -type DescribeOpts struct { - cli.OutputOpts - store store.S3BlockstoresDescriber - blockstoreID string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GetS3Blockstore(opts.blockstoreID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup s3 describe . -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Short: "Get a backup s3 blockstore configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Configuration identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.blockstoreID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/s3/describe_test.go b/internal/cli/opsmanager/admin/backup/s3/describe_test.go deleted file mode 100644 index e0a8e2e524..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package s3 - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockS3BlockstoresDescriber(ctrl) - - expected := &opsmngr.S3Blockstore{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT().GetS3Blockstore(opts.blockstoreID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/s3/list.go b/internal/cli/opsmanager/admin/backup/s3/list.go deleted file mode 100644 index 6c3e770978..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/list.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package s3 - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var listTemplate = `NAME URI SSL LOAD FACTOR AUTH METHOD{{range valueOrEmptySlice .Results}} -{{.ID}} {{.URI}} {{.SSL}} {{.LoadFactor}} {{.S3AuthMethod}}{{end}} -` - -type ListOpts struct { - cli.OutputOpts - cli.ListOpts - store store.S3BlockstoresLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.ListS3Blockstores(opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup s3 lists. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Short: "List backup s3 blockstore configurations.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/s3/list_test.go b/internal/cli/opsmanager/admin/backup/s3/list_test.go deleted file mode 100644 index 7a3c2f9624..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package s3 - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockS3BlockstoresLister(ctrl) - - expected := &opsmngr.S3Blockstores{} - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ListS3Blockstores(opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/s3/s3.go b/internal/cli/opsmanager/admin/backup/s3/s3.go deleted file mode 100644 index 64f2a2a7f8..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/s3.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package s3 - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "s3" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup s3 blockstore configurations.", - } - - cmd.AddCommand( - ListBuilder(), - DeleteBuilder(), - CreateBuilder(), - UpdateBuilder(), - DescribeBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/s3/s3_test.go b/internal/cli/opsmanager/admin/backup/s3/s3_test.go deleted file mode 100644 index 9a4fc57e0e..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/s3_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package s3 - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/s3/update.go b/internal/cli/opsmanager/admin/backup/s3/update.go deleted file mode 100644 index 62e8bba261..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/update.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package s3 - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -var updateTemplate = "S3 blockstore configuration '{{.ID}}' updated.\n" - -type UpdateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.S3BlockstoresUpdater - awsAccessKey string - awsSecretKey string - s3AuthMethod string - s3BucketEndpoint string - s3BucketName string - s3MaxConnections int64 - disableProxyS3 bool - acceptedTos bool - sseEnabled bool - pathStyleAccessEnabled bool -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateS3Blockstores(opts.ID, opts.newS3Blockstore()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *UpdateOpts) newS3Blockstore() *opsmngr.S3Blockstore { - return &opsmngr.S3Blockstore{ - BackupStore: *opts.NewBackupStore(), - AWSAccessKey: opts.awsAccessKey, - AWSSecretKey: opts.awsSecretKey, - S3AuthMethod: opts.s3AuthMethod, - S3BucketEndpoint: opts.s3BucketEndpoint, - S3BucketName: opts.s3BucketName, - S3MaxConnections: opts.s3MaxConnections, - AcceptedTos: &opts.acceptedTos, - SSEEnabled: &opts.sseEnabled, - DisableProxyS3: &opts.disableProxyS3, - PathStyleAccessEnabled: &opts.pathStyleAccessEnabled, - } -} - -// mongocli ops-manager admin backup blockstore(s) update name [--assignment][--encryptedCredentials] -// [--label label][--loadFactor loadFactor][--uri uri][--ssl][--writeConcern writeConcern] [--awsAccessKey awsAccessKey] -// [--awsSecretKey awsSecretKey] [--s3AuthMethod s3AuthMethod] [--s3BucketEndpoint s3BucketEndpoint] [--s3BucketName s3BucketName] -// [--s3MaxConnections s3MaxConnections] [--disableProxyS3 disableProxyS3] [--acceptedTos acceptedTos] [--sseEnabled sseEnabled] -// [--pathStyleAccessEnabled pathStyleAccessEnabled] - -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update ", - Args: require.ExactArgs(1), - Short: "Update a backup S3 blockstore configuration.", - Annotations: map[string]string{ - "IDDesc": "Blockstore identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.ID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label+usage.UpdateWarning) - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.BlockstoreAssignment) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - cmd.Flags().Int64Var(&opts.LoadFactor, flag.LoadFactor, 0, usage.LoadFactor) - cmd.Flags().StringVar(&opts.URI, flag.URI, "", usage.BlockstoreURI) - cmd.Flags().StringVar(&opts.WriteConcern, flag.WriteConcern, "", usage.WriteConcern) - cmd.Flags().StringVar(&opts.awsAccessKey, flag.AWSAccessKey, "", usage.AWSAccessKey) - cmd.Flags().StringVar(&opts.awsSecretKey, flag.AWSSecretKey, "", usage.AWSSecretKey) - cmd.Flags().StringVar(&opts.s3AuthMethod, flag.S3AuthMethod, "", usage.S3AuthMethod) - cmd.Flags().StringVar(&opts.s3BucketEndpoint, flag.S3BucketEndpoint, "", usage.S3BucketEndpoint) - cmd.Flags().StringVar(&opts.s3BucketName, flag.S3BucketName, "", usage.S3BucketName) - cmd.Flags().Int64Var(&opts.s3MaxConnections, flag.S3MaxConnections, 0, usage.S3MaxConnections) - cmd.Flags().BoolVar(&opts.disableProxyS3, flag.DisableProxyS3, false, usage.DisableProxyS3) - cmd.Flags().BoolVar(&opts.acceptedTos, flag.AcceptedTos, false, usage.AcceptedTos) - cmd.Flags().BoolVar(&opts.sseEnabled, flag.SSEEnabled, false, usage.SSEEnabled) - cmd.Flags().BoolVar(&opts.pathStyleAccessEnabled, flag.PathStyleAccessEnabled, false, usage.PathStyleAccessEnabled) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.URI) - _ = cmd.MarkFlagRequired(flag.AcceptedTos) - _ = cmd.MarkFlagRequired(flag.S3BucketName) - _ = cmd.MarkFlagRequired(flag.S3BucketEndpoint) - _ = cmd.MarkFlagRequired(flag.S3AuthMethod) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/s3/update_test.go b/internal/cli/opsmanager/admin/backup/s3/update_test.go deleted file mode 100644 index 1deac580ac..0000000000 --- a/internal/cli/opsmanager/admin/backup/s3/update_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package s3 - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockS3BlockstoresUpdater(ctrl) - - expected := &opsmngr.S3Blockstore{} - - opts := &UpdateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateS3Blockstores(opts.ID, opts.newS3Blockstore()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Output, flag.EncryptedCredentials, flag.LoadFactor, - flag.Assignment, flag.Label, flag.URI, flag.WriteConcern, - flag.AWSAccessKey, flag.AWSSecretKey, flag.S3BucketName, flag.S3BucketEndpoint, - flag.SSEEnabled, flag.DisableProxyS3, flag.PathStyleAccessEnabled, flag.AcceptedTos, - }, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/sync/create.go b/internal/cli/opsmanager/admin/backup/sync/create.go deleted file mode 100644 index 6e233c4342..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/create.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sync - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var createTemplate = "Sync configuration '{{.ID}}' created.\n" - -type CreateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.SyncsCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateSync(opts.NewBackupStore()) - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli ops-manager admin backup sync create [--assignment][--encryptedCredentials][--name name] -// [--label label][--loadFactor loadFactor][--maxCapacityGB maxCapacityGB][--uri uri][--ssl][--writeConcern writeConcern]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - opts.Template = createTemplate - cmd := &cobra.Command{ - Use: "create", - Short: "Create a backup sync configuration.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.SyncAssignment) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - cmd.Flags().StringVar(&opts.ID, flag.Name, "", usage.SyncName) - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label) - cmd.Flags().Int64Var(&opts.LoadFactor, flag.LoadFactor, 0, usage.LoadFactor) - cmd.Flags().Int64Var(&opts.MaxCapacityGB, flag.MaxCapacityGB, 0, usage.MaxCapacityGB) - cmd.Flags().StringVar(&opts.URI, flag.URI, "", usage.BlockstoreURI) - cmd.Flags().BoolVar(&opts.SSL, flag.SSL, false, usage.BlockstoreSSL) - cmd.Flags().StringVar(&opts.WriteConcern, flag.WriteConcern, "", usage.WriteConcern) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Name) - _ = cmd.MarkFlagRequired(flag.URI) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/sync/create_test.go b/internal/cli/opsmanager/admin/backup/sync/create_test.go deleted file mode 100644 index 3d8a113b76..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/create_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package sync - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSyncsCreator(ctrl) - - expected := &opsmngr.BackupStore{} - - createOpts := &CreateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().CreateSync(createOpts.NewBackupStore()). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Output, flag.Name, flag.SSL, flag.EncryptedCredentials, flag.LoadFactor, - flag.MaxCapacityGB, flag.Assignment, flag.Label, flag.URI, flag.WriteConcern}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/sync/delete.go b/internal/cli/opsmanager/admin/backup/sync/delete.go deleted file mode 100644 index c3ecf78a8c..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/delete.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sync - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - store store.SyncsDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteSync) -} - -// mongocli ops-manager admin backup sync delete [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Sync configuration '%s' deleted\n", "Sync configuration not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Delete a backup sync configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Configuration identifier.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.initStore(cmd.Context())(); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/sync/delete_test.go b/internal/cli/opsmanager/admin/backup/sync/delete_test.go deleted file mode 100644 index dda00c89eb..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/delete_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package sync - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSyncsDeleter(ctrl) - - mockStore. - EXPECT(). - DeleteSync(gomock.Eq("5a0a1e7e0f2912c554080adc")). - Return(nil). - Times(1) - - opts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.Force}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/sync/describe.go b/internal/cli/opsmanager/admin/backup/sync/describe.go deleted file mode 100644 index 1dc647a0a7..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/describe.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sync - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var describeTemplate = `NAME URI SSL LOAD FACTOR -{{.ID}} {{.URI}} {{.SSL}} {{.LoadFactor}} -` - -type DescribeOpts struct { - cli.OutputOpts - store store.SyncsDescriber - syncID string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GetSync(opts.syncID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup sync describe . -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - opts.Template = describeTemplate - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Short: "Get a backup sync configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Configuration identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.syncID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/sync/describe_test.go b/internal/cli/opsmanager/admin/backup/sync/describe_test.go deleted file mode 100644 index ce196011ba..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package sync - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSyncsDescriber(ctrl) - - expected := &opsmngr.BackupStore{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT().GetSync(opts.syncID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/sync/list.go b/internal/cli/opsmanager/admin/backup/sync/list.go deleted file mode 100644 index 8d0d0582fe..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/list.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sync - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var listTemplate = `NAME URI SSL LOAD FACTOR{{range valueOrEmptySlice .Results}} -{{.ID}} {{.URI}} {{.SSL}} {{.LoadFactor}}{{end}} -` - -type ListOpts struct { - cli.OutputOpts - cli.ListOpts - store store.SyncsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.ListSyncs(opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager admin backup sync lists. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Short: "List backup sync configurations.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/sync/list_test.go b/internal/cli/opsmanager/admin/backup/sync/list_test.go deleted file mode 100644 index 3ebf11556e..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package sync - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSyncsLister(ctrl) - - expected := &opsmngr.BackupStores{} - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ListSyncs(opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/sync/sync.go b/internal/cli/opsmanager/admin/backup/sync/sync.go deleted file mode 100644 index cbac9f15b4..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/sync.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sync - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "sync" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup sync configurations.", - } - - cmd.AddCommand( - ListBuilder(), - DeleteBuilder(), - CreateBuilder(), - UpdateBuilder(), - DescribeBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/sync/sync_test.go b/internal/cli/opsmanager/admin/backup/sync/sync_test.go deleted file mode 100644 index 63a2a8e99e..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/sync_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package sync - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/admin/backup/sync/update.go b/internal/cli/opsmanager/admin/backup/sync/update.go deleted file mode 100644 index 5ab3603a3d..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/update.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sync - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var updateTemplate = "Sync configuration '{{.ID}}' updated.\n" - -type UpdateOpts struct { - cli.OutputOpts - backup.AdminOpts - store store.SyncsUpdater -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateSync(opts.ID, opts.NewBackupStore()) - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli ops-manager admin backup sync update [--assignment][--encryptedCredentials][--name name] -// [--label label][--loadFactor loadFactor][--maxCapacityGB maxCapacityGB][--uri uri][--ssl][--writeConcern writeConcern] - -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update ", - Args: require.ExactArgs(1), - Short: "Update a backup sync configuration.", - Annotations: map[string]string{ - "IDDesc": "Configuration identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.ID = args[0] - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Assignment, flag.Assignment, false, usage.SyncAssignment) - cmd.Flags().BoolVar(&opts.EncryptedCredentials, flag.EncryptedCredentials, false, usage.EncryptedCredentials) - - cmd.Flags().StringSliceVar(&opts.Label, flag.Label, []string{}, usage.Label+usage.UpdateWarning) - cmd.Flags().Int64Var(&opts.LoadFactor, flag.LoadFactor, 0, usage.LoadFactor) - cmd.Flags().Int64Var(&opts.MaxCapacityGB, flag.MaxCapacityGB, 0, usage.MaxCapacityGB) - cmd.Flags().StringVar(&opts.URI, flag.URI, "", usage.BlockstoreURI) - cmd.Flags().BoolVar(&opts.SSL, flag.SSL, false, usage.BlockstoreSSL) - cmd.Flags().StringVar(&opts.WriteConcern, flag.WriteConcern, "", usage.WriteConcern) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.URI) - - return cmd -} diff --git a/internal/cli/opsmanager/admin/backup/sync/update_test.go b/internal/cli/opsmanager/admin/backup/sync/update_test.go deleted file mode 100644 index 4a92f84055..0000000000 --- a/internal/cli/opsmanager/admin/backup/sync/update_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package sync - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSyncsUpdater(ctrl) - - expected := &opsmngr.BackupStore{} - - opts := &UpdateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateSync(opts.ID, opts.NewBackupStore()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.Output, flag.SSL, flag.EncryptedCredentials, flag.LoadFactor, - flag.MaxCapacityGB, flag.Assignment, flag.Label, flag.URI, flag.WriteConcern}, - ) -} diff --git a/internal/cli/opsmanager/agents/agent_test.go b/internal/cli/opsmanager/agents/agent_test.go deleted file mode 100644 index 176d6f0a54..0000000000 --- a/internal/cli/opsmanager/agents/agent_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package agents - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 4, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/agents/agents.go b/internal/cli/opsmanager/agents/agents.go deleted file mode 100644 index e0c3bbae18..0000000000 --- a/internal/cli/opsmanager/agents/agents.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package agents - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/agents/apikeys" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/agents/versions" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "agents" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage MongoDB Agents.", - } - cmd.AddCommand( - ListBuilder(), - UpgradeBuilder(), - apikeys.Builder(), - versions.Builder(), - ) - return cmd -} diff --git a/internal/cli/opsmanager/agents/apikeys/apikeys.go b/internal/cli/opsmanager/agents/apikeys/apikeys.go deleted file mode 100644 index 8ea21b45b5..0000000000 --- a/internal/cli/opsmanager/agents/apikeys/apikeys.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "apiKeys" - cmd := &cobra.Command{ - Use: use, - Short: "Agent API Keys operations.", - Aliases: cli.GenerateAliases(use), - } - cmd.AddCommand( - ListBuilder(), - CreateBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/agents/apikeys/create.go b/internal/cli/opsmanager/agents/apikeys/create.go deleted file mode 100644 index 2f5a9fbde8..0000000000 --- a/internal/cli/opsmanager/agents/apikeys/create.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -const createTemplate = "API Key '{{.Key}}' created.\n" - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - desc string - store store.AgentAPIKeyCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) newAgentAPIKeysRequest() *opsmngr.AgentAPIKeysRequest { - return &opsmngr.AgentAPIKeysRequest{ - Desc: opts.desc, - } -} - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateAgentAPIKey(opts.ConfigProjectID(), opts.newAgentAPIKeysRequest()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli iam agents apiKey(s)|apikeys create [--desc description][--projectId projectId]. -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - cmd := &cobra.Command{ - Use: "create", - Short: "Create an Agent API Key for your project.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().StringVar(&opts.desc, flag.Description, "", usage.APIKeyDescription) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Description) - - return cmd -} diff --git a/internal/cli/opsmanager/agents/apikeys/create_test.go b/internal/cli/opsmanager/agents/apikeys/create_test.go deleted file mode 100644 index 42daf14ede..0000000000 --- a/internal/cli/opsmanager/agents/apikeys/create_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/stretchr/testify/require" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAgentAPIKeyCreator(ctrl) - - createOpts := &CreateOpts{ - store: mockStore, - } - - expected := &opsmngr.AgentAPIKey{} - - mockStore. - EXPECT(). - CreateAgentAPIKey(createOpts.OrgID, createOpts.newAgentAPIKeysRequest()). - Return(expected, nil). - Times(1) - - require.NoError(t, createOpts.Run()) -} diff --git a/internal/cli/opsmanager/agents/apikeys/delete.go b/internal/cli/opsmanager/agents/apikeys/delete.go deleted file mode 100644 index 43981def01..0000000000 --- a/internal/cli/opsmanager/agents/apikeys/delete.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - *cli.DeleteOpts - cli.GlobalOpts - store store.AgentAPIKeyDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteAgentAPIKey, opts.ConfigProjectID()) -} - -// mongocli iam ops-manager agents apiKey(s)|apikey(s) delete [--projectId projectId]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("API Key '%s' deleted\n", "API Key not deleted"), - } - - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Delete an Agent API Key for your project.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "ID of the API key.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/agents/apikeys/delete_test.go b/internal/cli/opsmanager/agents/apikeys/delete_test.go deleted file mode 100644 index fce0c73e40..0000000000 --- a/internal/cli/opsmanager/agents/apikeys/delete_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/stretchr/testify/require" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAgentAPIKeyDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Entry: "5a0a1e7e0f2912c554080adc", - Confirm: true, - }, - } - mockStore. - EXPECT(). - DeleteAgentAPIKey(deleteOpts.OrgID, "5a0a1e7e0f2912c554080adc"). - Return(nil). - Times(1) - - require.NoError(t, deleteOpts.Run()) -} diff --git a/internal/cli/opsmanager/agents/apikeys/list.go b/internal/cli/opsmanager/agents/apikeys/list.go deleted file mode 100644 index b0bc6ba231..0000000000 --- a/internal/cli/opsmanager/agents/apikeys/list.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apikeys - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.AgentAPIKeyLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `ID KEY DESCRIPTION CREATED AT{{range valueOrEmptySlice .}} -{{.ID}} {{.Key}} {{.Desc}} {{.CreatedTime}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.AgentAPIKeys(opts.ConfigProjectID()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om agents apiKeys(s) list [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "List available MongoDB Agent API Keys for your project.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/agents/apikeys/list_test.go b/internal/cli/opsmanager/agents/apikeys/list_test.go deleted file mode 100644 index 924dbdd23a..0000000000 --- a/internal/cli/opsmanager/agents/apikeys/list_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package apikeys - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/stretchr/testify/require" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestAgentsList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAgentAPIKeyLister(ctrl) - - listOpts := ListOpts{ - store: mockStore, - } - listOpts.ProjectID = "1" - - expected := make([]*opsmngr.AgentAPIKey, 0) - - mockStore. - EXPECT(). - AgentAPIKeys(listOpts.ProjectID). - Return(expected, nil). - Times(1) - - config.SetService(config.OpsManagerService) - - require.NoError(t, listOpts.Run()) -} diff --git a/internal/cli/opsmanager/agents/list.go b/internal/cli/opsmanager/agents/list.go deleted file mode 100644 index 3c84407d3b..0000000000 --- a/internal/cli/opsmanager/agents/list.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package agents - -import ( - "context" - "fmt" - "strings" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - agentType string - store store.AgentLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `HOSTNAME TYPE STATE{{range valueOrEmptySlice .Results}} -{{.Hostname}} {{.TypeName}} {{.StateName}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.Agents(opts.ConfigProjectID(), opts.agentType, opts.NewListOptions()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om agent(s) list [--projectId projectId]. -func ListBuilder() *cobra.Command { - validArgs := []string{"AUTOMATION", "MONITORING", "BACKUP"} - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: fmt.Sprintf("list <%s>", strings.Join(validArgs, "|")), - Aliases: []string{"ls"}, - Args: require.ExactValidArgs(1), - ValidArgs: validArgs, - Short: "List available MongoDB Agents for your project.", - Annotations: map[string]string{ - "AUTOMATION|MONITORING|BACKUPDesc": "Agent type", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.agentType = strings.ToUpper(args[0]) - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/agents/list_test.go b/internal/cli/opsmanager/agents/list_test.go deleted file mode 100644 index 1a1c0f74e5..0000000000 --- a/internal/cli/opsmanager/agents/list_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package agents - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/stretchr/testify/require" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestAgentsList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAgentLister(ctrl) - - expected := &opsmngr.Agents{} - - listOpts := ListOpts{ - store: mockStore, - agentType: "MONITORING", - } - listOpts.ProjectID = "1" - - mockStore. - EXPECT(). - Agents(listOpts.ProjectID, listOpts.agentType, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - config.SetService(config.OpsManagerService) - - require.NoError(t, listOpts.Run()) -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/agents/upgrade.go b/internal/cli/opsmanager/agents/upgrade.go deleted file mode 100644 index 0711b8dd4b..0000000000 --- a/internal/cli/opsmanager/agents/upgrade.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package agents - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type UpgradeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.AgentUpgrader -} - -var upgradeTemplate = "Updating agent versions to the latest available.\n" - -func (opts *UpgradeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpgradeOpts) Run() error { - r, err := opts.store.UpgradeAgent(opts.ConfigProjectID()) - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli ops-manager agents upgrade [--projectId projectId]. -func UpgradeBuilder() *cobra.Command { - opts := &UpgradeOpts{} - cmd := &cobra.Command{ - Use: "upgrade", - Args: require.NoArgs, - Short: "Upgrade MongoDB Agents to the latest available version.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), upgradeTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/agents/upgrade_test.go b/internal/cli/opsmanager/agents/upgrade_test.go deleted file mode 100644 index 69e066bef8..0000000000 --- a/internal/cli/opsmanager/agents/upgrade_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package agents - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestAgentsUpgradeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAgentUpgrader(ctrl) - - expected := new(opsmngr.AutomationConfigAgent) - - opts := &UpgradeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - UpgradeAgent(opts.ProjectID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/agents/versions/list.go b/internal/cli/opsmanager/agents/versions/list.go deleted file mode 100644 index 8c8647e604..0000000000 --- a/internal/cli/opsmanager/agents/versions/list.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package versions - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.AgentProjectVersionsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `HOSTNAME ADDRESS VERSION DEPRECATED{{range valueOrEmptySlice .Entries}} -{{.Hostname}} {{.Address}} {{.Version}} {{.IsVersionDeprecated}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.AgentProjectVersions(opts.ConfigProjectID()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om agent(s) version(s) list [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "List MongoDB Agent versions in the provided project.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/agents/versions/list_test.go b/internal/cli/opsmanager/agents/versions/list_test.go deleted file mode 100644 index cd68430991..0000000000 --- a/internal/cli/opsmanager/agents/versions/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package versions - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAgentProjectVersionsLister(ctrl) - - expected := &opsmngr.AgentVersions{} - - listOpts := ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - AgentProjectVersions(listOpts.ProjectID). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/agents/versions/versions.go b/internal/cli/opsmanager/agents/versions/versions.go deleted file mode 100644 index 9510353842..0000000000 --- a/internal/cli/opsmanager/agents/versions/versions.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package versions - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "versions" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage MongoDB Agents versions.", - } - cmd.AddCommand(ListBuilder()) - return cmd -} diff --git a/internal/cli/opsmanager/agents/versions/versions_test.go b/internal/cli/opsmanager/agents/versions/versions_test.go deleted file mode 100644 index 89c5dd93e5..0000000000 --- a/internal/cli/opsmanager/agents/versions/versions_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package versions - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/automation/automation.go b/internal/cli/opsmanager/automation/automation.go deleted file mode 100644 index 1613e477ea..0000000000 --- a/internal/cli/opsmanager/automation/automation.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package automation - -import ( - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "automation", - Short: "Manage automation configuration for your project.", - } - - cmd.AddCommand( - StatusBuilder(), - DescribeBuilder(), - UpdateBuilder(), - WatchBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/automation/describe.go b/internal/cli/opsmanager/automation/describe.go deleted file mode 100644 index 884bf30ad6..0000000000 --- a/internal/cli/opsmanager/automation/describe.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package automation - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.AutomationGetter -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager automation describe [--projectId projectId]. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe", - Aliases: []string{"show", "get"}, - Short: "Get the current automation configuration for a project.", - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), "use json output"), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/automation/describe_test.go b/internal/cli/opsmanager/automation/describe_test.go deleted file mode 100644 index ee6e8e2cb4..0000000000 --- a/internal/cli/opsmanager/automation/describe_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package automation - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestAutomationShowOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationGetter(ctrl) - - expected := fixture.AutomationConfig() - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(opts.ProjectID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/automation/status.go b/internal/cli/opsmanager/automation/status.go deleted file mode 100644 index 502fc2b4bb..0000000000 --- a/internal/cli/opsmanager/automation/status.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package automation - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type StatusOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.AutomationStatusGetter -} - -func (opts *StatusOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *StatusOpts) Run() error { - r, err := opts.store.GetAutomationStatus(opts.ConfigProjectID()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager automation status [--projectId projectId]. -func StatusBuilder() *cobra.Command { - opts := &StatusOpts{} - cmd := &cobra.Command{ - Use: "status", - Short: "Show the current status of the automation config.", - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), ""), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/automation/status_test.go b/internal/cli/opsmanager/automation/status_test.go deleted file mode 100644 index 281e241d79..0000000000 --- a/internal/cli/opsmanager/automation/status_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package automation - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestAutomationStatus_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationStatusGetter(ctrl) - - expected := fixture.AutomationStatus() - - opts := &StatusOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationStatus(opts.ProjectID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/automation/update.go b/internal/cli/opsmanager/automation/update.go deleted file mode 100644 index ca9864ec25..0000000000 --- a/internal/cli/opsmanager/automation/update.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package automation - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/file" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type UpdateOpts struct { - cli.GlobalOpts - filename string - fs afero.Fs - store store.AutomationUpdater -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - newConfig := new(opsmngr.AutomationConfig) - err := file.Load(opts.fs, opts.filename, newConfig) - if err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), newConfig); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli om automation update --projectId projectId --file myfile.json. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{ - fs: afero.NewOsFs(), - } - cmd := &cobra.Command{ - Use: "update", - Short: "Update the current automation configuration for a project.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.filename, flag.File, flag.FileShort, "", "Filename to use") - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.File) - _ = cmd.MarkFlagFilename(flag.File) - - return cmd -} diff --git a/internal/cli/opsmanager/automation/update_test.go b/internal/cli/opsmanager/automation/update_test.go deleted file mode 100644 index cfab9e089e..0000000000 --- a/internal/cli/opsmanager/automation/update_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package automation - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/spf13/afero" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestAutomationUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationUpdater(ctrl) - - expected := &opsmngr.AutomationConfig{ - Version: 1, - } - appFS := afero.NewMemMapFs() - // create test file - fileJSON := ` -{ -"version": 1 -}` - fileName := "om_automation_test.json" - _ = afero.WriteFile(appFS, fileName, []byte(fileJSON), 0600) - createOpts := &UpdateOpts{ - store: mockStore, - fs: appFS, - filename: fileName, - } - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/automation/watch.go b/internal/cli/opsmanager/automation/watch.go deleted file mode 100644 index 3159818b4c..0000000000 --- a/internal/cli/opsmanager/automation/watch.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package automation - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type WatchOpts struct { - cli.GlobalOpts - cli.WatchOpts - store store.AutomationStatusGetter -} - -func (opts *WatchOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *WatchOpts) watcher() (any, bool, error) { - result, err := opts.store.GetAutomationStatus(opts.ConfigProjectID()) - if err != nil { - return nil, false, err - } - - for _, p := range result.Processes { - if p.LastGoalVersionAchieved != result.GoalVersion { - return nil, false, nil - } - } - return nil, true, nil -} - -func (opts *WatchOpts) Run() error { - if _, err := opts.Watch(opts.watcher); err != nil { - return err - } - - return opts.Print(nil) -} - -// mongocli ops-manager automation watch [--projectId projectId]. -func WatchBuilder() *cobra.Command { - opts := &WatchOpts{} - cmd := &cobra.Command{ - Use: "watch", - Short: "Watch for automation changes to be completed.", - Long: `This command checks the automation "lastGoalVersionAchieved" periodically until it matches "goalVersion". -Once the expected status is reached, the command prints "Changes deployed successfully." -If you run the command in the terminal, it blocks the terminal session until the changes are completed. -You can interrupt the command's polling at any time with CTRL-C.`, - Example: ` mongocli ops-manager automation watch`, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), "\nChanges deployed successfully\n"), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/automation/watch_test.go b/internal/cli/opsmanager/automation/watch_test.go deleted file mode 100644 index b815d98509..0000000000 --- a/internal/cli/opsmanager/automation/watch_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package automation - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestAutomationWatch_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationStatusGetter(ctrl) - - expected := fixture.AutomationStatus() - - opts := &WatchOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationStatus(opts.ProjectID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/backup/backup.go b/internal/cli/opsmanager/backup/backup.go deleted file mode 100644 index 16a043318b..0000000000 --- a/internal/cli/opsmanager/backup/backup.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/backup/config" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/backup/snapshots" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "backups" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage continuous backups for your project.", - } - - cmd.AddCommand( - snapshots.Builder(), - RestoresBuilder(), - CheckpointsBuilder(), - EnableBuilder(), - DisableBuilder(), - config.Builder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/backup_test.go b/internal/cli/opsmanager/backup/backup_test.go deleted file mode 100644 index c4fe43422e..0000000000 --- a/internal/cli/opsmanager/backup/backup_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package backup - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 6, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/backup/checkpoints.go b/internal/cli/opsmanager/backup/checkpoints.go deleted file mode 100644 index 693bede6f9..0000000000 --- a/internal/cli/opsmanager/backup/checkpoints.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func CheckpointsBuilder() *cobra.Command { - const use = "checkpoints" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup checkpoints for your project.", - } - - cmd.AddCommand(AtlasBackupsCheckpointsListBuilder()) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/checkpoints_list.go b/internal/cli/opsmanager/backup/checkpoints_list.go deleted file mode 100644 index 1f3384a06d..0000000000 --- a/internal/cli/opsmanager/backup/checkpoints_list.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/mongodb/mongodb-atlas-cli/internal/validate" - "github.com/spf13/cobra" -) - -const checkpointsTemplate = `ID TIMESTAMP{{range valueOrEmptySlice .Results}} -{{.ID}} {{.Timestamp}}{{end}} -` - -type CheckpointsListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - clusterID string - store store.CheckpointsLister -} - -func (opts *CheckpointsListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CheckpointsListOpts) Run() error { - listOpts := opts.NewListOptions() - - r, err := opts.store.Checkpoints(opts.ConfigProjectID(), opts.clusterID, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas backup(s) checkpoint(s) list [--projectId projectId]. -func AtlasBackupsCheckpointsListBuilder() *cobra.Command { - opts := new(CheckpointsListOpts) - cmd := &cobra.Command{ - Use: "list ", - Aliases: []string{"ls"}, - Short: "List continuous backup checkpoints for your project.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterIdDesc": "ID of the cluster.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := validate.ObjectID(args[0]); err != nil { - return err - } - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), checkpointsTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.clusterID = args[0] - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/checkpoints_list_test.go b/internal/cli/opsmanager/backup/checkpoints_list_test.go deleted file mode 100644 index 0949cc70e0..0000000000 --- a/internal/cli/opsmanager/backup/checkpoints_list_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package backup - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCheckpointsList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockCheckpointsLister(ctrl) - - expected := &opsmngr.Checkpoints{} - clusterID := "5ec2ac941271767f21cbaefd" - - listOpts := &CheckpointsListOpts{ - store: mockStore, - clusterID: clusterID, - } - - mockStore. - EXPECT(). - Checkpoints(listOpts.ProjectID, clusterID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/backup/config/config.go b/internal/cli/opsmanager/backup/config/config.go deleted file mode 100644 index cb9ef4c1a6..0000000000 --- a/internal/cli/opsmanager/backup/config/config.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "config" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup configurations for your project.", - } - - cmd.AddCommand( - DescribeBuilder(), - ListBuilder(), - UpdateBuilder(), - ) - return cmd -} diff --git a/internal/cli/opsmanager/backup/config/config_test.go b/internal/cli/opsmanager/backup/config/config_test.go deleted file mode 100644 index 0acc72721b..0000000000 --- a/internal/cli/opsmanager/backup/config/config_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package config - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/backup/config/describe.go b/internal/cli/opsmanager/backup/config/describe.go deleted file mode 100644 index 4c1d0aac6f..0000000000 --- a/internal/cli/opsmanager/backup/config/describe.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var describeTemplate = `PROJECT ID CLUSTER ID STATUS STORAGE ENGINE -{{.GroupID}} {{.ClusterID}} {{.StatusName}} {{.StorageEngineName}} -` - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.BackupConfigGetter - clusterID string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GetBackupConfig(opts.ConfigProjectID(), opts.clusterID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager backup config describe [--projectId projectId]. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe ", - Aliases: []string{"get"}, - Short: "Get a backup configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterIdDesc": "ID of the cluster.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.clusterID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/config/describe_test.go b/internal/cli/opsmanager/backup/config/describe_test.go deleted file mode 100644 index c38fba1fe0..0000000000 --- a/internal/cli/opsmanager/backup/config/describe_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package config - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockBackupConfigGetter(ctrl) - - expected := &opsmngr.BackupConfig{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GetBackupConfig(opts.ProjectID, opts.clusterID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.ProjectID, flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/backup/config/list.go b/internal/cli/opsmanager/backup/config/list.go deleted file mode 100644 index 810ffdd311..0000000000 --- a/internal/cli/opsmanager/backup/config/list.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var listTemplate = `PROJECT ID CLUSTER ID STATUS STORAGE ENGINE{{range valueOrEmptySlice .Results}} -{{.GroupID}} {{.ClusterID}} {{.StatusName}} {{.StorageEngineName}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.BackupConfigLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.ListBackupConfigs(opts.ConfigProjectID(), opts.NewListOptions()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager backup config list [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Short: "List backup configurations for your project.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/config/list_test.go b/internal/cli/opsmanager/backup/config/list_test.go deleted file mode 100644 index 417b6ed9c5..0000000000 --- a/internal/cli/opsmanager/backup/config/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package config - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockBackupConfigLister(ctrl) - - expected := &opsmngr.BackupConfigs{} - - opts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ListBackupConfigs(opts.ProjectID, opts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/backup/config/update.go b/internal/cli/opsmanager/backup/config/update.go deleted file mode 100644 index e698a9f3fd..0000000000 --- a/internal/cli/opsmanager/backup/config/update.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -const updateTemplate = "Backup Configuration updated.\n" - -type UpdateOpts struct { - cli.OutputOpts - cli.GlobalOpts - store store.BackupConfigUpdater - clusterID string - status string - storageEngine string - authMechanism string - username string - password string - encryption bool - ssl bool - syncSource string - provisioned bool - excludedNamespace []string - includedNamespace []string -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateBackupConfig(opts.newBackupConfig()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *UpdateOpts) newBackupConfig() *opsmngr.BackupConfig { - backupConfig := &opsmngr.BackupConfig{ - GroupID: opts.ConfigProjectID(), - ClusterID: opts.clusterID, - StatusName: opts.status, - StorageEngineName: opts.storageEngine, - ExcludedNamespaces: opts.excludedNamespace, - IncludedNamespaces: opts.includedNamespace, - AuthMechanismName: opts.authMechanism, - Password: opts.password, - SyncSource: opts.syncSource, - Username: opts.username, - } - - if opts.ssl { - backupConfig.SSLEnabled = &opts.ssl - } - - if opts.encryption { - backupConfig.EncryptionEnabled = &opts.encryption - } - - if opts.provisioned { - backupConfig.Provisioned = &opts.provisioned - } - - return backupConfig -} - -// mongocli ops-manager backup config update clusterID --status status --storageEngine storageEngine --authMechanism authMechanism -// --username username --password password --provisioned provisioned --encryption encryption -// --ssl ssl --syncSource syncSource --excludedNamespace excludedNamespace --includedNamespace includedNamespace[--projectId projectId]. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update ", - Short: "Update a backup configuration.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterIdDesc": "ID of the cluster.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.clusterID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.status, flag.Status, "", usage.BackupStatus) - cmd.Flags().StringVar(&opts.storageEngine, flag.StorageEngine, "", usage.StorageEngine) - cmd.Flags().StringVar(&opts.authMechanism, flag.AuthMechanism, "", usage.AuthMechanism) - cmd.Flags().StringVar(&opts.username, flag.Username, "", usage.Username) - cmd.Flags().StringVar(&opts.password, flag.Password, "", usage.Password) - cmd.Flags().BoolVar(&opts.provisioned, flag.Provisioned, false, usage.Provisioned) - cmd.Flags().BoolVar(&opts.encryption, flag.Encryption, false, usage.Encryption) - cmd.Flags().BoolVar(&opts.ssl, flag.SSL, false, usage.SSL) - cmd.Flags().StringVar(&opts.syncSource, flag.SyncSource, "", usage.SyncSource) - cmd.Flags().StringSliceVar(&opts.excludedNamespace, flag.ExcludedNamespace, []string{}, usage.ExcludedNamespace+usage.UpdateWarning) - cmd.Flags().StringSliceVar(&opts.includedNamespace, flag.IncludedNamespace, []string{}, usage.IncludedNamespace+usage.UpdateWarning) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/config/update_test.go b/internal/cli/opsmanager/backup/config/update_test.go deleted file mode 100644 index e89a44b353..0000000000 --- a/internal/cli/opsmanager/backup/config/update_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package config - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockBackupConfigUpdater(ctrl) - - expected := &opsmngr.BackupConfig{} - - updateOpts := &UpdateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateBackupConfig(updateOpts.newBackupConfig()). - Return(expected, nil). - Times(1) - - if err := updateOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Output, flag.ProjectID, flag.Username, flag.Password, flag.Status, flag.SSL, flag.Encryption, flag.ExcludedNamespace, - flag.IncludedNamespace, flag.Provisioned, flag.AuthMechanism, flag.StorageEngine, flag.SyncSource}, - ) -} diff --git a/internal/cli/opsmanager/backup/disable.go b/internal/cli/opsmanager/backup/disable.go deleted file mode 100644 index 0aaa0bccc4..0000000000 --- a/internal/cli/opsmanager/backup/disable.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type DisableOpts struct { - cli.GlobalOpts - hostname string - store store.AutomationPatcher -} - -func (opts *DisableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DisableOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if err := atmcfg.DisableBackup(current, opts.hostname); err != nil { - return err - } - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli ops-manager backup disable [--projectId projectId]. -func DisableBuilder() *cobra.Command { - opts := &DisableOpts{} - cmd := &cobra.Command{ - Use: "disable ", - Short: "Disable backup for a given hostname", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "hostnameDesc": "Label hostname.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostname = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/disable_test.go b/internal/cli/opsmanager/backup/disable_test.go deleted file mode 100644 index 5389526d95..0000000000 --- a/internal/cli/opsmanager/backup/disable_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package backup - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestDisableBuilder(t *testing.T) { - test.CmdValidator( - t, - DisableBuilder(), - 0, - []string{flag.ProjectID}, - ) -} - -func TestDisableOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfigWithBackup() - - createOpts := &DisableOpts{ - hostname: "test", - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/backup/enable.go b/internal/cli/opsmanager/backup/enable.go deleted file mode 100644 index b082df1563..0000000000 --- a/internal/cli/opsmanager/backup/enable.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type EnableOpts struct { - cli.GlobalOpts - hostname string - store store.AutomationPatcher -} - -func (opts *EnableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *EnableOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - - if err := atmcfg.EnableBackup(current, opts.hostname); err != nil { - return err - } - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli ops-manager monitoring enable [--projectId projectId]. -func EnableBuilder() *cobra.Command { - opts := &EnableOpts{} - cmd := &cobra.Command{ - Use: "enable ", - Short: "Enable backup for a given hostname", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "hostnameDesc": "Label hostname.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostname = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/enable_test.go b/internal/cli/opsmanager/backup/enable_test.go deleted file mode 100644 index 47f23b4353..0000000000 --- a/internal/cli/opsmanager/backup/enable_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package backup - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestEnableBuilder(t *testing.T) { - test.CmdValidator( - t, - EnableBuilder(), - 0, - []string{flag.ProjectID}, - ) -} - -func TestEnableOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - createOpts := &EnableOpts{ - hostname: "test", - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/backup/restores.go b/internal/cli/opsmanager/backup/restores.go deleted file mode 100644 index 55e1342e89..0000000000 --- a/internal/cli/opsmanager/backup/restores.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func RestoresBuilder() *cobra.Command { - const use = "restores" - cmd := &cobra.Command{ - Use: use, - Short: "Manage restore jobs for your project.", - Aliases: cli.GenerateAliases(use), - } - - cmd.AddCommand( - RestoresListBuilder(), - RestoresStartBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/restores_list.go b/internal/cli/opsmanager/backup/restores_list.go deleted file mode 100644 index 864fe76443..0000000000 --- a/internal/cli/opsmanager/backup/restores_list.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/mongodb/mongodb-atlas-cli/internal/validate" - "github.com/spf13/cobra" -) - -const restoresTemplate = `ID TIMESTAMP STATUS{{range valueOrEmptySlice .Results}} -{{.ID}} {{.Timestamp.Date}} {{.StatusName}}{{end}} -` - -type RestoresListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - clusterID string - store store.ContinuousJobLister -} - -func (opts *RestoresListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *RestoresListOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.ContinuousRestoreJobs(opts.ConfigProjectID(), opts.clusterID, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas backup(s) restore(s) job(s) list [--page N] [--limit N]. -func RestoresListBuilder() *cobra.Command { - opts := new(RestoresListOpts) - cmd := &cobra.Command{ - Use: "list ", - Aliases: []string{"ls"}, - Short: "Lists restore jobs for a project and cluster.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterIdDesc": "ID of the cluster.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), restoresTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - if err := validate.ObjectID(args[0]); err != nil { - return err - } - opts.clusterID = args[0] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/restores_list_test.go b/internal/cli/opsmanager/backup/restores_list_test.go deleted file mode 100644 index 0305070940..0000000000 --- a/internal/cli/opsmanager/backup/restores_list_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package backup - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestRestoresListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockContinuousJobLister(ctrl) - - expected := &opsmngr.ContinuousJobs{} - clusterID := "5ec2ac941271767f21cbaeff" - - listOpts := &RestoresListOpts{ - store: mockStore, - clusterID: clusterID, - } - - mockStore. - EXPECT(). - ContinuousRestoreJobs(listOpts.ProjectID, clusterID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/backup/restores_start.go b/internal/cli/opsmanager/backup/restores_start.go deleted file mode 100644 index a2ae99c13e..0000000000 --- a/internal/cli/opsmanager/backup/restores_start.go +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package backup - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -const ( - automatedRestore = "AUTOMATED_RESTORE" - httpRestore = "HTTP" - onlyFor = "'%s' can only be used with %s" - createTemplate = `Created restore job(s):{{range valueOrEmptySlice .Results}} '{{.ID}}'{{end}}. -` -) - -type RestoresStartOpts struct { - cli.GlobalOpts - cli.OutputOpts - method string - clusterID string - targetProjectID string - targetClusterID string - checkpointID string - oplogTS string - oplogInc int64 - snapshotID string - expirationHours int64 - expires string - maxDownloads int64 - pointInTimeUTCMillis float64 - store store.ContinuousJobCreator -} - -func (opts *RestoresStartOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *RestoresStartOpts) Run() error { - request := opts.newContinuousJobRequest() - r, err := opts.store.CreateContinuousRestoreJob(opts.ConfigProjectID(), opts.clusterID, request) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *RestoresStartOpts) newContinuousJobRequest() *opsmngr.ContinuousJobRequest { - request := &opsmngr.ContinuousJobRequest{SnapshotID: opts.snapshotID} - request.Delivery.MethodName = opts.method - - if opts.isAutomatedRestore() { - request.Delivery.TargetGroupID = opts.targetProjectID - request.Delivery.TargetClusterID = opts.targetClusterID - - if opts.oplogTS != "" && opts.oplogInc != 0 { - request.OplogTS = opts.oplogTS - request.OplogInc = opts.oplogInc - } - if opts.pointInTimeUTCMillis != 0 { - request.PointInTimeUTCMillis = opts.pointInTimeUTCMillis - } - } - - if opts.isHTTP() { - if opts.expires != "" { - request.Delivery.Expires = opts.expires - } - if opts.maxDownloads > 0 { - request.Delivery.MaxDownloads = opts.maxDownloads - } - if opts.expirationHours > 0 { - request.Delivery.ExpirationHours = opts.expirationHours - } - } - return request -} - -func (opts *RestoresStartOpts) isAutomatedRestore() bool { - return opts.method == automatedRestore -} - -func (opts *RestoresStartOpts) isHTTP() bool { - return opts.method == httpRestore -} - -func (opts *RestoresStartOpts) validateParams() error { - if !opts.isAutomatedRestore() { - if e := opts.automatedRestoreOnlyFlags(); e != nil { - return e - } - } - - if !opts.isHTTP() { - if e := opts.httpRestoreOnlyFlags(); e != nil { - return e - } - } - - return nil -} - -func (opts *RestoresStartOpts) httpRestoreOnlyFlags() error { - if opts.expires != "" { - return fmt.Errorf(onlyFor, flag.Expires, httpRestore) - } - if opts.maxDownloads > 0 { - return fmt.Errorf(onlyFor, flag.MaxDownloads, httpRestore) - } - if opts.expirationHours > 0 { - return fmt.Errorf(onlyFor, flag.ExpirationHours, httpRestore) - } - return nil -} - -func (opts *RestoresStartOpts) automatedRestoreOnlyFlags() error { - if opts.checkpointID != "" { - return fmt.Errorf(onlyFor, flag.CheckpointID, automatedRestore) - } - if opts.oplogTS != "" { - return fmt.Errorf(onlyFor, flag.OplogTS, automatedRestore) - } - if opts.oplogInc > 0 { - return fmt.Errorf(onlyFor, flag.OplogInc, automatedRestore) - } - if opts.pointInTimeUTCMillis > 0 { - return fmt.Errorf(onlyFor, flag.PointInTimeUTCMillis, automatedRestore) - } - return nil -} - -func markRequiredAutomatedRestoreFlags(cmd *cobra.Command) error { - if err := cmd.MarkFlagRequired(flag.TargetProjectID); err != nil { - return err - } - - return cmd.MarkFlagRequired(flag.TargetClusterID) -} - -// mongocli atlas backup(s) restore(s) job(s) start. -func RestoresStartBuilder() *cobra.Command { - opts := new(RestoresStartOpts) - cmd := &cobra.Command{ - Use: fmt.Sprintf("start <%s|%s>", automatedRestore, httpRestore), - Short: "Start a restore job for a project and cluster.", - Args: require.ExactValidArgs(1), - Annotations: map[string]string{ - "AUTOMATED_RESTORE|HTTPDesc": "Restore type.", - }, - ValidArgs: []string{automatedRestore, httpRestore}, - PreRunE: func(cmd *cobra.Command, args []string) error { - opts.method = args[0] - if opts.isAutomatedRestore() { - if err := markRequiredAutomatedRestoreFlags(cmd); err != nil { - return err - } - } - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.validateParams, - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.snapshotID, flag.SnapshotID, "", usage.RestoreSnapshotID) - cmd.Flags().StringVar(&opts.clusterID, flag.ClusterID, "", usage.ClusterID) - cmd.Flags().StringVar(&opts.targetClusterID, flag.TargetClusterID, "", usage.TargetClusterID) - cmd.Flags().StringVar(&opts.checkpointID, flag.CheckpointID, "", usage.CheckpointID) - cmd.Flags().StringVar(&opts.oplogTS, flag.OplogTS, "", usage.OplogTS) - cmd.Flags().Int64Var(&opts.oplogInc, flag.OplogInc, 0, usage.OplogInc) - cmd.Flags().Float64Var(&opts.pointInTimeUTCMillis, flag.PointInTimeUTCMillis, 0, usage.PointInTimeUTCMillis) - - // For Automatic restore - cmd.Flags().StringVar(&opts.targetProjectID, flag.TargetProjectID, "", usage.TargetProjectID) - // For http restore - cmd.Flags().StringVar(&opts.expires, flag.Expires, "", usage.Expires) - cmd.Flags().Int64Var(&opts.maxDownloads, flag.MaxDownloads, 0, usage.MaxDownloads) - cmd.Flags().Int64Var(&opts.expirationHours, flag.ExpirationHours, 0, usage.ExpirationHours) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.ClusterID) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/restores_start_test.go b/internal/cli/opsmanager/backup/restores_start_test.go deleted file mode 100644 index a5fe0dfa85..0000000000 --- a/internal/cli/opsmanager/backup/restores_start_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package backup - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestRestoresStart_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockContinuousJobCreator(ctrl) - - expected := &opsmngr.ContinuousJobs{} - - t.Run(automatedRestore, func(t *testing.T) { - listOpts := &RestoresStartOpts{ - store: mockStore, - method: automatedRestore, - clusterID: "Cluster0", - } - - mockStore. - EXPECT(). - CreateContinuousRestoreJob(listOpts.ProjectID, "Cluster0", listOpts.newContinuousJobRequest()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - - t.Run(httpRestore, func(t *testing.T) { - listOpts := &RestoresStartOpts{ - store: mockStore, - method: httpRestore, - clusterID: "Cluster0", - } - - mockStore. - EXPECT(). - CreateContinuousRestoreJob(listOpts.ProjectID, "Cluster0", listOpts.newContinuousJobRequest()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} diff --git a/internal/cli/opsmanager/backup/snapshots/list.go b/internal/cli/opsmanager/backup/snapshots/list.go deleted file mode 100644 index d3e619fa38..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/list.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/mongodb/mongodb-atlas-cli/internal/validate" - "github.com/spf13/cobra" -) - -const snapshotsTemplate = `ID CREATED COMPLETE{{range valueOrEmptySlice .Results}} -{{.ID}} {{.Created.Date}} {{.Complete}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - clusterID string - store store.ContinuousSnapshotsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.ContinuousSnapshots(opts.ConfigProjectID(), opts.clusterID, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli atlas backups snapshots list [--projectId projectId] [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := new(ListOpts) - cmd := &cobra.Command{ - Use: "list ", - Short: "List snapshots for a project and cluster.", - Aliases: []string{"ls"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterIdDesc": "ID of the cluster.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), snapshotsTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - if err := validate.ObjectID(args[0]); err != nil { - return err - } - opts.clusterID = args[0] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/snapshots/list_test.go b/internal/cli/opsmanager/backup/snapshots/list_test.go deleted file mode 100644 index 7fc89b65d8..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/list_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockContinuousSnapshotsLister(ctrl) - - expected := &opsmngr.ContinuousSnapshots{} - - clusterID := "5ec2ac941271767f21cbaefe" - - listOpts := &ListOpts{ - store: mockStore, - clusterID: clusterID, - } - - mockStore. - EXPECT(). - ContinuousSnapshots(listOpts.ProjectID, clusterID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Page, flag.Limit, flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/backup/snapshots/schedule/describe.go b/internal/cli/opsmanager/backup/snapshots/schedule/describe.go deleted file mode 100644 index 6dce9041ec..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/schedule/describe.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package schedule - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var describeTemplate = `PROJECT ID CLUSTER ID MONTHLY SNAPSHOT RETENTION MONTHS POINT IN TIME WINDOW HOURS -{{.GroupID}} {{.ClusterID}} {{.MonthlySnapshotRetentionMonths}} {{.PointInTimeWindowHours}} -` - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.SnapshotScheduleDescriber - clusterID string -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.GetSnapshotSchedule(opts.ConfigProjectID(), opts.clusterID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager backup snapshots schedule describe --clusterId clusterId --projectId projectId. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe", - Aliases: []string{"get"}, - Short: "Describe a snapshot schedule for a cluster.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.clusterID, flag.ClusterID, "", usage.ClusterID) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.ClusterID) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/snapshots/schedule/describe_test.go b/internal/cli/opsmanager/backup/snapshots/schedule/describe_test.go deleted file mode 100644 index eacdaf6cad..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/schedule/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package schedule - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSnapshotScheduleDescriber(ctrl) - - expected := &opsmngr.SnapshotSchedule{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT().GetSnapshotSchedule(opts.ConfigProjectID(), opts.clusterID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.Output, flag.ProjectID}, - ) -} diff --git a/internal/cli/opsmanager/backup/snapshots/schedule/schedule.go b/internal/cli/opsmanager/backup/snapshots/schedule/schedule.go deleted file mode 100644 index 699b664313..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/schedule/schedule.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package schedule - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "schedule" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup snapshot schedules for a cluster.", - } - - cmd.AddCommand( - DescribeBuilder(), - UpdateBuilder()) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/snapshots/schedule/schedule_test.go b/internal/cli/opsmanager/backup/snapshots/schedule/schedule_test.go deleted file mode 100644 index 015ba28ad8..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/schedule/schedule_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package schedule - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/backup/snapshots/schedule/update.go b/internal/cli/opsmanager/backup/snapshots/schedule/update.go deleted file mode 100644 index 76310185d5..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/schedule/update.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package schedule - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -var updateTemplate = "Snapshot schedule updated.\n" - -type UpdateOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.SnapshotScheduleUpdater - clusterID string - referenceTimeZoneOffset string - dailySnapshotRetentionDays int - clusterCheckpointIntervalMin int - monthlySnapshotRetentionMonths int - snapshotIntervalHours int - snapshotRetentionDays int - weeklySnapshotRetentionWeeks int - pointInTimeWindowHours int - referenceHourOfDay int - referenceMinuteOfHour int -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateSnapshotSchedule(opts.ConfigProjectID(), opts.clusterID, opts.newSnapshotSchedule()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *UpdateOpts) newSnapshotSchedule() *opsmngr.SnapshotSchedule { - snapshotSchedule := &opsmngr.SnapshotSchedule{ - ClusterID: opts.clusterID, - GroupID: opts.ConfigProjectID(), - ReferenceTimeZoneOffset: opts.referenceTimeZoneOffset, - DailySnapshotRetentionDays: &opts.dailySnapshotRetentionDays, - ClusterCheckpointIntervalMin: opts.clusterCheckpointIntervalMin, - MonthlySnapshotRetentionMonths: &opts.monthlySnapshotRetentionMonths, - SnapshotIntervalHours: opts.snapshotIntervalHours, - SnapshotRetentionDays: opts.snapshotRetentionDays, - WeeklySnapshotRetentionWeeks: &opts.weeklySnapshotRetentionWeeks, - } - - if opts.pointInTimeWindowHours >= 0 { - snapshotSchedule.PointInTimeWindowHours = &opts.pointInTimeWindowHours - } - - if opts.referenceHourOfDay >= 0 { - snapshotSchedule.ReferenceHourOfDay = &opts.referenceHourOfDay - } - - if opts.referenceMinuteOfHour >= 0 { - snapshotSchedule.ReferenceMinuteOfHour = &opts.referenceMinuteOfHour - } - - return snapshotSchedule -} - -// mongocli ops-manager backup snapshot(s) schedule update [--clusterID clusterID ][--projectId projectId] [--referenceTimeZoneOffset referenceTimeZoneOffset] -// [--dailySnapshotRetentionDays dailySnapshotRetentionDays] [--clusterCheckpointIntervalMin clusterCheckpointIntervalMin] -// [--snapshotIntervalHours snapshotIntervalHours] [--snapshotRetentionDays snapshotRetentionDays] [--weeklySnapshotRetentionWeeks weeklySnapshotRetentionWeeks] -// [--pointInTimeWindowHours pointInTimeWindowHours] [--referenceHourOfDay referenceHourOfDay] [--referenceMinuteOfHour referenceMinuteOfHour] -// [--monthlySnapshotRetentionMonths monthlySnapshotRetentionMonths] - -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update", - Short: "Update a snapshot schedule for a cluster.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.clusterID, flag.ClusterID, "", usage.ClusterID) - cmd.Flags().StringVar(&opts.referenceTimeZoneOffset, flag.ReferenceTimeZoneOffset, "", usage.ReferenceTimeZoneOffset) - cmd.Flags().IntVar(&opts.dailySnapshotRetentionDays, flag.DailySnapshotRetentionDays, 0, usage.DailySnapshotRetentionDays) - cmd.Flags().IntVar(&opts.clusterCheckpointIntervalMin, flag.ClusterCheckpointIntervalMin, 0, usage.ClusterCheckpointIntervalMin) - cmd.Flags().IntVar(&opts.snapshotIntervalHours, flag.SnapshotIntervalHours, 0, usage.SnapshotIntervalHours) - cmd.Flags().IntVar(&opts.snapshotRetentionDays, flag.SnapshotRetentionDays, 0, usage.SnapshotRetentionDays) - cmd.Flags().IntVar(&opts.weeklySnapshotRetentionWeeks, flag.WeeklySnapshotRetentionWeeks, 0, usage.WeeklySnapshotRetentionWeeks) - cmd.Flags().IntVar(&opts.pointInTimeWindowHours, flag.PointInTimeWindowHours, 0, usage.PointInTimeWindowHours) - cmd.Flags().IntVar(&opts.referenceHourOfDay, flag.ReferenceHourOfDay, 0, usage.ReferenceHourOfDay) - cmd.Flags().IntVar(&opts.referenceMinuteOfHour, flag.ReferenceMinuteOfHour, 0, usage.ReferenceMinuteOfHour) - cmd.Flags().IntVar(&opts.monthlySnapshotRetentionMonths, flag.MonthlySnapshotRetentionMonths, 0, usage.MonthlySnapshotRetentionMonths) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.ClusterID) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/snapshots/schedule/update_test.go b/internal/cli/opsmanager/backup/snapshots/schedule/update_test.go deleted file mode 100644 index a5ae208203..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/schedule/update_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package schedule - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSnapshotScheduleUpdater(ctrl) - - expected := &opsmngr.SnapshotSchedule{} - - opts := &UpdateOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateSnapshotSchedule(opts.ConfigProjectID(), opts.clusterID, opts.newSnapshotSchedule()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Output, flag.ProjectID, flag.ClusterID, flag.SnapshotRetentionDays, flag.DailySnapshotRetentionDays, flag.WeeklySnapshotRetentionWeeks, - flag.PointInTimeWindowHours, flag.ReferenceHourOfDay, flag.ReferenceMinuteOfHour, flag.ReferenceTimeZoneOffset, flag.SnapshotIntervalHours, - flag.ClusterCheckpointIntervalMin, - }, - ) -} diff --git a/internal/cli/opsmanager/backup/snapshots/snapshots.go b/internal/cli/opsmanager/backup/snapshots/snapshots.go deleted file mode 100644 index 3220d356fe..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/snapshots.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package snapshots - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/backup/snapshots/schedule" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "snapshots" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage backup snapshots for your project.", - } - - cmd.AddCommand( - ListBuilder(), - schedule.Builder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/backup/snapshots/snapshots_test.go b/internal/cli/opsmanager/backup/snapshots/snapshots_test.go deleted file mode 100644 index 5e253c5197..0000000000 --- a/internal/cli/opsmanager/backup/snapshots/snapshots_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package snapshots - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/clusters/apply.go b/internal/cli/opsmanager/clusters/apply.go deleted file mode 100644 index 24edbe573b..0000000000 --- a/internal/cli/opsmanager/clusters/apply.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/convert" - "github.com/mongodb/mongodb-atlas-cli/internal/file" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -type ApplyOpts struct { - cli.GlobalOpts - filename string - fs afero.Fs - store store.AutomationPatcher -} - -func (opts *ApplyOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ApplyOpts) Run() error { - newConfig := new(convert.ClusterConfig) - err := file.Load(opts.fs, opts.filename, newConfig) - if err != nil { - return err - } - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if err := newConfig.PatchAutomationConfig(current); err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli cloud-manager cluster(s) apply --projectId projectId --file myfile.yaml. -func ApplyBuilder() *cobra.Command { - opts := &ApplyOpts{ - fs: afero.NewOsFs(), - } - cmd := &cobra.Command{ - Use: "apply", - Short: "Apply a new cluster configuration for your project.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.filename, flag.File, flag.FileShort, "", "Filename to use to change the automation config") - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.File) - _ = cmd.MarkFlagFilename(flag.File) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/apply_test.go b/internal/cli/opsmanager/clusters/apply_test.go deleted file mode 100644 index 9f501e0aef..0000000000 --- a/internal/cli/opsmanager/clusters/apply_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" - "github.com/spf13/afero" -) - -func TestApply_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - appFS := afero.NewMemMapFs() - // create test file - fileYML := ` ---- -name: "myReplicaSet" -version: 4.2.2 -featureCompatibilityVersion: 4.2 -processes: - - hostname: host0 - dbPath: /data/myReplicaSet/rs1 - logPath: /data/myReplicaSet/rs1/mongodb.log - priority: 1 - votes: 1 - port: 29010 - - hostname: host1 - dbPath: /data/myReplicaSet/rs2 - logPath: /data/myReplicaSet/rs2/mongodb.log - priority: 1 - votes: 1 - port: 29020 - - hostname: host2 - dbPath: /data/myReplicaSet/rs3 - logPath: /data/myReplicaSet/rs3/mongodb.log - priority: 1 - votes: 1 - port: 29030` - fileName := "test_om_apply.yml" - _ = afero.WriteFile(appFS, fileName, []byte(fileYML), 0600) - createOpts := &ApplyOpts{ - store: mockStore, - fs: appFS, - filename: fileName, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/clusters/clusters.go b/internal/cli/opsmanager/clusters/clusters.go deleted file mode 100644 index c576522d84..0000000000 --- a/internal/cli/opsmanager/clusters/clusters.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "clusters" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage clusters for your project.", - } - - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - CreateBuilder(), - UpdateBuilder(), - DeleteBuilder(), - ApplyBuilder(), - IndexesBuilder(), - UnmanageBuilder(), - RestartBuilder(), - StartupBuilder(), - ShutdownBuilder(), - ReclaimFreeSpaceBuilder(), - ResyncBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/clusters_test.go b/internal/cli/opsmanager/clusters/clusters_test.go deleted file mode 100644 index 75061cac17..0000000000 --- a/internal/cli/opsmanager/clusters/clusters_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 13, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/clusters/create.go b/internal/cli/opsmanager/clusters/create.go deleted file mode 100644 index f30335c895..0000000000 --- a/internal/cli/opsmanager/clusters/create.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/convert" - "github.com/mongodb/mongodb-atlas-cli/internal/file" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -type CreateOpts struct { - cli.GlobalOpts - filename string - fs afero.Fs - store store.AutomationPatcher -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - newConfig := new(convert.ClusterConfig) - err := file.Load(opts.fs, opts.filename, newConfig) - if err != nil { - return err - } - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if search.ClusterExists(current, newConfig.Name) { - return fmt.Errorf("cluster %s already exists", newConfig.Name) - } - - if err := newConfig.PatchAutomationConfig(current); err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli cloud-manager cluster(s) create --projectId projectId --file myfile.yaml. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{ - fs: afero.NewOsFs(), - } - cmd := &cobra.Command{ - Use: "create", - Short: "Create a MongoDB cluster.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.filename, flag.File, flag.FileShort, "", "Filename to use to create the cluster") - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.File) - _ = cmd.MarkFlagFilename(flag.File) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/create_test.go b/internal/cli/opsmanager/clusters/create_test.go deleted file mode 100644 index 429a8acdc7..0000000000 --- a/internal/cli/opsmanager/clusters/create_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" - "github.com/spf13/afero" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - appFS := afero.NewMemMapFs() - // create test file - fileYML := ` ---- -name: "cluster_2" -version: 4.2.2 -featureCompatibilityVersion: 4.2 -processes: - - hostname: host0 - dbPath: /data/cluster_2/rs1 - logPath: /data/cluster_2/rs1/mongodb.log - priority: 1 - votes: 1 - port: 29010 - - hostname: host1 - dbPath: /data/cluster_2/rs2 - logPath: /data/cluster_2/rs2/mongodb.log - priority: 1 - votes: 1 - port: 29020 - - hostname: host2 - dbPath: /data/cluster_2/rs3 - logPath: /data/cluster_2/rs3/mongodb.log - priority: 1 - votes: 1 - port: 29030` - fileName := "test_om_create.yml" - _ = afero.WriteFile(appFS, fileName, []byte(fileYML), 0600) - - createOpts := &CreateOpts{ - store: mockStore, - fs: appFS, - filename: fileName, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/clusters/delete.go b/internal/cli/opsmanager/clusters/delete.go deleted file mode 100644 index d9b6b0e212..0000000000 --- a/internal/cli/opsmanager/clusters/delete.go +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" - "go.mongodb.org/ops-manager/opsmngr" -) - -type DeleteOpts struct { - cli.GlobalOpts - cli.WatchOpts - *cli.DeleteOpts - store store.CloudManagerClustersDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - if !opts.Confirm { - return nil - } - - hostIDs, err := opts.hostIDs() - if err != nil { - return err - } - - // shutdown cluster - err = opts.shutdownCluster() - if err != nil { - return err - } - - // Remove cluster from automation - err = opts.removeClusterFromAutomation() - if err != nil { - return err - } - - // Stop monitoring - err = opts.stopMonitoring(hostIDs) - if err != nil { - return err - } - - fmt.Print("Cluster deleted\n") - return nil -} - -func (opts *DeleteOpts) hostIDs() ([]string, error) { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return nil, err - } - - hostnameMap := make(map[string][]int) - replicaSetHostNames(current, hostnameMap, opts.Entry) - opts.shardClusterHostNames(current, hostnameMap) - - var hostIDs []string - for k, ports := range hostnameMap { - for _, port := range ports { - host, err := opts.store.HostByHostname(opts.ConfigProjectID(), k, port) - if err != nil { - return nil, err - } - hostIDs = append(hostIDs, host.ID) - } - } - - if len(hostIDs) == 0 { - return nil, fmt.Errorf("cluster '%s' doesn't exist", opts.Entry) - } - - return hostIDs, nil -} - -func replicaSetHostNames(automationConfig *opsmngr.AutomationConfig, hostnameMap map[string][]int, name string) { - for _, process := range automationConfig.Processes { - if process.Cluster == name || (process.Args26.Replication != nil && process.Args26.Replication.ReplSetName == name) { - hostnameMap[process.Hostname] = append(hostnameMap[process.Hostname], process.Args26.NET.Port) - } - } -} - -func (opts *DeleteOpts) shardClusterHostNames(automationConfig *opsmngr.AutomationConfig, hostnameMap map[string][]int) { - for _, sharding := range automationConfig.Sharding { - if sharding.Name == opts.Entry { - for _, shard := range sharding.Shards { - replicaSetHostNames(automationConfig, hostnameMap, shard.RS) - } - // config rs - replicaSetHostNames(automationConfig, hostnameMap, sharding.ConfigServerReplica) - break - } - } -} - -func (opts *DeleteOpts) stopMonitoring(hostIDs []string) error { - for _, id := range hostIDs { - if err := opts.store.StopMonitoring(opts.ConfigProjectID(), id); err != nil { - return err - } - } - - return nil -} - -func (opts *DeleteOpts) removeClusterFromAutomation() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - - atmcfg.RemoveByClusterName(current, opts.Entry) - if err = opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - // Wait for changes being deployed on automation - _, err = opts.Watch(opts.watcher) - return err -} - -func (opts *DeleteOpts) shutdownCluster() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - if !search.ClusterExists(current, opts.Entry) { - return fmt.Errorf("cluster '%s' doesn't exist", opts.Entry) - } - - // Shutdown Cluster - atmcfg.Shutdown(current, opts.Entry) - if err = opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - // Wait for changes being deployed on automation - _, err = opts.Watch(opts.watcher) - return err -} - -func (opts *DeleteOpts) watcher() (any, bool, error) { - result, err := opts.store.GetAutomationStatus(opts.ConfigProjectID()) - if err != nil { - return nil, false, err - } - - for _, p := range result.Processes { - if p.LastGoalVersionAchieved != result.GoalVersion { - return nil, false, nil - } - } - return nil, true, nil -} - -// mongocli cloud-manager cluster(s) delete --projectId projectId [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("", "Cluster not deleted\""), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Completely removes a cluster from your project.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "nameDesc": "Name of the cLuster.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - opts.OutWriter = cmd.OutOrStdout() - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/delete_test.go b/internal/cli/opsmanager/clusters/delete_test.go deleted file mode 100644 index ce024984d1..0000000000 --- a/internal/cli/opsmanager/clusters/delete_test.go +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDeleteReplicaSet_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockCloudManagerClustersDeleter(ctrl) - - expected := fixture.AutomationConfig() - watchExpected := fixture.AutomationStatus() - host0 := &opsmngr.Host{ - Hostname: "host0", - ID: "0", - } - host1 := &opsmngr.Host{ - Hostname: "host1", - ID: "1", - } - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "myReplicaSet", - }, - } - - mockStore. - EXPECT(). - GetAutomationConfig(deleteOpts.ProjectID). - Return(expected, nil). - Times(3) - - mockStore. - EXPECT(). - UpdateAutomationConfig(deleteOpts.ProjectID, expected). - Return(nil). - Times(2) - - mockStore.EXPECT(). - GetAutomationStatus(deleteOpts.ProjectID). - Return(watchExpected, nil). - Times(2) - - mockStore. - EXPECT(). - StopMonitoring(deleteOpts.ProjectID, "0"). - Return(nil). - Times(2) - - mockStore. - EXPECT(). - StopMonitoring(deleteOpts.ProjectID, "1"). - Return(nil). - Times(1) - - mockStore. - EXPECT(). - HostByHostname(deleteOpts.ProjectID, "host0", 27000). - Return(host0, nil). - Times(1) - - mockStore. - EXPECT(). - HostByHostname(deleteOpts.ProjectID, "host1", 27010). - Return(host1, nil). - Times(1) - - mockStore. - EXPECT(). - HostByHostname(deleteOpts.ProjectID, "host0", 27020). - Return(host0, nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteShardedCluster_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockCloudManagerClustersDeleter(ctrl) - - expected := fixture.AutomationConfigWithOneShardedCluster("MyCluster", false) - watchExpected := fixture.AutomationStatus() - host0 := &opsmngr.Host{ - Hostname: "example", - ID: "0", - } - - host1 := &opsmngr.Host{ - Hostname: "example", - ID: "1", - } - - host2 := &opsmngr.Host{ - Hostname: "example", - ID: "2", - } - - deleteOpts := &DeleteOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "MyCluster", - }, - } - - mockStore. - EXPECT(). - GetAutomationConfig(deleteOpts.ProjectID). - Return(expected, nil). - Times(3) - - mockStore. - EXPECT(). - UpdateAutomationConfig(deleteOpts.ProjectID, expected). - Return(nil). - Times(2) - - mockStore.EXPECT(). - GetAutomationStatus(deleteOpts.ProjectID). - Return(watchExpected, nil). - Times(2) - - mockStore. - EXPECT(). - StopMonitoring(deleteOpts.ProjectID, "0"). - Return(nil). - Times(1) - - mockStore. - EXPECT(). - StopMonitoring(deleteOpts.ProjectID, "1"). - Return(nil). - Times(1) - - mockStore. - EXPECT(). - StopMonitoring(deleteOpts.ProjectID, "2"). - Return(nil). - Times(1) - - mockStore. - EXPECT(). - HostByHostname(deleteOpts.ProjectID, "example", 1). - Return(host0, nil). - Times(1) - - mockStore. - EXPECT(). - HostByHostname(deleteOpts.ProjectID, "example", 2). - Return(host1, nil). - Times(1) - - mockStore. - EXPECT(). - HostByHostname(deleteOpts.ProjectID, "example", 3). - Return(host2, nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.ProjectID, flag.Force}, - ) -} diff --git a/internal/cli/opsmanager/clusters/describe.go b/internal/cli/opsmanager/clusters/describe.go deleted file mode 100644 index 176389cd4d..0000000000 --- a/internal/cli/opsmanager/clusters/describe.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/convert" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/mongodb/mongodb-atlas-cli/internal/validate" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - name string - store store.CloudManagerClustersDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var describeTemplate = `ID NAME TYPE REPLICASET NAME -{{.ID}} {{.ClusterName}} {{.TypeName}} {{.ReplicaSetName}} -` - -func (opts *DescribeOpts) Run() error { - r, err := opts.cluster() - if err != nil { - return err - } - - return opts.Print(r) -} -func (opts *DescribeOpts) validateArg() error { - if opts.ConfigOutput() != "" { - return nil - } - if err := validate.ObjectID(opts.name); err != nil { - return fmt.Errorf("please provide a valid cluster ID or provide an output format to use names, %w", err) - } - return nil -} - -func (opts *DescribeOpts) cluster() (interface{}, error) { - if opts.ConfigOutput() == "" { - return opts.store.OpsManagerCluster(opts.ConfigProjectID(), opts.name) - } - c, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return nil, err - } - r := convert.FromAutomationConfig(c) - for _, rs := range r { - if rs.Name == opts.name { - return rs, nil - } - } - return nil, fmt.Errorf("replica set %s not found", opts.name) -} - -// mongocli cloud-manager cluster(s) describe --projectId projectId. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe ", - Short: "Describe a cluster.", - Long: `When describing cluster with no output format please provide the cluster ID. -When using an output format please provide the cluster name.`, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "id|nameDesc": "Name or ID of the cluster.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.validateArg, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.name = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/describe_test.go b/internal/cli/opsmanager/clusters/describe_test.go deleted file mode 100644 index 88edb529ca..0000000000 --- a/internal/cli/opsmanager/clusters/describe_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" - "github.com/stretchr/testify/require" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockCloudManagerClustersDescriber(ctrl) - - t.Run("describe cluster simplified", func(t *testing.T) { - descOpts := &DescribeOpts{ - store: mockStore, - name: "myReplicaSet", - } - expected := &opsmngr.Cluster{} - mockStore. - EXPECT(). - OpsManagerCluster(descOpts.ProjectID, descOpts.name). - Return(expected, nil). - Times(1) - - require.NoError(t, descOpts.Run()) - }) - - t.Run("describe cluster for JSON", func(t *testing.T) { - descOpts := &DescribeOpts{ - store: mockStore, - OutputOpts: cli.OutputOpts{Output: "json"}, - name: "myReplicaSet", - } - - expected := fixture.AutomationConfig() - mockStore. - EXPECT(). - GetAutomationConfig(descOpts.ProjectID). - Return(expected, nil). - Times(1) - - require.NoError(t, descOpts.Run()) - }) -} - -func TestDescribeOpts_validateArg(t *testing.T) { - type fields struct { - OutputOpts cli.OutputOpts - name string - } - tests := []struct { - name string - fields fields - wantErr require.ErrorAssertionFunc - }{ - { - name: "no output valid id", - fields: fields{ - OutputOpts: cli.OutputOpts{}, - name: "62bdbde098ecb26e563edf84", - }, - wantErr: require.NoError, - }, - { - name: "no output invalid id", - fields: fields{ - OutputOpts: cli.OutputOpts{}, - name: "test", - }, - wantErr: require.Error, - }, - { - name: "json output valid id", - fields: fields{ - OutputOpts: cli.OutputOpts{Output: "json"}, - name: "test", - }, - wantErr: require.NoError, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - opts := &DescribeOpts{ - OutputOpts: tt.fields.OutputOpts, - name: tt.fields.name, - } - tt.wantErr(t, opts.validateArg()) - }) - } -} diff --git a/internal/cli/opsmanager/clusters/indexes.go b/internal/cli/opsmanager/clusters/indexes.go deleted file mode 100644 index ca9db0dddb..0000000000 --- a/internal/cli/opsmanager/clusters/indexes.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func IndexesBuilder() *cobra.Command { - const use = "indexes" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage cluster rolling indexes for your project.", - } - cmd.AddCommand(IndexesCreateBuilder()) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/indexes_create.go b/internal/cli/opsmanager/clusters/indexes_create.go deleted file mode 100644 index 9e9e307b2c..0000000000 --- a/internal/cli/opsmanager/clusters/indexes_create.go +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - "strings" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/atmcfg" - "go.mongodb.org/ops-manager/opsmngr" -) - -type IndexesCreateOpts struct { - cli.GlobalOpts - name string - db string - collection string - rsName string - locale string - caseFirst string - alternate string - maxVariable string - strength int - caseLevel bool - numericOrdering bool - normalization bool - backwards bool - sparse bool - keys []string - store store.AutomationPatcher -} - -func (opts *IndexesCreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *IndexesCreateOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - - index, err := opts.newIndex() - if err != nil { - return err - } - - err = atmcfg.AddIndexConfig(current, index) - if err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -func (opts *IndexesCreateOpts) newIndex() (*opsmngr.IndexConfig, error) { - keys, err := opts.indexKeys() - if err != nil { - return nil, err - } - - i := new(opsmngr.IndexConfig) - i.DBName = opts.db - i.CollectionName = opts.collection - i.RSName = opts.rsName - i.Key = keys - i.Options = opts.newIndexOptions() - - if opts.locale != "" { - i.Collation = opts.newCollationOptions() - } - - return i, nil -} - -func (opts *IndexesCreateOpts) newIndexOptions() *opsmngr.IndexOptions { - return &opsmngr.IndexOptions{ - Sparse: opts.sparse, - Name: opts.name, - } -} - -func (opts *IndexesCreateOpts) newCollationOptions() *atlas.CollationOptions { - return &atlas.CollationOptions{ - Locale: opts.locale, - CaseLevel: opts.caseLevel, - CaseFirst: opts.caseFirst, - Strength: opts.strength, - NumericOrdering: opts.numericOrdering, - Alternate: opts.alternate, - MaxVariable: opts.maxVariable, - Normalization: opts.normalization, - Backwards: opts.backwards, - } -} - -const keyParts = 2 - -// indexKeys takes a slice of values formatted as key:value and returns an array of slice [[key, value][key, value]]. -func (opts *IndexesCreateOpts) indexKeys() ([][]string, error) { - propertiesList := make([][]string, len(opts.keys)) - for i, key := range opts.keys { - value := strings.Split(key, ":") - if len(value) != keyParts { - return nil, fmt.Errorf("unexpected key format: %s", key) - } - values := []string{value[0], value[1]} - propertiesList[i] = values - } - - return propertiesList, nil -} - -// IndexesCreateBuilder mongocli cloud-manager cluster(s) index(es) create [name] -// --rsName rsName -// --dbName dbName -// [--key field:type] -// [--projectId projectId] -// --locale locale -// --caseFirst caseFirst -// --alternate alternate -// --maxVariable maxVariable -// --strength strength -// --caseLevel caseLevel -// --numericOrdering numericOrdering -// --normalization normalization -// --backwards backwards -// --unique unique -// --sparse sparse -// --background background. -func IndexesCreateBuilder() *cobra.Command { - opts := &IndexesCreateOpts{} - cmd := &cobra.Command{ - Use: "create [indexName]", - Short: "Create a rolling index for your MongoDB cluster.", - Args: require.MaximumNArgs(1), - Annotations: map[string]string{ - "indexNameDesc": "Name of the index to create.", - }, - Example: ` # Create an index named bedrooms_1 on the listings collection of the realestate database on the replica set repl1. - The command uses the default profile. - - mongocli om clusters indexes create bedrooms_1 \ - --collectionName listings --db realestate --key bedrooms:1 \ - --rsName repl1`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, args []string) error { - if len(args) == 1 { - opts.name = args[0] - } - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.db, flag.Database, "", usage.Database) - cmd.Flags().StringVar(&opts.rsName, flag.RSName, "", usage.RSName) - cmd.Flags().StringVar(&opts.collection, flag.CollectionName, "", usage.Collection) - cmd.Flags().StringSliceVar(&opts.keys, flag.Key, []string{}, usage.Key) - cmd.Flags().StringVar(&opts.locale, flag.Locale, "", usage.Locale) - cmd.Flags().StringVar(&opts.caseFirst, flag.CaseFirst, "", usage.CaseFirst) - cmd.Flags().StringVar(&opts.alternate, flag.Alternate, "", usage.Alternate) - cmd.Flags().StringVar(&opts.maxVariable, flag.MaxVariable, "", usage.MaxVariable) - cmd.Flags().BoolVar(&opts.caseLevel, flag.CaseLevel, false, usage.CaseLevel) - cmd.Flags().BoolVar(&opts.numericOrdering, flag.NumericOrdering, false, usage.NumericOrdering) - cmd.Flags().BoolVar(&opts.normalization, flag.Normalization, false, usage.Normalization) - cmd.Flags().BoolVar(&opts.backwards, flag.Backwards, false, usage.Backwards) - cmd.Flags().IntVar(&opts.strength, flag.Strength, 0, usage.Strength) - cmd.Flags().BoolVar(&opts.sparse, flag.Sparse, false, usage.Sparse) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.RSName) - _ = cmd.MarkFlagRequired(flag.Database) - _ = cmd.MarkFlagRequired(flag.CollectionName) - _ = cmd.MarkFlagRequired(flag.Key) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/indexes_create_test.go b/internal/cli/opsmanager/clusters/indexes_create_test.go deleted file mode 100644 index 9317b1149c..0000000000 --- a/internal/cli/opsmanager/clusters/indexes_create_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestIndexesCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - createOpts := &IndexesCreateOpts{ - GlobalOpts: cli.GlobalOpts{}, - name: "index", - db: "db", - collection: "db", - rsName: "rsName", - locale: "locale", - caseFirst: "test", - alternate: "alternate", - maxVariable: "max", - strength: 0, - caseLevel: false, - numericOrdering: false, - normalization: false, - backwards: false, - keys: []string{"field:key", "field:key", "field:key"}, - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/clusters/list.go b/internal/cli/opsmanager/clusters/list.go deleted file mode 100644 index e50693930f..0000000000 --- a/internal/cli/opsmanager/clusters/list.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/convert" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.CloudManagerClustersLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -// listTemplate used when project ID is given. -var listTemplate = `ID NAME TYPE REPLICASET NAME{{range valueOrEmptySlice .Results}} -{{.ID}} {{.ClusterName}} {{.TypeName}} {{.ReplicaSetName}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.clusters() - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *ListOpts) clusters() (interface{}, error) { - if opts.IsPlainOutput() { - return opts.store.ProjectClusters(opts.ConfigProjectID(), nil) - } - c, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return nil, err - } - r := convert.FromAutomationConfig(c) - - return r, nil -} - -// ListBuilder mongocli cloud-manager cluster(s) list --projectId projectId. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "List clusters for your project.", - Long: `When listing clusters with no output format the information provided is defined by monitoring. -When using an output format the information will be provided by automation.`, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/list_test.go b/internal/cli/opsmanager/clusters/list_test.go deleted file mode 100644 index 2d2b5f5cdf..0000000000 --- a/internal/cli/opsmanager/clusters/list_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "bytes" - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" - "github.com/stretchr/testify/require" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockCloudManagerClustersLister(ctrl) - - t.Run("clusters for project simple view", func(t *testing.T) { - expected := &opsmngr.Clusters{} - - listOpts := &ListOpts{ - store: mockStore, - } - buf := new(bytes.Buffer) - listOpts.OutWriter = buf - listOpts.ProjectID = "1" - mockStore. - EXPECT(). - ProjectClusters(listOpts.ProjectID, nil). - Return(expected, nil). - Times(1) - - require.NoError(t, listOpts.Run()) - test.VerifyOutputTemplate(t, listTemplate, expected) - }) - - t.Run("clusters for project json view", func(t *testing.T) { - expected := fixture.AutomationConfig() - listOpts := &ListOpts{ - store: mockStore, - } - buf := new(bytes.Buffer) - listOpts.OutWriter = buf - listOpts.ProjectID = "1" - listOpts.Output = config.JSON - mockStore. - EXPECT(). - GetAutomationConfig(listOpts.ProjectID). - Return(expected, nil). - Times(1) - require.NoError(t, listOpts.Run()) - }) -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator(t, - ListBuilder(), - 0, - []string{ - flag.Output, - flag.ProjectID, - }) -} diff --git a/internal/cli/opsmanager/clusters/reclaim_free_space.go b/internal/cli/opsmanager/clusters/reclaim_free_space.go deleted file mode 100644 index e2e7f11a6b..0000000000 --- a/internal/cli/opsmanager/clusters/reclaim_free_space.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - "strings" - - "github.com/AlecAivazis/survey/v2" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type ReclaimFreeSpaceOpts struct { - cli.GlobalOpts - confirm bool - clusterName string - timestamp string - processes []string - store store.AutomationPatcher -} - -func (opts *ReclaimFreeSpaceOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ReclaimFreeSpaceOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - - err = atmcfg.ReclaimFreeSpaceForProcessesByClusterName(current, opts.clusterName, opts.timestamp, opts.processes) - if err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -func (opts *ReclaimFreeSpaceOpts) Confirm() error { - if opts.confirm { - return nil - } - - process := opts.clusterName - - if len(opts.processes) > 0 { - process = fmt.Sprintf("%s (%s)", opts.clusterName, strings.Join(opts.processes, ", ")) - } - - prompt := &survey.Confirm{ - Message: fmt.Sprintf("Are you sure you want to reclaim free space for: %s", process), - } - return telemetry.TrackAskOne(prompt, &opts.confirm) -} - -// mongocli cloud-manager cluster(s) reclaimFreeSpace|rfs [--processName process1,process2...][--timestamp timestamp] [--force]. -func ReclaimFreeSpaceBuilder() *cobra.Command { - opts := &ReclaimFreeSpaceOpts{} - cmd := &cobra.Command{ - Use: "reclaimFreeSpace ", - Short: "Reclaim unused space for a cluster using compact.", - Long: `During certain operations, MongoDB might move or delete data but it doesn't free the currently unused space. Ops Manager reclaims the disk space in a rolling fashion across members of the replica set or shards.`, - Aliases: []string{"rfs"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Name of the cluster for which you want to reclaim free space.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.clusterName = args[0] - return opts.Confirm() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.processes, flag.ProcessName, []string{}, usage.ProcessName) - cmd.Flags().BoolVar(&opts.confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.timestamp, flag.Timestamp, "", usage.ReclaimFreeSpaceTimestamp) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/reclaim_free_space_test.go b/internal/cli/opsmanager/clusters/reclaim_free_space_test.go deleted file mode 100644 index bdd0e3bb58..0000000000 --- a/internal/cli/opsmanager/clusters/reclaim_free_space_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestReclaimFreeSpace_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - opts := &ReclaimFreeSpaceOpts{ - store: mockStore, - confirm: true, - clusterName: "myReplicaSet2", - } - - mockStore. - EXPECT(). - GetAutomationConfig(opts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(opts.ProjectID, expected). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestReclaimFreeSpaceBuilder(t *testing.T) { - test.CmdValidator( - t, - ReclaimFreeSpaceBuilder(), - 0, - []string{flag.ProjectID, flag.Force, flag.ProcessName}, - ) -} diff --git a/internal/cli/opsmanager/clusters/restart.go b/internal/cli/opsmanager/clusters/restart.go deleted file mode 100644 index c7693be5c4..0000000000 --- a/internal/cli/opsmanager/clusters/restart.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - "strings" - - "github.com/AlecAivazis/survey/v2" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type RestartOpts struct { - cli.GlobalOpts - clusterName string - confirm bool - processes []string - store store.AutomationPatcher -} - -func (opts *RestartOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *RestartOpts) Run() error { - if !opts.confirm { - return nil - } - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if !search.ClusterExists(current, opts.clusterName) { - return fmt.Errorf("cluster '%s' doesn't exist", opts.clusterName) - } - - err = atmcfg.RestartProcessesByClusterName(current, opts.clusterName, opts.processes) - if err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -func (opts *RestartOpts) Confirm() error { - if opts.confirm { - return nil - } - - startupProcess := opts.clusterName - - if len(opts.processes) > 0 { - startupProcess = fmt.Sprintf("%s (%s)", opts.clusterName, strings.Join(opts.processes, ", ")) - } - - prompt := &survey.Confirm{ - Message: fmt.Sprintf("Are you sure you want to restart: %s", startupProcess), - } - return telemetry.TrackAskOne(prompt, &opts.confirm) -} - -// mongocli cloud-manager cluster(s) restart --process hostname:port,hostname2:port2 --projectId projectId [--force]. -func RestartBuilder() *cobra.Command { - opts := &RestartOpts{} - cmd := &cobra.Command{ - Use: "restart ", - Short: "Restart a cluster for your project.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Name of the cluster you want to restart.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.clusterName = args[0] - return opts.Confirm() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.processes, flag.ProcessName, []string{}, usage.ProcessName) - cmd.Flags().BoolVar(&opts.confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/restart_test.go b/internal/cli/opsmanager/clusters/restart_test.go deleted file mode 100644 index f86a70c06b..0000000000 --- a/internal/cli/opsmanager/clusters/restart_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestRestart_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - opts := &RestartOpts{ - store: mockStore, - confirm: true, - clusterName: "myReplicaSet", - } - - mockStore. - EXPECT(). - GetAutomationConfig(opts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(opts.ProjectID, expected). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestRestartBuilder(t *testing.T) { - test.CmdValidator( - t, - RestartBuilder(), - 0, - []string{flag.ProjectID, flag.Force, flag.ProcessName}, - ) -} diff --git a/internal/cli/opsmanager/clusters/resync.go b/internal/cli/opsmanager/clusters/resync.go deleted file mode 100644 index 11546a59ba..0000000000 --- a/internal/cli/opsmanager/clusters/resync.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - "strings" - - "github.com/AlecAivazis/survey/v2" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type resyncOpts struct { - cli.GlobalOpts - confirm bool - clusterName string - timestamp string - processes []string - store store.AutomationPatcher -} - -func (opts *resyncOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *resyncOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - - if err = atmcfg.StartInitialSyncAtForProcessesByClusterName(current, opts.clusterName, opts.timestamp, opts.processes); err != nil { - return err - } - - if err = opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -func (opts *resyncOpts) Confirm() error { - if opts.confirm { - return nil - } - - process := opts.clusterName - - if len(opts.processes) > 0 { - process = fmt.Sprintf("%s (%s)", opts.clusterName, strings.Join(opts.processes, ", ")) - } - - prompt := &survey.Confirm{ - Message: fmt.Sprintf("Are you sure you want to reclaim free space for: %s", process), - } - return telemetry.TrackAskOne(prompt, &opts.confirm) -} - -// ResyncBuilder mongocli cloud-manager cluster(s) resync [--processName process1,process2...][--timestamp timestamp] [--force]. -func ResyncBuilder() *cobra.Command { - opts := &resyncOpts{} - cmd := &cobra.Command{ - Use: "resync ", - Short: "Start an initial sync for a cluster or process.", - Long: `The MongoDB Agent checks whether the specified timestamp is later than the time of the last resync, and if confirmed, the MongoDB Agent: - -1. Starts the initial sync on the secondary nodes in a rolling fashion -2. Waits until you ask the primary node to become the secondary with the rs.stepDown() method -3. Starts the initial sync on the primary node - -Warning: Use this method with caution. During initial sync, Automation removes the entire contents of the node’s dbPath directory. - -To learn more, see: https://docs.mongodb.com/manual/tutorial/resync-replica-set-member/`, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Name of the cluster for which you want to start a resync.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context())); err != nil { - return err - } - opts.clusterName = args[0] - return opts.Confirm() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.processes, flag.ProcessName, []string{}, usage.ProcessName) - cmd.Flags().BoolVar(&opts.confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.timestamp, flag.Timestamp, "", usage.ResyncTimestamp) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/resync_test.go b/internal/cli/opsmanager/clusters/resync_test.go deleted file mode 100644 index 1fa082feb0..0000000000 --- a/internal/cli/opsmanager/clusters/resync_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestResync_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - opts := &resyncOpts{ - store: mockStore, - confirm: true, - clusterName: "myReplicaSet2", - } - - mockStore. - EXPECT(). - GetAutomationConfig(opts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(opts.ProjectID, expected). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestResyncBuilder(t *testing.T) { - test.CmdValidator( - t, - ResyncBuilder(), - 0, - []string{flag.ProjectID, flag.Force, flag.ProcessName}, - ) -} diff --git a/internal/cli/opsmanager/clusters/shutdown.go b/internal/cli/opsmanager/clusters/shutdown.go deleted file mode 100644 index a1f4b757d1..0000000000 --- a/internal/cli/opsmanager/clusters/shutdown.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - "strings" - - "github.com/AlecAivazis/survey/v2" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type ShutdownOpts struct { - cli.GlobalOpts - clusterName string - confirm bool - processes []string - store store.AutomationPatcher -} - -func (opts *ShutdownOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ShutdownOpts) Run() error { - if !opts.confirm { - return nil - } - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - - if !search.ClusterExists(current, opts.clusterName) { - return fmt.Errorf("cluster '%s' doesn't exist", opts.clusterName) - } - - err = atmcfg.ShutdownProcessesByClusterName(current, opts.clusterName, opts.processes) - if err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -func (opts *ShutdownOpts) Confirm() error { - if opts.confirm { - return nil - } - - shutdownProcess := opts.clusterName - - if len(opts.processes) > 0 { - shutdownProcess = fmt.Sprintf("%s (%s)", opts.clusterName, strings.Join(opts.processes, ", ")) - } - prompt := &survey.Confirm{ - Message: fmt.Sprintf("Are you sure you want to shutdown: %s", shutdownProcess), - } - return telemetry.TrackAskOne(prompt, &opts.confirm) -} - -// mongocli cloud-manager cluster(s) shutdown --projectId projectId --processName hostname:port,hostname:port[--force]. -func ShutdownBuilder() *cobra.Command { - opts := &ShutdownOpts{} - cmd := &cobra.Command{ - Use: "shutdown ", - Short: "Shutdown a cluster for your project.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Name of the cluster that you want to shutdown.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.clusterName = args[0] - return opts.Confirm() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.confirm, flag.Force, false, usage.Force) - cmd.Flags().StringSliceVar(&opts.processes, flag.ProcessName, []string{}, usage.ProcessName) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/shutdown_test.go b/internal/cli/opsmanager/clusters/shutdown_test.go deleted file mode 100644 index 11c2c63d08..0000000000 --- a/internal/cli/opsmanager/clusters/shutdown_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestShutdown_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - shutdownOpts := &ShutdownOpts{ - store: mockStore, - confirm: true, - clusterName: "myReplicaSet", - } - - mockStore. - EXPECT(). - GetAutomationConfig(shutdownOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(shutdownOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := shutdownOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestShutdownBuilder(t *testing.T) { - test.CmdValidator( - t, - ShutdownBuilder(), - 0, - []string{flag.ProjectID, flag.Force, flag.ProcessName}, - ) -} diff --git a/internal/cli/opsmanager/clusters/startup.go b/internal/cli/opsmanager/clusters/startup.go deleted file mode 100644 index a70de41a9a..0000000000 --- a/internal/cli/opsmanager/clusters/startup.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - "strings" - - "github.com/AlecAivazis/survey/v2" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type StartupOpts struct { - cli.GlobalOpts - clusterName string - confirm bool - processes []string - store store.AutomationPatcher -} - -func (opts *StartupOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *StartupOpts) Run() error { - if !opts.confirm { - return nil - } - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - if err != nil { - return err - } - - if !search.ClusterExists(current, opts.clusterName) { - return fmt.Errorf("cluster '%s' doesn't exist", opts.clusterName) - } - - err = atmcfg.StartupProcessesByClusterName(current, opts.clusterName, opts.processes) - if err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -func (opts *StartupOpts) Confirm() error { - if opts.confirm { - return nil - } - - startupProcess := opts.clusterName - - if len(opts.processes) > 0 { - startupProcess = fmt.Sprintf("%s (%s)", opts.clusterName, strings.Join(opts.processes, ", ")) - } - - prompt := &survey.Confirm{ - Message: fmt.Sprintf("Are you sure you want to startup: %s", startupProcess), - } - return telemetry.TrackAskOne(prompt, &opts.confirm) -} - -// mongocli cloud-manager cluster(s) startup --process hostname:port,hostname2:port2 --projectId projectId [--force]. -func StartupBuilder() *cobra.Command { - opts := &StartupOpts{} - cmd := &cobra.Command{ - Use: "startup ", - Short: "Start up a cluster for your project.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "clusterNameDesc": "Name of the cluster that you want to start.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.clusterName = args[0] - return opts.Confirm() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.processes, flag.ProcessName, []string{}, usage.ProcessName) - cmd.Flags().BoolVar(&opts.confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/startup_test.go b/internal/cli/opsmanager/clusters/startup_test.go deleted file mode 100644 index 16a669ced4..0000000000 --- a/internal/cli/opsmanager/clusters/startup_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestStartup_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - startupOpts := &StartupOpts{ - store: mockStore, - confirm: true, - clusterName: "myReplicaSet", - } - - mockStore. - EXPECT(). - GetAutomationConfig(startupOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(startupOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := startupOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestStartupBuilder(t *testing.T) { - test.CmdValidator( - t, - StartupBuilder(), - 0, - []string{flag.ProjectID, flag.Force, flag.ProcessName}, - ) -} diff --git a/internal/cli/opsmanager/clusters/unmanage.go b/internal/cli/opsmanager/clusters/unmanage.go deleted file mode 100644 index 1779aa940a..0000000000 --- a/internal/cli/opsmanager/clusters/unmanage.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type UnmanageOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.AutomationPatcher -} - -func (opts *UnmanageOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UnmanageOpts) Run() error { - if !opts.Confirm { - return nil - } - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if !search.ClusterExists(current, opts.Entry) { - return fmt.Errorf("cluster '%s' doesn't exist", opts.Entry) - } - - atmcfg.RemoveByClusterName(current, opts.Entry) - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli cloud-manager cluster(s) unmanage --projectId projectId [--force]. -func UnmanageBuilder() *cobra.Command { - opts := &UnmanageOpts{ - DeleteOpts: cli.NewDeleteOpts("", "Cluster not deleted\""), - } - cmd := &cobra.Command{ - Use: "unmanage ", - Short: "Stop managing a cluster via automation.", - Long: `This commands only removes entries from the automation config but does not actually remove a cluster.`, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "nameDesc": "Name of the cluster for which you want to un-manage.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/unmanage_test.go b/internal/cli/opsmanager/clusters/unmanage_test.go deleted file mode 100644 index c2f9c5cdd7..0000000000 --- a/internal/cli/opsmanager/clusters/unmanage_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestUnmanage_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - deleteOpts := &UnmanageOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "myReplicaSet", - }, - } - - mockStore. - EXPECT(). - GetAutomationConfig(deleteOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(deleteOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/clusters/update.go b/internal/cli/opsmanager/clusters/update.go deleted file mode 100644 index 0b0c427286..0000000000 --- a/internal/cli/opsmanager/clusters/update.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package clusters - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/convert" - "github.com/mongodb/mongodb-atlas-cli/internal/file" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -type UpdateOpts struct { - cli.GlobalOpts - filename string - fs afero.Fs - store store.AutomationPatcher -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - newConfig := new(convert.ClusterConfig) - err := file.Load(opts.fs, opts.filename, newConfig) - if err != nil { - return err - } - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if !search.ClusterExists(current, newConfig.Name) { - return fmt.Errorf("cluster '%s' doesn't exist", newConfig.Name) - } - - if err := newConfig.PatchAutomationConfig(current); err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli cloud-manager cluster(s) update --projectId projectId --file myfile.yaml. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{ - fs: afero.NewOsFs(), - } - cmd := &cobra.Command{ - Use: "update", - Short: "Update a MongoDB cluster.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.filename, flag.File, flag.FileShort, "", "Filename to use to update the cluster") - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.File) - _ = cmd.MarkFlagFilename(flag.File) - - return cmd -} diff --git a/internal/cli/opsmanager/clusters/update_test.go b/internal/cli/opsmanager/clusters/update_test.go deleted file mode 100644 index 7711de2956..0000000000 --- a/internal/cli/opsmanager/clusters/update_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package clusters - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" - "github.com/spf13/afero" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - appFS := afero.NewMemMapFs() - // create test file - fileYML := ` ---- -name: "myReplicaSet" -version: 4.2.2 -featureCompatibilityVersion: 4.0 -processes: - - hostname: host0 - dbPath: /data/myReplicaSet/rs1 - logPath: /data/myReplicaSet/rs1/mongodb.log - priority: 1 - votes: 1 - port: 29010 - - hostname: host1 - dbPath: /data/myReplicaSet/rs2 - logPath: /data/myReplicaSet/rs2/mongodb.log - priority: 1 - votes: 1 - port: 29020 - - hostname: host2 - dbPath: /data/myReplicaSet/rs3 - logPath: /data/myReplicaSet/rs3/mongodb.log - priority: 1 - votes: 1 - port: 29030` - fileName := "test_om_update.yml" - _ = afero.WriteFile(appFS, fileName, []byte(fileYML), 0600) - createOpts := &UpdateOpts{ - store: mockStore, - fs: appFS, - filename: fileName, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/dbusers/create.go b/internal/cli/opsmanager/dbusers/create.go deleted file mode 100644 index 6353480eee..0000000000 --- a/internal/cli/opsmanager/dbusers/create.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package dbusers - -import ( - "context" - "fmt" - - "github.com/AlecAivazis/survey/v2" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/convert" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" - "go.mongodb.org/ops-manager/opsmngr" -) - -const scramSHA1 = "SCRAM-SHA-1" - -type CreateOpts struct { - cli.GlobalOpts - cli.InputOpts - username string - password string - authDB string - roles []string - mechanisms []string - store store.AutomationPatcher -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - dbuser := opts.newDBUser() - if err := atmcfg.ConfigureScramCredentials(dbuser, opts.password); err != nil { - return err - } - - atmcfg.AddUser(current, dbuser) - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -func (opts *CreateOpts) newDBUser() *opsmngr.MongoDBUser { - return &opsmngr.MongoDBUser{ - Database: opts.authDB, - Username: opts.username, - Roles: convert.BuildOMRoles(opts.roles), - AuthenticationRestrictions: []opsmngr.AuthenticationRestriction{}, - Mechanisms: &opts.mechanisms, - } -} - -func (opts *CreateOpts) Prompt() error { - if opts.password != "" { - return nil - } - - if !opts.IsTerminalInput() { - _, err := fmt.Fscanln(opts.InReader, &opts.password) - return err - } - - surveyPrompt := &survey.Password{ - Message: "Password:", - } - return telemetry.TrackAskOne(surveyPrompt, &opts.password) -} - -// mongocli atlas dbuser(s) create --username username --password password --role roleName@dbName [--projectId projectId]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - cmd := &cobra.Command{ - Use: "create", - Short: "Create a database user for your project.", - Example: ` - # Create a user with readWriteAnyDatabase and clusterMonitor access - mongocli om dbuser create --username --role readWriteAnyDatabase,clusterMonitor --mechanisms SCRAM-SHA-256 --projectId `, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.InitInput(cmd.InOrStdin()), - opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, _ []string) error { - if err := opts.Prompt(); err != nil { - return err - } - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.username, flag.Username, flag.UsernameShort, "", usage.DBUsername) - cmd.Flags().StringVarP(&opts.password, flag.Password, flag.PasswordShort, "", usage.DBUserPassword) - cmd.Flags().StringVar(&opts.authDB, flag.AuthDB, convert.AdminDB, usage.AuthDB) - cmd.Flags().StringSliceVar(&opts.roles, flag.Role, []string{}, usage.Roles) - cmd.Flags().StringSliceVar(&opts.mechanisms, flag.Mechanisms, []string{scramSHA1}, usage.Mechanisms) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagRequired(flag.Username) - - return cmd -} diff --git a/internal/cli/opsmanager/dbusers/create_test.go b/internal/cli/opsmanager/dbusers/create_test.go deleted file mode 100644 index 738c08e9a4..0000000000 --- a/internal/cli/opsmanager/dbusers/create_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package dbusers - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - createOpts := &CreateOpts{ - username: "ProjectBar", - password: "US", - roles: []string{"admin@admin"}, - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/dbusers/dbusers.go b/internal/cli/opsmanager/dbusers/dbusers.go deleted file mode 100644 index 02c16a7a68..0000000000 --- a/internal/cli/opsmanager/dbusers/dbusers.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package dbusers - -import ( - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "dbusers", - Aliases: []string{"dbuser", "databaseUsers", "databaseUser"}, - Short: "Manage database users for your project.", - Long: `The dbusers command retrieves, creates and modifies the MongoDB database users in your cluster. -Each user has a set of roles that provide access to the project’s databases. -A user’s roles apply to all the clusters in the project.`, - } - - cmd.AddCommand( - CreateBuilder(), - ListBuilder(), - DeleteBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/dbusers/dbusers_test.go b/internal/cli/opsmanager/dbusers/dbusers_test.go deleted file mode 100644 index 2abdce63bd..0000000000 --- a/internal/cli/opsmanager/dbusers/dbusers_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package dbusers - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/dbusers/delete.go b/internal/cli/opsmanager/dbusers/delete.go deleted file mode 100644 index 00b298be02..0000000000 --- a/internal/cli/opsmanager/dbusers/delete.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package dbusers - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/convert" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - authDB string - store store.AutomationPatcher -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if err := atmcfg.RemoveUser(current, opts.Entry, opts.authDB); err != nil { - return err - } - - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli atlas dbuser(s) delete [--projectId projectId] [--force]. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("DB user '%s' deleted\n", "DB user not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Delete a database user for your project.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "usernameDesc": "Username to delete in the MongoDB database.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.authDB, flag.AuthDB, convert.AdminDB, usage.AuthDB) - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/dbusers/delete_test.go b/internal/cli/opsmanager/dbusers/delete_test.go deleted file mode 100644 index c9964428d3..0000000000 --- a/internal/cli/opsmanager/dbusers/delete_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package dbusers - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfigWithMongoDBUsers() - - createOpts := &DeleteOpts{ - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "test", - }, - authDB: "test", - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/dbusers/list.go b/internal/cli/opsmanager/dbusers/list.go deleted file mode 100644 index bc0343f0ef..0000000000 --- a/internal/cli/opsmanager/dbusers/list.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package dbusers - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const listTemplate = `USERNAME DATABASE{{range valueOrEmptySlice .}} -{{.Username}} {{.Database}}{{end}} -` - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.AutomationGetter -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *ListOpts) Run() error { - r, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - return opts.Print(r.Auth.UsersWanted) -} - -// mongocli om|cm dbuser(s) list [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Short: "List Atlas database users for your project.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/dbusers/list_test.go b/internal/cli/opsmanager/dbusers/list_test.go deleted file mode 100644 index cfea63b4ba..0000000000 --- a/internal/cli/opsmanager/dbusers/list_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package dbusers - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - createOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/diagnosearchive/diagnose_archive.go b/internal/cli/opsmanager/diagnosearchive/diagnose_archive.go deleted file mode 100644 index 311a5a7743..0000000000 --- a/internal/cli/opsmanager/diagnosearchive/diagnose_archive.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package diagnosearchive - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "diagnoseArchives" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage diagnose archives.", - } - - cmd.AddCommand(DownloadBuilder()) - - return cmd -} diff --git a/internal/cli/opsmanager/diagnosearchive/diagnose_archive_download.go b/internal/cli/opsmanager/diagnosearchive/diagnose_archive_download.go deleted file mode 100644 index fd39c992f8..0000000000 --- a/internal/cli/opsmanager/diagnosearchive/diagnose_archive_download.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package diagnosearchive - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type DownloadOpts struct { - cli.GlobalOpts - cli.DownloaderOpts - limit int64 - minutes int64 - store store.ArchivesDownloader -} - -func (opts *DownloadOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DownloadOpts) Run() error { - out, err := opts.NewWriteCloser() - if err != nil { - return err - } - - if err := opts.store.DownloadArchive(opts.ConfigProjectID(), opts.newDiagnosticsListOpts(), out); err != nil { - _ = opts.OnError(out) - return err - } - - return out.Close() -} - -func (opts *DownloadOpts) newDiagnosticsListOpts() *opsmngr.DiagnosticsListOpts { - return &opsmngr.DiagnosticsListOpts{ - Limit: opts.limit, - Minutes: opts.minutes, - } -} - -// mongocli om diagnose-archive download [--out out] [--projectId projectId]. -func DownloadBuilder() *cobra.Command { - opts := &DownloadOpts{} - opts.Fs = afero.NewOsFs() - cmd := &cobra.Command{ - Use: "download", - Aliases: []string{"get"}, - Short: "Download diagnose archives.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.Out, flag.Out, "diagnose-archive.tar.gz", usage.DiagnoseOut) - cmd.Flags().Int64Var(&opts.limit, flag.Limit, 0, usage.ArchiveLimit) - cmd.Flags().Int64Var(&opts.minutes, flag.Minutes, 0, usage.ArchiveMinutes) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagFilename(flag.Out) - - return cmd -} diff --git a/internal/cli/opsmanager/diagnosearchive/diagnose_archive_download_test.go b/internal/cli/opsmanager/diagnosearchive/diagnose_archive_download_test.go deleted file mode 100644 index 5cba6a8d94..0000000000 --- a/internal/cli/opsmanager/diagnosearchive/diagnose_archive_download_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package diagnosearchive - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/spf13/afero" -) - -func TestDiagnoseArchiveDownloadOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockArchivesDownloader(ctrl) - - opts := &DownloadOpts{ - store: mockStore, - } - opts.Out = "fake_diagnostic.tar.gz" - opts.Fs = afero.NewMemMapFs() - - mockStore. - EXPECT(). - DownloadArchive(opts.ProjectID, opts.newDiagnosticsListOpts(), gomock.Any()). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/diagnosearchive/diagnose_archive_test.go b/internal/cli/opsmanager/diagnosearchive/diagnose_archive_test.go deleted file mode 100644 index 03c2b8e43e..0000000000 --- a/internal/cli/opsmanager/diagnosearchive/diagnose_archive_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package diagnosearchive - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/featurepolicies/feature_policies.go b/internal/cli/opsmanager/featurepolicies/feature_policies.go deleted file mode 100644 index 05315234b6..0000000000 --- a/internal/cli/opsmanager/featurepolicies/feature_policies.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package featurepolicies - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "featurePolicies" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage feature control policies.", - } - - cmd.AddCommand( - ListBuilder(), - UpdateBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/featurepolicies/feature_policies_test.go b/internal/cli/opsmanager/featurepolicies/feature_policies_test.go deleted file mode 100644 index 0cad432a80..0000000000 --- a/internal/cli/opsmanager/featurepolicies/feature_policies_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package featurepolicies - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/featurepolicies/list.go b/internal/cli/opsmanager/featurepolicies/list.go deleted file mode 100644 index 5f5c4b2d39..0000000000 --- a/internal/cli/opsmanager/featurepolicies/list.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package featurepolicies - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.FeatureControlPoliciesLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `NAME SYSTEM ID POLICY -{{if .ExternalManagementSystem}}{{- $name := .ExternalManagementSystem.Name }}{{- $systemID := .ExternalManagementSystem.SystemID }}{{- range valueOrEmptySlice .Policies}} -{{ $name }} {{ $systemID }} {{.Policy}}{{end}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.FeatureControlPolicies(opts.ConfigProjectID(), opts.NewListOptions()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om featurePolicy(ies) list [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "List feature control policies for your project.", - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/featurepolicies/list_test.go b/internal/cli/opsmanager/featurepolicies/list_test.go deleted file mode 100644 index 71b3c83de7..0000000000 --- a/internal/cli/opsmanager/featurepolicies/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package featurepolicies - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockFeatureControlPoliciesLister(ctrl) - - expected := &opsmngr.FeaturePolicy{} - - listOpts := ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - FeatureControlPolicies(listOpts.ProjectID, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/featurepolicies/update.go b/internal/cli/opsmanager/featurepolicies/update.go deleted file mode 100644 index 1ae9d7cb8b..0000000000 --- a/internal/cli/opsmanager/featurepolicies/update.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package featurepolicies - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/file" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -var updateTemplate = "Feature control policies updated.\n" - -type UpdateOpts struct { - cli.OutputOpts - cli.GlobalOpts - store store.FeatureControlPoliciesUpdater - name string - systemID string - policy []string - filename string - fs afero.Fs -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *UpdateOpts) Run() error { - p, err := opts.newFeatureControl() - if err != nil { - return err - } - r, err := opts.store.UpdateFeatureControlPolicy(opts.ConfigProjectID(), p) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *UpdateOpts) newFeatureControl() (*opsmngr.FeaturePolicy, error) { - policy := new(opsmngr.FeaturePolicy) - if opts.filename != "" { - if err := file.Load(opts.fs, opts.filename, policy); err != nil { - return nil, err - } - } else { - policy.ExternalManagementSystem = &opsmngr.ExternalManagementSystem{ - Name: opts.name, - SystemID: opts.systemID, - } - policy.Policies = opts.newPolicies() - } - return policy, nil -} - -func (opts *UpdateOpts) newPolicies() []*opsmngr.Policy { - policies := make([]*opsmngr.Policy, len(opts.policy)) - for i := range opts.policy { - policy := &opsmngr.Policy{ - Policy: opts.policy[i], - } - policies[i] = policy - } - return policies -} - -// UpdateBuilder mongocli ops-manager featurePolicy(ies) update --name name --policy policy --systemId systemId [--projectId projectId]. -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{ - fs: afero.NewOsFs(), - } - cmd := &cobra.Command{ - Use: "update", - Short: "Update feature control policies for your project.", - Long: `Feature Control Policies allow you to enable or disable certain MongoDB features based on your site-specific needs.`, - Example: ` # Disable user management for a project: - mongocli ops-manager featurePolicies update --projectId --name Operator --policy DISABLE_USER_MANAGEMENT - - # Update policies from a JSON configuration file: - mongocli atlas featurePolicies update --projectId --file -`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - if opts.filename == "" { - _ = cmd.MarkFlagRequired(flag.Name) - } - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.policy, flag.Policy, []string{}, usage.Policy+usage.UpdateWarning) - cmd.Flags().StringVar(&opts.name, flag.Name, "", usage.ExternalSystemName) - cmd.Flags().StringVar(&opts.systemID, flag.SystemID, "", usage.SystemID) - cmd.Flags().StringVarP(&opts.filename, flag.File, flag.FileShort, "", usage.PoliciesFilename) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - _ = cmd.MarkFlagFilename(flag.File) - - return cmd -} diff --git a/internal/cli/opsmanager/featurepolicies/update_test.go b/internal/cli/opsmanager/featurepolicies/update_test.go deleted file mode 100644 index 6bc34078d8..0000000000 --- a/internal/cli/opsmanager/featurepolicies/update_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package featurepolicies - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/spf13/afero" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockFeatureControlPoliciesUpdater(ctrl) - - expected := &opsmngr.FeaturePolicy{} - - t.Run("flags", func(t *testing.T) { - opts := &UpdateOpts{ - store: mockStore, - } - p, _ := opts.newFeatureControl() - mockStore. - EXPECT().UpdateFeatureControlPolicy(opts.ConfigProjectID(), p). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - t.Run("file run", func(t *testing.T) { - appFS := afero.NewMemMapFs() - // create test file - fileYML := `{ - "created":"2022-03-15T15:03:32Z", - "externalManagementSystem": { - "name": "mongodb-enterprise-operator", - "version": "" - }, - "policies": [ - { - "policy": "DISABLE_SET_MONGOD_VERSION" - }, - { - "disabledParams": [], - "policy": "EXTERNALLY_MANAGED_LOCK" - }, - { - "policy": "DISABLE_AUTHENTICATION_MECHANISMS", - "disabledParams": [] - }, - { - "policy": "DISABLE_SET_MONGOD_CONFIG", - "disabledParams": [ - "syslog.verbosity", - "net.tls.mode", - "syslog.timeStampFormat", - "net.tls.disabledProtocols", - "setParameter.suppressNoTLSPeerCertificateWarning" - ] - } - ] -}` - fileName := "atlas_cluster_create_test.json" - _ = afero.WriteFile(appFS, fileName, []byte(fileYML), 0600) - - opts := &UpdateOpts{ - filename: fileName, - fs: appFS, - store: mockStore, - } - - p, _ := opts.newFeatureControl() - mockStore. - EXPECT().UpdateFeatureControlPolicy(opts.ConfigProjectID(), p). - Return(expected, nil). - Times(1) - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Output, flag.Name, flag.SystemID, flag.Policy}, - ) -} diff --git a/internal/cli/opsmanager/livemigrations/link/create.go b/internal/cli/opsmanager/livemigrations/link/create.go deleted file mode 100644 index 5e824fa369..0000000000 --- a/internal/cli/opsmanager/livemigrations/link/create.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package link - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -var createTemplate = "Organization link successfully created.\n" - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.OrganizationsConnector - linkToken string -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CreateOpts) Run() error { - createRequest := opts.newCreateLinkRequest() - - r, err := opts.store.ConnectOrganizations(opts.ConfigOrgID(), createRequest) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *CreateOpts) newCreateLinkRequest() *opsmngr.LinkToken { - return &opsmngr.LinkToken{ - LinkToken: opts.linkToken, - } -} - -// mongocli opsmanager|cloud-manager liveMigrations|lm link create --linkToken linkToken [--orgId orgId]. -func CreateBuilder() *cobra.Command { - opts := &CreateOpts{} - cmd := &cobra.Command{ - Use: "create", - Short: "Create one new organization link.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVar(&opts.linkToken, flag.LinkToken, "", usage.LinkToken) - - return cmd -} diff --git a/internal/cli/opsmanager/livemigrations/link/create_test.go b/internal/cli/opsmanager/livemigrations/link/create_test.go deleted file mode 100644 index 3eb2c42689..0000000000 --- a/internal/cli/opsmanager/livemigrations/link/create_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package link - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestLinkCreateOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationsConnector(ctrl) - - createOpts := &CreateOpts{ - GlobalOpts: cli.GlobalOpts{OrgID: "1"}, - linkToken: "test", - store: mockStore, - } - - mockStore. - EXPECT().ConnectOrganizations(createOpts.OrgID, &opsmngr.LinkToken{LinkToken: "test"}).Return(&opsmngr.ConnectionStatus{}, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{ - flag.LinkToken, - flag.OrgID, - }, - ) -} diff --git a/internal/cli/opsmanager/livemigrations/link/delete.go b/internal/cli/opsmanager/livemigrations/link/delete.go deleted file mode 100644 index e196b47224..0000000000 --- a/internal/cli/opsmanager/livemigrations/link/delete.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package link - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.LinkTokenDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteLinkToken) -} - -// mongocli ops-manager|cloud-manager liveMigrations|lm link delete|rm [--orgId orgId] [--force]. - -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Link-token %s successfully deleted\n", "Link-token not deleted"), - } - cmd := &cobra.Command{ - Use: "delete", - Aliases: []string{"rm"}, - Short: "Delete one link-token.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.Prompt, - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - opts.Entry = opts.ConfigOrgID() - return opts.Run() - }, - } - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - return cmd -} diff --git a/internal/cli/opsmanager/livemigrations/link/delete_test.go b/internal/cli/opsmanager/livemigrations/link/delete_test.go deleted file mode 100644 index acfb6dfff0..0000000000 --- a/internal/cli/opsmanager/livemigrations/link/delete_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package link - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestLinkTokenDeleteOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockLinkTokenDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - GlobalOpts: cli.GlobalOpts{OrgID: "1"}, - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "1", - }, - } - - mockStore. - EXPECT().DeleteLinkToken(deleteOpts.OrgID). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.OrgID, flag.Force}, - ) -} diff --git a/internal/cli/opsmanager/livemigrations/link/describe.go b/internal/cli/opsmanager/livemigrations/link/describe.go deleted file mode 100644 index 834d9d37e4..0000000000 --- a/internal/cli/opsmanager/livemigrations/link/describe.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package link - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.OrganizationsDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var describeTemplate = "Organization Link status: '{{.Status}}'\n" - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.OrganizationConnectionStatus(opts.ConfigOrgID()) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager|cloud-manager liveMigration|lm link describe|get [--orgId orgId]. -func DescribeBuilder() *cobra.Command { - opts := new(DescribeOpts) - cmd := &cobra.Command{ - Use: "describe", - Aliases: []string{"get"}, - Short: "Return the status of the connection between the specified source organization and the target MongoDB Atlas organization.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/livemigrations/link/describe_test.go b/internal/cli/opsmanager/livemigrations/link/describe_test.go deleted file mode 100644 index 6c63496397..0000000000 --- a/internal/cli/opsmanager/livemigrations/link/describe_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package link - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestLinkDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationsDescriber(ctrl) - - describeOpts := &DescribeOpts{ - GlobalOpts: cli.GlobalOpts{OrgID: "1"}, - store: mockStore, - } - - mockStore. - EXPECT().OrganizationConnectionStatus(describeOpts.OrgID).Return(&opsmngr.ConnectionStatus{}, nil). - Times(1) - - if err := describeOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{ - flag.OrgID, - }, - ) -} diff --git a/internal/cli/opsmanager/livemigrations/link/link.go b/internal/cli/opsmanager/livemigrations/link/link.go deleted file mode 100644 index b173b3110b..0000000000 --- a/internal/cli/opsmanager/livemigrations/link/link.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package link - -import ( - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "link", - Short: "Manage the link-token for your organization.", - } - - cmd.AddCommand( - CreateBuilder(), - DeleteBuilder(), - DescribeBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/livemigrations/link/link_test.go b/internal/cli/opsmanager/livemigrations/link/link_test.go deleted file mode 100644 index bbd9fbf785..0000000000 --- a/internal/cli/opsmanager/livemigrations/link/link_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package link - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/livemigrations/live_migrations.go b/internal/cli/opsmanager/livemigrations/live_migrations.go deleted file mode 100644 index 46dff58b50..0000000000 --- a/internal/cli/opsmanager/livemigrations/live_migrations.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package livemigrations - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/livemigrations/link" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "liveMigrations" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use, "lm"), - Short: "Manage a Live Migration to Atlas for your organization.", - } - - cmd.AddCommand( - link.Builder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/livemigrations/live_migrations_test.go b/internal/cli/opsmanager/livemigrations/live_migrations_test.go deleted file mode 100644 index 69f0709394..0000000000 --- a/internal/cli/opsmanager/livemigrations/live_migrations_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package livemigrations - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/logs/decrypt.go b/internal/cli/opsmanager/logs/decrypt.go deleted file mode 100644 index 2b670fc4f6..0000000000 --- a/internal/cli/opsmanager/logs/decrypt.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2022 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/decryption" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -type DecryptOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.DownloaderOpts - inFileName string - kmipServerCAFileName string - kmipClientCertificateFileName string - kmipClientCertificatePassword string - kmipUsername string - kmipPassword string - localKeyFileName string -} - -func (opts *DecryptOpts) newDecryption() *decryption.Decryption { - return decryption.NewDecryption( - decryption.WithLocalOpts(opts.localKeyFileName), - decryption.WithKMIPOpts(&decryption.KeyProviderKMIPOpts{ - ServerCAFileName: opts.kmipServerCAFileName, - ClientCertificateFileName: opts.kmipClientCertificateFileName, - ClientCertificatePassword: opts.kmipClientCertificatePassword, - Username: opts.kmipUsername, - Password: opts.kmipPassword, - }), - ) -} - -func (opts *DecryptOpts) initDefaultOut() error { - if opts.Out == "" { - opts.Out = cli.StdOutMode // sets to "-" - } - return nil -} - -func (opts *DecryptOpts) Run() error { - outWriter, err := opts.NewWriteCloser() - if err != nil { - return err - } - defer outWriter.Close() - - inReader, err := opts.Fs.Open(opts.inFileName) - if err != nil { - return err - } - defer inReader.Close() - - d := opts.newDecryption() - if err := d.Decrypt(inReader, outWriter); err != nil && !opts.ShouldDownloadToStdout() { - _ = opts.OnError(outWriter) - return err - } - - if !opts.ShouldDownloadToStdout() { - fmt.Printf("Decrypt of %s to %s completed.\n", opts.inFileName, opts.Out) - } - - return nil -} - -// mongocli om logs decrypt --localKey --kmipServerCAFile –-kmipClientCertificateFile --file --out . -func DecryptBuilder() *cobra.Command { - opts := &DecryptOpts{} - opts.Fs = afero.NewOsFs() - cmd := &cobra.Command{ - Use: "decrypt", - Short: "Decrypts an audit log file with the provided local key file or with a server that supports KMIP.", - Example: ` - # For audit logs in BSON format: - mongocli ops-manager logs decrypt --localKeyFile /path/to/keyFile --file /path/to/logFile.bson --out /path/to/file.json - # For audit logs in JSON format: - mongocli ops-manager logs decrypt --localKeyFile /path/to/keyFile --file /path/to/logFile.json --out /path/to/file.json`, - PreRunE: func(_ *cobra.Command, _ []string) error { - return opts.PreRunE(opts.initDefaultOut) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.inFileName, flag.File, flag.FileShort, "", usage.EncryptedLogFile) - cmd.Flags().StringVarP(&opts.Out, flag.Out, flag.OutputShort, "", usage.OutputLogFile) - - cmd.Flags().StringVarP(&opts.localKeyFileName, flag.LocalKeyFile, "", "", usage.LocalKeyFile) - cmd.Flags().StringVarP(&opts.kmipServerCAFileName, flag.KMIPServerCAFile, "", "", usage.KMIPServerCAFile) - cmd.Flags().StringVarP(&opts.kmipClientCertificateFileName, flag.KMIPClientCertificateFile, "", "", usage.KMIPClientCertificateFile) - cmd.Flags().StringVar(&opts.kmipClientCertificatePassword, flag.KMIPClientCertificatePassword, "", usage.KMIPClientCertificatePassword) - cmd.Flags().StringVarP(&opts.kmipUsername, flag.KMIPUsername, "", "", usage.KMIPUsername) - cmd.Flags().StringVarP(&opts.kmipPassword, flag.KMIPPassword, "", "", usage.KMIPPassword) - - _ = cmd.MarkFlagRequired(flag.File) - _ = cmd.MarkFlagFilename(flag.File) - _ = cmd.MarkFlagFilename(flag.Out) - _ = cmd.MarkFlagFilename(flag.LocalKeyFile) - _ = cmd.MarkFlagFilename(flag.KMIPServerCAFile) - _ = cmd.MarkFlagFilename(flag.KMIPClientCertificateFile) - - return cmd -} diff --git a/internal/cli/opsmanager/logs/decrypt_test.go b/internal/cli/opsmanager/logs/decrypt_test.go deleted file mode 100644 index 5627663273..0000000000 --- a/internal/cli/opsmanager/logs/decrypt_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2022 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package logs - -import ( - "encoding/base64" - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/spf13/afero" -) - -func TestDecryptBuilder(t *testing.T) { - test.CmdValidator( - t, - DecryptBuilder(), - 0, - []string{ - flag.File, - flag.Out, - flag.LocalKeyFile, - flag.KMIPClientCertificateFile, - flag.KMIPServerCAFile, - flag.KMIPUsername, - flag.KMIPPassword, - }, - ) -} - -func TestDecrypt_Run(t *testing.T) { - fileKey := []byte("LxbM6ik6lgJjKEkugTdkRUoHCeyArNxg2xx7kGHl/io=") - fileJSON := []byte(`{"ts":{"$date":{"$numberLong":"1644232049921"}},"version":"0.0","compressionMode":"zstd","keyStoreIdentifier":{"provider":"local","filename":"localKey"},"encryptedKey":{"$binary":{"base64":"+yjPCaKKE1M8fZmPGzGHkyfHYxaw34okpavsHzpd8iPVx2+JjOhXwXw5E2FdI5Rcb5JgmcPUFRPISh/7Si1R/g==","subType":"0"}},"MAC":"qE9fUsGK0EuRrrCRAQAAAAAAAAAAAAAA","auditRecordType":"header"} -{"ts":{"$date":{"$numberLong":"1644232049922"}},"log":"1Lu4o8XVMM/Rg7GKAQAAAAEAAAAAAAAA/8tXQ36mEd90OaAOzCOSti7N5a2jr0B9ek48/uvyteG/zUJHyM16Hs3wMEhDqTQGBwGhWSHEqXh0/5Jbz6tXsYHhDTMr1BOsn1zaavZScx/CkO5+Hd8Vx+zeFPREtQTe1y+JngXSIroezeyV0/zF4YC4vpug+OZtrEQLNEgwT2bjaqUyaKDbmzCNetd2Ff/eFfMFzinbzKVgXAC7T4YmDuowqXommEXLIBiYh2u4VagwJKZRw5OGZjnvqwyVpSPgGqLxGKUoFigh3NgC6EuGi17VIs5BLRZOIw7+OfbPgQQiKzjCxCk="}`) - fileBSON, _ := base64.StdEncoding.DecodeString(`GQEAAAl0cwAoM/iHfwEAAAJ2ZXJzaW9uAAQAAAAwLjAAAmNvbXByZXNzaW9uTW9kZQAFAAAAenN0ZAADa2V5U3RvcmVJZGVudGlmaWVyADAAAAACcHJvdmlkZXIABgAAAGxvY2FsAAJmaWxlbmFtZQAJAAAAbG9jYWxLZXkAAAVlbmNyeXB0ZWRLZXkAQAAAAAD0maD5Lru6ePgZ8t+Xg/GZJ2jzt7V1u1DRQyt2J3u3HtHjZeG+0megvO1JSFhCFbMid7+w1e88hWX3gz1WdeL6Ak1BQwAhAAAAT0cvVndNbHBQVTlDaERtSEFRQUFBQUFBQUFBQUFBQUEAAmF1ZGl0UmVjb3JkVHlwZQAHAAAAaGVhZGVyAABzAQAACXRzACkz+Id/AQAAAmxvZwBZAQAAMFFqd3VmWUl5ZHZOdURYVEFRQUFBQUVBQUFBQUFBQUFVWmFNa0I3eVlsbHlIRTh6RVM0QStCSzVIT0RraFdqVEJUOVlxL3Z3RzNUdjhXNGtFZ0VENDBhRE1wOExMUWJXek8vZ1RDK016R1NuSEZxZXI2RGdXOVQxYTdnNEdxTGxaQm1QOVdKaFl4TSsyeURVUlZzS3VvZ2hLbFdsb3NYVkdnZDFHUEQ3UGV4Ums4Z3l0alZlRkZ4WVRvbFBPd2JMZWVrM2ZlYU1UMXZUaGZsZmtBZWZjK1ZoVVNmeGtjdFg4Tkt2dFkxQ0xManJPeXpYRUcwT09CYWluYlhpeWJDQXlzekRDOVdkTDBDZzh3eDVrbjRMWFFIc2hGakNXQThHTUlXUThNTlU3ZG1oeDFtY0VvS0dycGRWZVAveVFOT3hTamtLRHJDMm8xUDB3WGlnT1o4elJ6L1cAAA==`) - - testCases := []struct { - input []byte - }{ - {input: fileBSON}, - {input: fileJSON}, - } - - for _, testCase := range testCases { - listOpts := &DecryptOpts{ - inFileName: "log", - localKeyFileName: "localKey", - } - listOpts.Out = "decryptedAuditLog" - listOpts.Fs = afero.NewMemMapFs() - _ = afero.WriteFile(listOpts.Fs, "log", testCase.input, 0600) - _ = afero.WriteFile(listOpts.Fs, "localKey", fileKey, 0600) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - } -} diff --git a/internal/cli/opsmanager/logs/jobs.go b/internal/cli/opsmanager/logs/jobs.go deleted file mode 100644 index 714a5598a8..0000000000 --- a/internal/cli/opsmanager/logs/jobs.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "github.com/spf13/cobra" -) - -func JobsBuilder() *cobra.Command { - cmd := &cobra.Command{ - Use: "jobs", - Aliases: []string{"job"}, - Short: "Manage log collection jobs for your project.", - } - - cmd.AddCommand( - JobsCollectOptsBuilder(), - JobsListOptsBuilder(), - JobsDownloadOptsBuilder(), - JobsDeleteOptsBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/logs/jobs_collect.go b/internal/cli/opsmanager/logs/jobs_collect.go deleted file mode 100644 index 30063b16ab..0000000000 --- a/internal/cli/opsmanager/logs/jobs_collect.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "context" - "fmt" - "strings" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type JobsCollectOpts struct { - cli.GlobalOpts - cli.OutputOpts - resourceType string - resourceName string - logTypes []string - sizeRequestedPerFileBytes int64 - redacted bool - store store.LogCollector -} - -func (opts *JobsCollectOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var collectTemplate = "Log collection job '{{.ID}}' started successfully.\n" - -func (opts *JobsCollectOpts) Run() error { - r, err := opts.store.Collect(opts.ConfigProjectID(), opts.newLog()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *JobsCollectOpts) newLog() *opsmngr.LogCollectionJob { - return &opsmngr.LogCollectionJob{ - ResourceType: opts.resourceType, - ResourceName: opts.resourceName, - Redacted: &opts.redacted, - SizeRequestedPerFileBytes: opts.sizeRequestedPerFileBytes, - LogTypes: opts.logTypes, - } -} - -// mongocli om logs jobs collect --sizeRequestedPerFileBytes size --type type --redacted redacted [--projectId projectId]. -func JobsCollectOptsBuilder() *cobra.Command { - const argsN = 2 - opts := &JobsCollectOpts{} - cmd := &cobra.Command{ - Use: "collect ", - Short: "Start a job to collect logs for your project.", - Args: func(cmd *cobra.Command, args []string) error { - if len(args) != argsN { - return fmt.Errorf("accepts %d arg(s), received %d", argsN, len(args)) - } - - args[0] = strings.ToLower(args[0]) - if !search.StringInSlice(cmd.ValidArgs, args[0]) { - return fmt.Errorf("invalid resource type '%s', expected one of %v", args[0], cmd.ValidArgs) - } - return nil - }, - ValidArgs: []string{"cluster", "process", "replicaset"}, - Annotations: map[string]string{ - "resourceTypeDesc": "Type of resource to collect logs from.", - "resourceNameDesc": "Name of the resource to collect logs from.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), collectTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.resourceType = args[0] - opts.resourceName = args[1] - return opts.Run() - }, - } - - cmd.Flags().StringSliceVar(&opts.logTypes, flag.TypeFlag, []string{}, usage.LogTypes) - cmd.Flags().Int64Var(&opts.sizeRequestedPerFileBytes, flag.SizeRequestedPerFileBytes, 0, usage.SizeRequestedPerFileBytes) - cmd.Flags().BoolVar(&opts.redacted, flag.Redacted, false, usage.LogRedacted) - - _ = cmd.MarkFlagRequired(flag.SizeRequestedPerFileBytes) - _ = cmd.MarkFlagRequired(flag.TypeFlag) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/logs/jobs_collect_test.go b/internal/cli/opsmanager/logs/jobs_collect_test.go deleted file mode 100644 index 23795b411d..0000000000 --- a/internal/cli/opsmanager/logs/jobs_collect_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package logs - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestLogsCollectOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockLogCollector(ctrl) - - expected := &opsmngr.LogCollectionJob{ID: "1"} - - listOpts := &JobsCollectOpts{ - redacted: false, - sizeRequestedPerFileBytes: 64, - resourceType: "CLUSTER", - resourceName: "", - logTypes: []string{"AUTOMATION_AGENT"}, - store: mockStore, - } - - mockStore. - EXPECT().Collect(listOpts.ProjectID, listOpts.newLog()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/logs/jobs_delete.go b/internal/cli/opsmanager/logs/jobs_delete.go deleted file mode 100644 index 63fea029a8..0000000000 --- a/internal/cli/opsmanager/logs/jobs_delete.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type JobsDeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.LogJobDeleter -} - -func (opts *JobsDeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *JobsDeleteOpts) Run() error { - return opts.store.DeleteCollectionJob(opts.ConfigProjectID(), opts.Entry) -} - -// mongocli om logs jobs delete [--projectId projectId] [--force]. -func JobsDeleteOptsBuilder() *cobra.Command { - opts := &JobsDeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Log collection Entry '%s' deleted\n", "Log collection Entry not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Args: require.ExactArgs(1), - Short: "Delete a log collection job from your project.", - Annotations: map[string]string{ - "IDDesc": "Log job identifier.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/logs/jobs_delete_test.go b/internal/cli/opsmanager/logs/jobs_delete_test.go deleted file mode 100644 index af47c9404a..0000000000 --- a/internal/cli/opsmanager/logs/jobs_delete_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package logs - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" -) - -func TestJobsDeleteOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockLogJobDeleter(ctrl) - - deleteOpts := &JobsDeleteOpts{ - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "test", - }, - store: mockStore, - } - - mockStore. - EXPECT(). - DeleteCollectionJob(deleteOpts.ProjectID, deleteOpts.Entry). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/logs/jobs_download.go b/internal/cli/opsmanager/logs/jobs_download.go deleted file mode 100644 index c7cdef86c7..0000000000 --- a/internal/cli/opsmanager/logs/jobs_download.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -type JobsDownloadOpts struct { - cli.GlobalOpts - cli.DownloaderOpts - id string - store store.LogJobsDownloader -} - -func (opts *JobsDownloadOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *JobsDownloadOpts) Run() error { - out, err := opts.NewWriteCloser() - if err != nil { - return err - } - - if err := opts.store.DownloadLogJob(opts.ConfigProjectID(), opts.id, out); err != nil { - _ = opts.OnError(out) - return err - } - - return out.Close() -} - -// mongocli om logs jobs download [--out out] [--projectId projectId]. -func JobsDownloadOptsBuilder() *cobra.Command { - opts := &JobsDownloadOpts{} - opts.Fs = afero.NewOsFs() - cmd := &cobra.Command{ - Use: "download ", - Short: "Download logs generated by a log collection job.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Log job identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.Out, flag.Out, "", usage.LogOut) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().BoolVar(&opts.Force, flag.Force, false, usage.ForceFile) - - _ = cmd.MarkFlagRequired(flag.Out) - _ = cmd.MarkFlagFilename(flag.Out) - - return cmd -} diff --git a/internal/cli/opsmanager/logs/jobs_download_test.go b/internal/cli/opsmanager/logs/jobs_download_test.go deleted file mode 100644 index 7425edd6a9..0000000000 --- a/internal/cli/opsmanager/logs/jobs_download_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package logs - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/spf13/afero" -) - -func TestDownloadOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockLogJobsDownloader(ctrl) - - opts := &JobsDownloadOpts{ - id: "1", - store: mockStore, - } - opts.Out = "fake_log.tar.gz" - opts.Fs = afero.NewMemMapFs() - - mockStore. - EXPECT(). - DownloadLogJob(opts.ProjectID, opts.id, gomock.Any()). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestJobsDownloadOptsBuilder(t *testing.T) { - test.CmdValidator( - t, - JobsDownloadOptsBuilder(), - 0, - []string{flag.Out, flag.ProjectID, flag.Force}, - ) -} diff --git a/internal/cli/opsmanager/logs/jobs_list.go b/internal/cli/opsmanager/logs/jobs_list.go deleted file mode 100644 index 0d59f6bde0..0000000000 --- a/internal/cli/opsmanager/logs/jobs_list.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type JobsListOpts struct { - cli.GlobalOpts - cli.OutputOpts - verbose bool - store store.LogJobLister -} - -func (opts *JobsListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `ID CREATED AT EXPIRES AT STATUS URL REDACTED{{range valueOrEmptySlice .Results}} -{{.ID}} {{.CreationDate}} {{.ExpirationDate}} {{.Status}} {{.DownloadURL}} {{.Redacted}}{{end}} -` - -func (opts *JobsListOpts) Run() error { - r, err := opts.store.LogCollectionJobs(opts.ConfigProjectID(), opts.newLogListOptions()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *JobsListOpts) newLogListOptions() *opsmngr.LogListOptions { - return &opsmngr.LogListOptions{Verbose: opts.verbose} -} - -// mongocli om logs jobs list --verbose verbose [--projectId projectId]. -func JobsListOptsBuilder() *cobra.Command { - opts := &JobsListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "List log collection jobs for your project.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.verbose, flag.Verbose, false, usage.Verbose) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/logs/jobs_list_test.go b/internal/cli/opsmanager/logs/jobs_list_test.go deleted file mode 100644 index 03cc5425cf..0000000000 --- a/internal/cli/opsmanager/logs/jobs_list_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package logs - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestListOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockLogJobLister(ctrl) - - expected := &opsmngr.LogCollectionJobs{} - - listOpts := &JobsListOpts{ - store: mockStore, - verbose: true, - } - - mockStore. - EXPECT().LogCollectionJobs(listOpts.ProjectID, listOpts.newLogListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/logs/jobs_test.go b/internal/cli/opsmanager/logs/jobs_test.go deleted file mode 100644 index 552c18d5f1..0000000000 --- a/internal/cli/opsmanager/logs/jobs_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package logs - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestJobsBuilder(t *testing.T) { - test.CmdValidator( - t, - JobsBuilder(), - 4, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/logs/logs.go b/internal/cli/opsmanager/logs/logs.go deleted file mode 100644 index 6d1fa18391..0000000000 --- a/internal/cli/opsmanager/logs/logs.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package logs - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli/decryption" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "logs", - Aliases: []string{"log"}, - Short: "Manage log collection jobs for your project.", - } - - cmd.AddCommand( - JobsBuilder(), - decryption.KeyProvidersBuilder(), - DecryptBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/logs/logs_test.go b/internal/cli/opsmanager/logs/logs_test.go deleted file mode 100644 index b6ed525ac0..0000000000 --- a/internal/cli/opsmanager/logs/logs_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package logs - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/maintenance/create.go b/internal/cli/opsmanager/maintenance/create.go deleted file mode 100644 index 874a898102..0000000000 --- a/internal/cli/opsmanager/maintenance/create.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package maintenance - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - alertType []string - startDate string - endDate string - description string - store store.OpsManagerMaintenanceWindowCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var createTemplate = "Maintenance window '{{.ID}}' successfully created.\n" - -func (opts *CreateOpts) Run() error { - r, err := opts.store.CreateOpsManagerMaintenanceWindow(opts.ConfigProjectID(), opts.newMaintenanceWindow()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *CreateOpts) newMaintenanceWindow() *opsmngr.MaintenanceWindow { - return &opsmngr.MaintenanceWindow{ - StartDate: opts.startDate, - EndDate: opts.endDate, - AlertTypeNames: opts.alertType, - Description: opts.description, - } -} - -// mongocli ops-manager maintenanceWindows create --startDate startDate --endDate endDate --alertType alertType --desc desc [--projectId projectId]. -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - cmd := &cobra.Command{ - Use: "create", - Short: "Create a maintenance window.", - Args: cobra.OnlyValidArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.startDate, flag.StartDate, "", usage.StartDate) - cmd.Flags().StringVar(&opts.endDate, flag.EndDate, "", usage.EndDate) - cmd.Flags().StringSliceVar(&opts.alertType, flag.AlertType, []string{}, usage.AlertType) - cmd.Flags().StringVar(&opts.description, flag.Description, "", usage.MaintenanceDescription) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.StartDate) - _ = cmd.MarkFlagRequired(flag.EndDate) - _ = cmd.MarkFlagRequired(flag.AlertType) - - return cmd -} diff --git a/internal/cli/opsmanager/maintenance/create_test.go b/internal/cli/opsmanager/maintenance/create_test.go deleted file mode 100644 index 89b8edb903..0000000000 --- a/internal/cli/opsmanager/maintenance/create_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package maintenance - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOpsManagerMaintenanceWindowCreator(ctrl) - - expected := &opsmngr.MaintenanceWindow{} - - t.Run("no access list", func(t *testing.T) { - createOpts := &CreateOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - CreateOpsManagerMaintenanceWindow(createOpts.ProjectID, createOpts.newMaintenanceWindow()). - Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} - -func TestCreateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.ProjectID, flag.StartDate, flag.EndDate, flag.Description}, - ) -} diff --git a/internal/cli/opsmanager/maintenance/delete.go b/internal/cli/opsmanager/maintenance/delete.go deleted file mode 100644 index 5b1b661605..0000000000 --- a/internal/cli/opsmanager/maintenance/delete.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package maintenance - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DeleteOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.OpsManagerMaintenanceWindowDeleter -} - -func (opts *DeleteOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DeleteOpts) Run() error { - return opts.Delete(opts.store.DeleteOpsManagerMaintenanceWindow, opts.ConfigProjectID()) -} - -// mongocli ops-manager maintenanceWindows delete --force. -func DeleteBuilder() *cobra.Command { - opts := &DeleteOpts{ - DeleteOpts: cli.NewDeleteOpts("Maintenance window '%s' deleted\n", "Maintenance window not deleted"), - } - cmd := &cobra.Command{ - Use: "delete ", - Aliases: []string{"rm"}, - Short: "Delete a maintenance window.", - Annotations: map[string]string{ - "IDDesc": "Maintenance window identifier.", - }, - Args: require.ExactArgs(1), - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/maintenance/delete_test.go b/internal/cli/opsmanager/maintenance/delete_test.go deleted file mode 100644 index 9916e45207..0000000000 --- a/internal/cli/opsmanager/maintenance/delete_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package maintenance - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestDelete_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOpsManagerMaintenanceWindowDeleter(ctrl) - - deleteOpts := &DeleteOpts{ - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "test", - }, - store: mockStore, - } - - mockStore. - EXPECT(). - DeleteOpsManagerMaintenanceWindow(deleteOpts.ProjectID, deleteOpts.Entry). - Return(nil). - Times(1) - - if err := deleteOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDeleteBuilder(t *testing.T) { - test.CmdValidator( - t, - DeleteBuilder(), - 0, - []string{flag.ProjectID}, - ) -} diff --git a/internal/cli/opsmanager/maintenance/describe.go b/internal/cli/opsmanager/maintenance/describe.go deleted file mode 100644 index 3b3610a08f..0000000000 --- a/internal/cli/opsmanager/maintenance/describe.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package maintenance - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - id string - store store.OpsManagerMaintenanceWindowDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var describeTemplate = `ID PROJECT ID START DATE END DATE -{{.ID}} {{.GroupID}} {{.StartDate}} {{.EndDate}} -` - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.OpsManagerMaintenanceWindow(opts.ConfigProjectID(), opts.id) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager maintenanceWindows describe [--projectId projectId]. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe ", - Short: "Get a maintenance window.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Maintenance window identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/maintenance/describe_test.go b/internal/cli/opsmanager/maintenance/describe_test.go deleted file mode 100644 index 45a7b2f1c0..0000000000 --- a/internal/cli/opsmanager/maintenance/describe_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package maintenance - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOpsManagerMaintenanceWindowDescriber(ctrl) - - expected := &opsmngr.MaintenanceWindow{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - OpsManagerMaintenanceWindow(opts.ProjectID, opts.id). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescrieBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.ProjectID}, - ) -} diff --git a/internal/cli/opsmanager/maintenance/list.go b/internal/cli/opsmanager/maintenance/list.go deleted file mode 100644 index a17b89b690..0000000000 --- a/internal/cli/opsmanager/maintenance/list.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package maintenance - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - store store.OpsManagerMaintenanceWindowLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `ID PROJECT ID START DATE END DATE{{range valueOrEmptySlice .Results}} -{{.ID}} {{.GroupID}} {{.StartDate}} {{.EndDate}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.OpsManagerMaintenanceWindows(opts.ConfigProjectID()) - if err != nil { - return err - } - return opts.Print(r) -} - -// mongocli ops-manager maintenanceWindows list [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Args: require.NoArgs, - Short: "List maintenance windows.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/maintenance/list_test.go b/internal/cli/opsmanager/maintenance/list_test.go deleted file mode 100644 index f7b1a6d13a..0000000000 --- a/internal/cli/opsmanager/maintenance/list_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package maintenance - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOpsManagerMaintenanceWindowLister(ctrl) - - expected := &opsmngr.MaintenanceWindows{} - - listOpts := ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - OpsManagerMaintenanceWindows(listOpts.ProjectID). - Return(expected, nil). - Times(1) - - config.SetService(config.OpsManagerService) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID}, - ) -} diff --git a/internal/cli/opsmanager/maintenance/maintenance.go b/internal/cli/opsmanager/maintenance/maintenance.go deleted file mode 100644 index 0922bfa021..0000000000 --- a/internal/cli/opsmanager/maintenance/maintenance.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package maintenance - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "maintenanceWindows" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage Ops Manager/Cloud Manager maintenance windows.", - } - - cmd.AddCommand( - CreateBuilder(), - ListBuilder(), - DeleteBuilder(), - DescribeBuilder(), - UpdateBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/maintenance/maintenance_test.go b/internal/cli/opsmanager/maintenance/maintenance_test.go deleted file mode 100644 index 63ac8f1563..0000000000 --- a/internal/cli/opsmanager/maintenance/maintenance_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package maintenance - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 5, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/maintenance/update.go b/internal/cli/opsmanager/maintenance/update.go deleted file mode 100644 index 88349df7b2..0000000000 --- a/internal/cli/opsmanager/maintenance/update.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package maintenance - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type UpdateOpts struct { - cli.GlobalOpts - cli.OutputOpts - alertType []string - startDate string - endDate string - description string - id string - store store.OpsManagerMaintenanceWindowUpdater -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var updateTemplate = "Maintenance window '{{.ID}}' successfully updated.\n" - -func (opts *UpdateOpts) Run() error { - r, err := opts.store.UpdateOpsManagerMaintenanceWindow(opts.ConfigProjectID(), opts.newMaintenanceWindow()) - if err != nil { - return err - } - return opts.Print(r) -} - -func (opts *UpdateOpts) newMaintenanceWindow() *opsmngr.MaintenanceWindow { - return &opsmngr.MaintenanceWindow{ - ID: opts.id, - StartDate: opts.startDate, - EndDate: opts.endDate, - AlertTypeNames: opts.alertType, - Description: opts.description, - } -} - -// mongocli ops-manager maintenanceWindows update --startDate startDate --endDate endDate --alertType alertType --desc desc [--projectId projectId]. -func UpdateBuilder() *cobra.Command { - opts := new(UpdateOpts) - cmd := &cobra.Command{ - Use: "update ", - Short: "Update a maintenance window.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Maintenance window identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), updateTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.id = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.startDate, flag.StartDate, "", usage.StartDate) - cmd.Flags().StringVar(&opts.endDate, flag.EndDate, "", usage.EndDate) - cmd.Flags().StringSliceVar(&opts.alertType, flag.AlertType, []string{}, usage.AlertType+usage.UpdateWarning) - cmd.Flags().StringVar(&opts.description, flag.Description, "", usage.MaintenanceDescription) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/maintenance/update_test.go b/internal/cli/opsmanager/maintenance/update_test.go deleted file mode 100644 index c78e58c5c4..0000000000 --- a/internal/cli/opsmanager/maintenance/update_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package maintenance - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOpsManagerMaintenanceWindowUpdater(ctrl) - - expected := &opsmngr.MaintenanceWindow{} - - t.Run("no access list", func(t *testing.T) { - opts := &UpdateOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - UpdateOpsManagerMaintenanceWindow(opts.ProjectID, opts.newMaintenanceWindow()). - Return(expected, nil). - Times(1) - - err := opts.Run() - if err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - CreateBuilder(), - 0, - []string{flag.ProjectID, flag.StartDate, flag.EndDate, flag.Description}, - ) -} diff --git a/internal/cli/opsmanager/metrics/databases.go b/internal/cli/opsmanager/metrics/databases.go deleted file mode 100644 index 4ca56bbba0..0000000000 --- a/internal/cli/opsmanager/metrics/databases.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "github.com/spf13/cobra" -) - -func DatabasesBuilder() *cobra.Command { - cmd := &cobra.Command{ - Use: "databases", - Aliases: []string{"database"}, - Short: "List available databases or databases measurements for a given host.", - } - - cmd.AddCommand( - DatabasesListBuilder(), - DatabasesDescribeBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/metrics/databases_describe.go b/internal/cli/opsmanager/metrics/databases_describe.go deleted file mode 100644 index 73108d9c92..0000000000 --- a/internal/cli/opsmanager/metrics/databases_describe.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DatabasesDescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.MetricsOpts - hostID string - name string - store store.HostDatabaseMeasurementsLister -} - -func (opts *DatabasesDescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var databasesMetricTemplate = `NAME UNITS TIMESTAMP VALUE{{range valueOrEmptySlice .ProcessMeasurements.Measurements}} {{if .DataPoints}} -{{- $name := .Name }}{{- $unit := .Units }}{{- range valueOrEmptySlice .DataPoints}} -{{ $name }} {{ $unit }} {{.Timestamp}} {{if .Value }} {{ .Value }}{{else}} N/A {{end}}{{end}}{{end}}{{end}} -` - -func (opts *DatabasesDescribeOpts) Run() error { - listOpts := opts.NewProcessMetricsListOptions() - r, err := opts.store.HostDatabaseMeasurements(opts.ConfigProjectID(), opts.hostID, opts.name, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mcli om metric(s) database(s) describe --granularity g --period p --start start --end end [--type type] [--projectId projectId]. -func DatabasesDescribeBuilder() *cobra.Command { - const argsN = 2 - opts := &DatabasesDescribeOpts{} - cmd := &cobra.Command{ - Use: "describe ", - Short: "Describe database measurements for a given host database.", - Args: require.ExactArgs(argsN), - Example: `# List metrics for the database test of the process e4ac1e57c58cc9c8aaa5a1163a851993 - mongocli ops-manager metrics database describe e4ac1e57c58cc9c8aaa5a1163a851993 test --period P1DT12H --granularity PT5`, - Annotations: map[string]string{ - "hostIdDesc": "Process identifier. You can use mongocli ops-manager processes list to get the ID.", - "nameDesc": "Database name.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.ValidatePeriodStartEnd, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), databasesMetricTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostID = args[0] - opts.name = args[1] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.Granularity, flag.Granularity, "", usage.Granularity) - cmd.Flags().StringVar(&opts.Period, flag.Period, "", usage.Period) - cmd.Flags().StringVar(&opts.Start, flag.Start, "", usage.MeasurementStart) - cmd.Flags().StringVar(&opts.End, flag.End, "", usage.MeasurementEnd) - cmd.Flags().StringSliceVar(&opts.MeasurementType, flag.TypeFlag, nil, usage.MeasurementType) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Granularity) - - cmd.MarkFlagsRequiredTogether(flag.Start, flag.End) - cmd.MarkFlagsMutuallyExclusive(flag.Period, flag.Start) - cmd.MarkFlagsMutuallyExclusive(flag.Period, flag.End) - - return cmd -} diff --git a/internal/cli/opsmanager/metrics/databases_describe_test.go b/internal/cli/opsmanager/metrics/databases_describe_test.go deleted file mode 100644 index 2a42c85c82..0000000000 --- a/internal/cli/opsmanager/metrics/databases_describe_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package metrics - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDatabasesDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockHostDatabaseMeasurementsLister(ctrl) - - listOpts := &DatabasesDescribeOpts{ - hostID: "1", - name: "test", - store: mockStore, - } - - opts := listOpts.NewProcessMetricsListOptions() - expected := &opsmngr.ProcessDatabaseMeasurements{ - ProcessMeasurements: &opsmngr.ProcessMeasurements{ - Measurements: []*opsmngr.Measurements{}, - }, - } - mockStore. - EXPECT().HostDatabaseMeasurements(listOpts.ProjectID, listOpts.hostID, listOpts.name, opts). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - test.VerifyOutputTemplate(t, databasesMetricTemplate, expected) -} diff --git a/internal/cli/opsmanager/metrics/databases_list.go b/internal/cli/opsmanager/metrics/databases_list.go deleted file mode 100644 index 02f206d8d2..0000000000 --- a/internal/cli/opsmanager/metrics/databases_list.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DatabasesListsOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - hostID string - store store.HostDatabaseLister -} - -func (opts *DatabasesListsOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var databasesListTemplate = `{{range valueOrEmptySlice .Results}} -{{.DatabaseName}}{{end}} -` - -func (opts *DatabasesListsOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.HostDatabases(opts.ConfigProjectID(), opts.hostID, listOpts) - - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om metric(s) process(es) disks lists . -func DatabasesListBuilder() *cobra.Command { - opts := &DatabasesListsOpts{} - cmd := &cobra.Command{ - Use: "list ", - Short: "List available databases for a given host.", - Aliases: []string{"ls"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Process identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), databasesListTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostID = args[0] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/metrics/databases_list_test.go b/internal/cli/opsmanager/metrics/databases_list_test.go deleted file mode 100644 index dab8143120..0000000000 --- a/internal/cli/opsmanager/metrics/databases_list_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package metrics - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDatabasesListsOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockHostDatabaseLister(ctrl) - - expected := &opsmngr.ProcessDatabasesResponse{} - - listOpts := &DatabasesListsOpts{ - hostID: "1", - store: mockStore, - } - - opts := listOpts.NewListOptions() - mockStore. - EXPECT().HostDatabases(listOpts.ProjectID, listOpts.hostID, opts). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/metrics/disks.go b/internal/cli/opsmanager/metrics/disks.go deleted file mode 100644 index 73ce50170d..0000000000 --- a/internal/cli/opsmanager/metrics/disks.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "github.com/spf13/cobra" -) - -func DisksBuilder() *cobra.Command { - cmd := &cobra.Command{ - Use: "disks", - Aliases: []string{"disk"}, - Short: "List available disks or disks measurements for a given host.", - } - - cmd.AddCommand( - DisksListBuilder(), - DisksDescribeBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/metrics/disks_describe.go b/internal/cli/opsmanager/metrics/disks_describe.go deleted file mode 100644 index 626dac93a8..0000000000 --- a/internal/cli/opsmanager/metrics/disks_describe.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DisksDescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.MetricsOpts - hostID string - name string - store store.HostDiskMeasurementsLister -} - -func (opts *DisksDescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var diskMetricTemplate = `NAME UNITS TIMESTAMP VALUE{{range valueOrEmptySlice .ProcessMeasurements.Measurements}} {{if .DataPoints}} -{{- $name := .Name }}{{- $unit := .Units }}{{- range valueOrEmptySlice .DataPoints}} -{{ $name }} {{ $unit }} {{.Timestamp}} {{if .Value }} {{ .Value }}{{else}} N/A {{end}}{{end}}{{end}}{{end}} -` - -func (opts *DisksDescribeOpts) Run() error { - listOpts := opts.NewProcessMetricsListOptions() - r, err := opts.store.HostDiskMeasurements(opts.ConfigProjectID(), opts.hostID, opts.name, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mcli om metric(s) disk(s) describe --granularity g --period p --start start --end end [--type type] [--projectId projectId]. -func DisksDescribeBuilder() *cobra.Command { - const argsN = 2 - opts := &DisksDescribeOpts{} - cmd := &cobra.Command{ - Use: "describe ", - Short: "Describe disks measurements for a given host partition.", - Args: require.ExactArgs(argsN), - Example: `# List metrics for the test partition of the process e4ac1e57c58cc9c8aaa5a1163a851993 - mongocli ops-manager metrics disk describe e4ac1e57c58cc9c8aaa5a1163a851993 test --period P1DT12H --granularity PT5`, - Annotations: map[string]string{ - "hostIdDesc": "Process identifier. You can use mongocli ops-manager processes list to get the ID.", - "nameDesc": "Partition name.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.ValidatePeriodStartEnd, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), diskMetricTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostID = args[0] - opts.name = args[1] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.Granularity, flag.Granularity, "", usage.Granularity) - cmd.Flags().StringVar(&opts.Period, flag.Period, "", usage.Period) - cmd.Flags().StringVar(&opts.Start, flag.Start, "", usage.MeasurementStart) - cmd.Flags().StringVar(&opts.End, flag.End, "", usage.MeasurementEnd) - cmd.Flags().StringSliceVar(&opts.MeasurementType, flag.TypeFlag, nil, usage.MeasurementType) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Granularity) - - cmd.MarkFlagsRequiredTogether(flag.Start, flag.End) - cmd.MarkFlagsMutuallyExclusive(flag.Period, flag.Start) - cmd.MarkFlagsMutuallyExclusive(flag.Period, flag.End) - - return cmd -} diff --git a/internal/cli/opsmanager/metrics/disks_describe_test.go b/internal/cli/opsmanager/metrics/disks_describe_test.go deleted file mode 100644 index 3af51759a3..0000000000 --- a/internal/cli/opsmanager/metrics/disks_describe_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package metrics - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDisksDescribeOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockHostDiskMeasurementsLister(ctrl) - - expected := &opsmngr.ProcessDiskMeasurements{ - ProcessMeasurements: &opsmngr.ProcessMeasurements{ - Measurements: []*opsmngr.Measurements{}, - }, - } - - listOpts := &DisksDescribeOpts{ - hostID: "1", - name: "test", - store: mockStore, - } - - opts := listOpts.NewProcessMetricsListOptions() - mockStore. - EXPECT().HostDiskMeasurements(listOpts.ProjectID, listOpts.hostID, listOpts.name, opts). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/metrics/disks_list.go b/internal/cli/opsmanager/metrics/disks_list.go deleted file mode 100644 index b5c148a645..0000000000 --- a/internal/cli/opsmanager/metrics/disks_list.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DisksListsOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - hostID string - store store.HostDisksLister -} - -func (opts *DisksListsOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `{{range valueOrEmptySlice .Results}} -{{.PartitionName}}{{end}} -` - -func (opts *DisksListsOpts) Run() error { - listOpts := opts.NewListOptions() - r, err := opts.store.HostDisks(opts.ConfigProjectID(), opts.hostID, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om metric(s) process(es) disks lists . -func DisksListBuilder() *cobra.Command { - opts := &DisksListsOpts{} - cmd := &cobra.Command{ - Use: "list ", - Short: "List available disks for a given host.", - Aliases: []string{"ls"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Process identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostID = args[0] - - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/metrics/disks_list_test.go b/internal/cli/opsmanager/metrics/disks_list_test.go deleted file mode 100644 index 43afaefc50..0000000000 --- a/internal/cli/opsmanager/metrics/disks_list_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package metrics - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDisksListsOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockHostDisksLister(ctrl) - - expected := &opsmngr.ProcessDisksResponse{} - - listOpts := &DisksListsOpts{ - hostID: "1", - store: mockStore, - } - - opts := listOpts.NewListOptions() - mockStore. - EXPECT().HostDisks(listOpts.ProjectID, listOpts.hostID, opts). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/metrics/metrics.go b/internal/cli/opsmanager/metrics/metrics.go deleted file mode 100644 index 9af6e95c38..0000000000 --- a/internal/cli/opsmanager/metrics/metrics.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "metrics", - Aliases: []string{"metric", "measurements", "measurement"}, - Short: "Get measurements on the state of the MongoDB process.", - } - - cmd.AddCommand( - ProcessBuilder(), - DisksBuilder(), - DatabasesBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/metrics/metrics_test.go b/internal/cli/opsmanager/metrics/metrics_test.go deleted file mode 100644 index fe2001f4f2..0000000000 --- a/internal/cli/opsmanager/metrics/metrics_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package metrics - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/metrics/process.go b/internal/cli/opsmanager/metrics/process.go deleted file mode 100644 index 843699b47f..0000000000 --- a/internal/cli/opsmanager/metrics/process.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ProcessOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.MetricsOpts - hostID string - store store.HostMeasurementLister -} - -func (opts *ProcessOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var metricTemplate = `NAME UNITS TIMESTAMP VALUE{{range valueOrEmptySlice .Measurements}} {{if .DataPoints}} -{{- $name := .Name }}{{- $unit := .Units }}{{- range valueOrEmptySlice .DataPoints}} -{{ $name }} {{ $unit }} {{.Timestamp}} {{if .Value }} {{ .Value }}{{else}} N/A {{end}}{{end}}{{end}}{{end}} -` - -func (opts *ProcessOpts) Run() error { - listOpts := opts.NewProcessMetricsListOptions() - r, err := opts.store.HostMeasurements(opts.ConfigProjectID(), opts.hostID, listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om|cm metric(s) process(es) [--granularity granularity] [--period period] [--start start] [--end end] [--type type][--projectId projectId]. -func ProcessBuilder() *cobra.Command { - opts := &ProcessOpts{} - cmd := &cobra.Command{ - Use: "process ", - Short: "Get measurements for a given host.", - Aliases: []string{"processes"}, - Example: `# List metrics for the process e4ac1e57c58cc9c8aaa5a1163a851993 - mongocli ops-manager metrics process e4ac1e57c58cc9c8aaa5a1163a851993 --period P1DT12H --granularity PT5`, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "hostIdDesc": "Process identifier. You can use mongocli ops-manager processes list to get the ID.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.ValidatePeriodStartEnd, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), metricTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.Granularity, flag.Granularity, "", usage.Granularity) - cmd.Flags().StringVar(&opts.Period, flag.Period, "", usage.Period) - cmd.Flags().StringVar(&opts.Start, flag.Start, "", usage.MeasurementStart) - cmd.Flags().StringVar(&opts.End, flag.End, "", usage.MeasurementEnd) - cmd.Flags().StringSliceVar(&opts.MeasurementType, flag.TypeFlag, nil, usage.MeasurementType) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Granularity) - - cmd.MarkFlagsRequiredTogether(flag.Start, flag.End) - cmd.MarkFlagsMutuallyExclusive(flag.Period, flag.Start) - cmd.MarkFlagsMutuallyExclusive(flag.Period, flag.End) - - return cmd -} diff --git a/internal/cli/opsmanager/metrics/process_test.go b/internal/cli/opsmanager/metrics/process_test.go deleted file mode 100644 index 8413f3d703..0000000000 --- a/internal/cli/opsmanager/metrics/process_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package metrics - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -const oneMinute = "PT1M" - -func TestProcess_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockHostMeasurementLister(ctrl) - - expected := &opsmngr.ProcessMeasurements{} - - listOpts := &ProcessOpts{ - hostID: "hard-00-00.mongodb.net", - store: mockStore, - } - listOpts.Granularity = oneMinute - listOpts.Period = oneMinute - - opts := listOpts.NewProcessMetricsListOptions() - mockStore. - EXPECT().HostMeasurements(listOpts.ProjectID, listOpts.hostID, opts). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/monitoring/disable.go b/internal/cli/opsmanager/monitoring/disable.go deleted file mode 100644 index 34dc05971d..0000000000 --- a/internal/cli/opsmanager/monitoring/disable.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package monitoring - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -type DisableOpts struct { - cli.GlobalOpts - hostname string - store store.AutomationPatcher -} - -func (opts *DisableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DisableOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if err := atmcfg.DisableMonitoring(current, opts.hostname); err != nil { - return err - } - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli ops-manager monitoring disable [--projectId projectId]. -func DisableBuilder() *cobra.Command { - opts := &DisableOpts{} - cmd := &cobra.Command{ - Use: "disable ", - Short: "Disable monitoring for a given hostname", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "hostnameDesc": "Label for the hostname.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostname = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/monitoring/disable_test.go b/internal/cli/opsmanager/monitoring/disable_test.go deleted file mode 100644 index 8188cbd698..0000000000 --- a/internal/cli/opsmanager/monitoring/disable_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package monitoring - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestDisableBuilder(t *testing.T) { - test.CmdValidator( - t, - DisableBuilder(), - 0, - []string{flag.ProjectID}, - ) -} - -func TestDisableOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfigWithMonitoring() - - createOpts := &DisableOpts{ - hostname: "test", - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/monitoring/enable.go b/internal/cli/opsmanager/monitoring/enable.go deleted file mode 100644 index 77e2db98ae..0000000000 --- a/internal/cli/opsmanager/monitoring/enable.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package monitoring - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -func Builder() *cobra.Command { - const use = "monitoring" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage monitoring for your project.", - } - - cmd.AddCommand( - EnableBuilder(), - DisableBuilder(), - StopBuilder(), - ) - return cmd -} - -type EnableOpts struct { - cli.GlobalOpts - hostname string - store store.AutomationPatcher -} - -func (opts *EnableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *EnableOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if err := atmcfg.EnableMonitoring(current, opts.hostname); err != nil { - return err - } - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli ops-manager monitoring enable [--projectId projectId]. -func EnableBuilder() *cobra.Command { - opts := &EnableOpts{} - cmd := &cobra.Command{ - Use: "enable ", - Short: "Enable monitoring for a given hostname", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "hostnameDesc": "Label for the hostname.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostname = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/monitoring/enable_test.go b/internal/cli/opsmanager/monitoring/enable_test.go deleted file mode 100644 index 4467f0c73c..0000000000 --- a/internal/cli/opsmanager/monitoring/enable_test.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package monitoring - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 3, - []string{}, - ) -} - -func TestEnableBuilder(t *testing.T) { - test.CmdValidator( - t, - EnableBuilder(), - 0, - []string{flag.ProjectID}, - ) -} - -func TestEnableOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - createOpts := &EnableOpts{ - hostname: "test", - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/monitoring/stop.go b/internal/cli/opsmanager/monitoring/stop.go deleted file mode 100644 index 00a6c0d9ad..0000000000 --- a/internal/cli/opsmanager/monitoring/stop.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package monitoring - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type StopOpts struct { - cli.GlobalOpts - *cli.DeleteOpts - store store.MonitoringStopper -} - -func (opts *StopOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *StopOpts) Run() error { - return opts.Delete(opts.store.StopMonitoring, opts.ConfigProjectID()) -} - -// mongocli ops-manager monitoring stop --force. -func StopBuilder() *cobra.Command { - opts := &StopOpts{ - DeleteOpts: cli.NewDeleteOpts("Stopped monitoring '%s'\n", "Monitoring did not stop"), - } - cmd := &cobra.Command{ - Use: "stop ", - Aliases: []string{"rm"}, - Short: "Stops monitoring the MongoDB process specified", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "IDDesc": "Process identifier.", - }, - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())); err != nil { - return err - } - opts.Entry = args[0] - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.Confirm, flag.Force, false, usage.Force) - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/monitoring/stop_test.go b/internal/cli/opsmanager/monitoring/stop_test.go deleted file mode 100644 index 90991e449f..0000000000 --- a/internal/cli/opsmanager/monitoring/stop_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package monitoring - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestStopBuilder(t *testing.T) { - test.CmdValidator( - t, - StopBuilder(), - 0, - []string{flag.ProjectID, flag.Force}, - ) -} - -func TestStopOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockMonitoringStopper(ctrl) - - opts := &StopOpts{ - store: mockStore, - DeleteOpts: &cli.DeleteOpts{ - Confirm: true, - Entry: "test", - }, - } - - mockStore. - EXPECT(). - StopMonitoring(opts.ProjectID, opts.Entry). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/ops_manager.go b/internal/cli/opsmanager/ops_manager.go deleted file mode 100644 index df87bae126..0000000000 --- a/internal/cli/opsmanager/ops_manager.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package opsmanager - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/alerts" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/events" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/mongocli/performanceadvisor" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/admin" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/agents" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/automation" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/backup" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/clusters" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/dbusers" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/diagnosearchive" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/featurepolicies" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/livemigrations" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/logs" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/maintenance" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/metrics" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/monitoring" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/owner" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/processes" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/security" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/servers" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/serverusage" - softwarecompotents "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/softwarecomponents" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/versionmanifest" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/log" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/mongodb/mongodb-atlas-cli/internal/validate" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - var debugLevel bool - cmd := &cobra.Command{ - Use: "ops-manager", - Aliases: []string{"om"}, - Short: "MongoDB Ops Manager operations.", - PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { - log.SetWriter(cmd.ErrOrStderr()) - if debugLevel { - log.SetLevel(log.DebugLevel) - } - - config.SetService(config.OpsManagerService) - // do not validate to create an owner - if cmd.CommandPath() != "mongocli ops-manager owner create" { - return validate.Credentials() - } - return nil - }, - Annotations: map[string]string{ - "toc": "true", - }, - } - - cmd.AddCommand( - clusters.Builder(), - alerts.Builder(), - backup.Builder(), - servers.Builder(), - automation.Builder(), - security.Builder(), - dbusers.Builder(), - owner.Builder(), - events.Builder(), - monitoring.Builder(), - processes.Builder(), - metrics.Builder(), - logs.Builder(), - agents.Builder(), - diagnosearchive.Builder(), - maintenance.Builder(), - performanceadvisor.Builder(), - versionmanifest.Builder(), - admin.Builder(), - softwarecompotents.Builder(), - featurepolicies.Builder(), - serverusage.Builder(), - livemigrations.Builder()) - - cmd.PersistentFlags().BoolVarP(&debugLevel, flag.Debug, flag.DebugShort, false, usage.Debug) - _ = cmd.PersistentFlags().MarkHidden(flag.Debug) - - return cmd -} diff --git a/internal/cli/opsmanager/ops_manager_test.go b/internal/cli/opsmanager/ops_manager_test.go deleted file mode 100644 index 44d5e803e4..0000000000 --- a/internal/cli/opsmanager/ops_manager_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package opsmanager - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 23, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/owner/create.go b/internal/cli/opsmanager/owner/create.go deleted file mode 100644 index 18236e8e11..0000000000 --- a/internal/cli/opsmanager/owner/create.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package owner - -import ( - "context" - "fmt" - - "github.com/AlecAivazis/survey/v2" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/telemetry" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type CreateOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.InputOpts - email string - password string - firstName string - lastName string - accessIps []string - store store.OwnerCreator -} - -func (opts *CreateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.UnauthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var createTemplate = `Owner successfully created. -{{if .APIKey}}Personal API Key: {{.APIKey}}{{end}} -{{- if .ProgrammaticAPIKey}} -Public API Key: {{.ProgrammaticAPIKey.PublicKey}} -Private API Key: {{.ProgrammaticAPIKey.PrivateKey}} -{{- end}} -` - -func (opts *CreateOpts) Run() error { - user := opts.newOwner() - r, err := opts.store.CreateOwner(user, opts.accessIps) - - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *CreateOpts) newOwner() *opsmngr.User { - user := &opsmngr.User{ - Username: opts.email, - Password: opts.password, - FirstName: opts.firstName, - LastName: opts.lastName, - EmailAddress: opts.email, - Links: nil, - } - return user -} - -func (opts *CreateOpts) Prompt() error { - if opts.password != "" { - return nil - } - - if !opts.IsTerminalInput() { - _, err := fmt.Fscanln(opts.InReader, &opts.password) - return err - } - - prompt := &survey.Password{ - Message: "Password:", - } - return telemetry.TrackAskOne(prompt, &opts.password) -} - -// CreateBuilder mongocli ops-manager owner create --email username --password password --firstName firstName --lastName lastName --accessListIp . -func CreateBuilder() *cobra.Command { - opts := new(CreateOpts) - cmd := &cobra.Command{ - Use: "create", - Short: "Create the first user for Ops Manager.", - Long: "Create the first user for Ops Manager. Use this command to automate Ops Manager Installations.", - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - if err := opts.PreRunE( - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), createTemplate), - opts.InitInput(cmd.InOrStdin())); err != nil { - return err - } - - return opts.Prompt() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.email, flag.Email, "", usage.Email) - cmd.Flags().StringVarP(&opts.password, flag.Password, flag.PasswordShort, "", usage.Password) - cmd.Flags().StringVar(&opts.firstName, flag.FirstName, "", usage.FirstName) - cmd.Flags().StringVar(&opts.lastName, flag.LastName, "", usage.LastName) - cmd.Flags().StringSliceVar(&opts.accessIps, flag.AccessListIP, []string{}, usage.AccessListIps) - cmd.Flags().StringSliceVar(&opts.accessIps, flag.WhitelistIP, []string{}, usage.AccessListIps) - _ = cmd.Flags().MarkDeprecated(flag.WhitelistIP, fmt.Sprintf("please use --%s instead", flag.AccessListIP)) - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.Email) - _ = cmd.MarkFlagRequired(flag.FirstName) - _ = cmd.MarkFlagRequired(flag.LastName) - - return cmd -} diff --git a/internal/cli/opsmanager/owner/create_test.go b/internal/cli/opsmanager/owner/create_test.go deleted file mode 100644 index d1d287b5d6..0000000000 --- a/internal/cli/opsmanager/owner/create_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package owner - -import ( - "bytes" - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/stretchr/testify/require" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestManagerOwnerCreate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOwnerCreator(ctrl) - - email := "test@test.com" - password := "Passw0rd!" - firstName := "Testy" - lastName := "McTestyson" - expected := &opsmngr.CreateUserResponse{} - - t.Run("no access list", func(t *testing.T) { - createOpts := &CreateOpts{ - email: email, - password: password, - firstName: firstName, - lastName: lastName, - store: mockStore, - } - - mockStore. - EXPECT(). - CreateOwner(createOpts.newOwner(), createOpts.accessIps).Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - - t.Run("with access list", func(t *testing.T) { - createOpts := &CreateOpts{ - email: email, - password: password, - firstName: firstName, - lastName: lastName, - store: mockStore, - accessIps: []string{"192.168.0.1"}, - } - - mockStore. - EXPECT(). - CreateOwner(createOpts.newOwner(), createOpts.accessIps).Return(expected, nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) -} - -func TestManagerOwnerCreateWithPasswordStdin(t *testing.T) { - password := "P4ssw0rd!" - - createOpts := &CreateOpts{} - - require.NoError(t, createOpts.InitInput(bytes.NewReader([]byte(password)))()) - require.NoError(t, createOpts.Prompt()) - - if u := createOpts.newOwner(); u.Password != password { - t.Fatalf("failed to set password from input stream") - } -} diff --git a/internal/cli/opsmanager/owner/owner.go b/internal/cli/opsmanager/owner/owner.go deleted file mode 100644 index 0612488842..0000000000 --- a/internal/cli/opsmanager/owner/owner.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package owner - -import ( - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "owner", - Short: "Manage Ops Manager owners.", - } - - cmd.AddCommand(CreateBuilder()) - return cmd -} diff --git a/internal/cli/opsmanager/owner/owner_test.go b/internal/cli/opsmanager/owner/owner_test.go deleted file mode 100644 index b534cd53f5..0000000000 --- a/internal/cli/opsmanager/owner/owner_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package owner - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/processes/describe.go b/internal/cli/opsmanager/processes/describe.go deleted file mode 100644 index 7fcd48f19f..0000000000 --- a/internal/cli/opsmanager/processes/describe.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package processes - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type DescribeOpts struct { - cli.GlobalOpts - cli.OutputOpts - hostID string - store store.HostDescriber -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var describeTemplate = `ID TYPE HOSTNAME PORT -{{.ID}} {{.TypeName}} {{.Hostname}} {{.Port}} -` - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.Host(opts.ConfigProjectID(), opts.hostID) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om process(es) describe [--projectId projectId]. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe ", - Short: "Describe MongoDB processes for your project.", - Aliases: []string{"get"}, - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "hostIdDesc": "Process identifier.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), describeTemplate), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.hostID = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/processes/describe_test.go b/internal/cli/opsmanager/processes/describe_test.go deleted file mode 100644 index 8c059a89e0..0000000000 --- a/internal/cli/opsmanager/processes/describe_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package processes - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestDescribe_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockHostDescriber(ctrl) - - expected := &opsmngr.Host{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - Host(opts.ProjectID, opts.hostID). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/processes/list.go b/internal/cli/opsmanager/processes/list.go deleted file mode 100644 index 563e4221ac..0000000000 --- a/internal/cli/opsmanager/processes/list.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package processes - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - clusterID string - store store.HostLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `ID TYPE HOSTNAME STATE NAME PORT{{range valueOrEmptySlice .Results}} -{{.ID}} {{.TypeName}} {{.Hostname}} {{.ReplicaStateName}} {{.Port}}{{end}} -` - -func (opts *ListOpts) Run() error { - listOpts := opts.newHostListOptions() - r, err := opts.store.Hosts(opts.ConfigProjectID(), listOpts) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *ListOpts) newHostListOptions() *opsmngr.HostListOptions { - return &opsmngr.HostListOptions{ - ClusterID: opts.clusterID, - ListOptions: *opts.NewListOptions(), - } -} - -// mongocli om process(es) list --projectId projectId [--page N] [--limit N]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Short: "List MongoDB processes for your project.", - Aliases: []string{"ls"}, - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.clusterID, flag.ClusterID, "", usage.ClusterID) - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/processes/list_test.go b/internal/cli/opsmanager/processes/list_test.go deleted file mode 100644 index 973e3b2ad1..0000000000 --- a/internal/cli/opsmanager/processes/list_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package processes - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockHostLister(ctrl) - - expected := &opsmngr.Hosts{} - - listOpts := &ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - Hosts(listOpts.ProjectID, listOpts.newHostListOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/processes/processes.go b/internal/cli/opsmanager/processes/processes.go deleted file mode 100644 index 28f686e3b6..0000000000 --- a/internal/cli/opsmanager/processes/processes.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package processes - -import ( - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "processes", - Aliases: []string{"process"}, - Short: "Manage MongoDB processes for your project.", - } - cmd.AddCommand( - ListBuilder(), - DescribeBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/processes/processes_test.go b/internal/cli/opsmanager/processes/processes_test.go deleted file mode 100644 index c5ae31b06d..0000000000 --- a/internal/cli/opsmanager/processes/processes_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package processes - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/security/enable.go b/internal/cli/opsmanager/security/enable.go deleted file mode 100644 index dbe2a11b4c..0000000000 --- a/internal/cli/opsmanager/security/enable.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package security - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/atmcfg" -) - -const ( - cr = "MONGODB-CR" - sha1 = "SCRAM-SHA-1" - sha256 = "SCRAM-SHA-256" -) - -type EnableOpts struct { - cli.GlobalOpts - mechanisms []string - store store.AutomationPatcher -} - -func (opts *EnableOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *EnableOpts) Run() error { - current, err := opts.store.GetAutomationConfig(opts.ConfigProjectID()) - - if err != nil { - return err - } - - if err := atmcfg.EnableMechanism(current, opts.mechanisms); err != nil { - return err - } - if err := opts.store.UpdateAutomationConfig(opts.ConfigProjectID(), current); err != nil { - return err - } - - fmt.Print(cli.DeploymentStatus(config.OpsManagerURL(), opts.ConfigProjectID())) - - return nil -} - -// mongocli ops-manager security enable [--projectId projectId]. -func EnableBuilder() *cobra.Command { - opts := &EnableOpts{} - cmd := &cobra.Command{ - Use: fmt.Sprintf("enable <%s|%s>", cr, sha256), - Short: "Enable authentication mechanisms for your project.", - Args: cobra.OnlyValidArgs, - ValidArgs: []string{cr, sha1, sha256}, - Annotations: map[string]string{ - "MONGODB-CR|SCRAM-SHA-256Desc": "Authentication mechanism.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE(opts.ValidateProjectID, opts.initStore(cmd.Context())) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.mechanisms = args - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/security/enable_test.go b/internal/cli/opsmanager/security/enable_test.go deleted file mode 100644 index 4275b64a91..0000000000 --- a/internal/cli/opsmanager/security/enable_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package security - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestSecurityEnableOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAutomationPatcher(ctrl) - - expected := fixture.AutomationConfig() - - createOpts := &EnableOpts{ - mechanisms: []string{sha256}, - store: mockStore, - } - - mockStore. - EXPECT(). - GetAutomationConfig(createOpts.ProjectID). - Return(expected, nil). - Times(1) - - mockStore. - EXPECT(). - UpdateAutomationConfig(createOpts.ProjectID, expected). - Return(nil). - Times(1) - - if err := createOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} diff --git a/internal/cli/opsmanager/security/security.go b/internal/cli/opsmanager/security/security.go deleted file mode 100644 index 98679de66c..0000000000 --- a/internal/cli/opsmanager/security/security.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package security - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - cmd := &cobra.Command{ - Use: "security", - Short: "Manage security configuration for your project.", - Args: require.NoArgs, - } - - cmd.AddCommand(EnableBuilder()) - return cmd -} diff --git a/internal/cli/opsmanager/security/security_test.go b/internal/cli/opsmanager/security/security_test.go deleted file mode 100644 index fafe6a0f0f..0000000000 --- a/internal/cli/opsmanager/security/security_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package security - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/servers/list.go b/internal/cli/opsmanager/servers/list.go deleted file mode 100644 index b6136d3838..0000000000 --- a/internal/cli/opsmanager/servers/list.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package servers - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const ( - agentType = "AUTOMATION" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.AgentLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `HOSTNAME STATE{{range valueOrEmptySlice .Results}} -{{.Hostname}} {{.StateName}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.Agents(opts.ConfigProjectID(), agentType, opts.NewListOptions()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om server(s) list [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Args: require.NoArgs, - Short: "List all available servers running an automation agent for your project.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/servers/list_test.go b/internal/cli/opsmanager/servers/list_test.go deleted file mode 100644 index c0f39e9c80..0000000000 --- a/internal/cli/opsmanager/servers/list_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package servers - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestAgentsList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAgentLister(ctrl) - - expected := &opsmngr.Agents{} - - listOpts := ListOpts{ - store: mockStore, - } - listOpts.ProjectID = "1" - - mockStore. - EXPECT(). - Agents(listOpts.ProjectID, agentType, listOpts.NewListOptions()). - Return(expected, nil). - Times(1) - - config.SetService(config.OpsManagerService) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Output, flag.Page, flag.Limit}, - ) -} diff --git a/internal/cli/opsmanager/servers/servers.go b/internal/cli/opsmanager/servers/servers.go deleted file mode 100644 index 9211be8461..0000000000 --- a/internal/cli/opsmanager/servers/servers.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package servers - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "servers" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage automated servers for your project.", - } - - cmd.AddCommand(ListBuilder()) - return cmd -} diff --git a/internal/cli/opsmanager/servers/servers_test.go b/internal/cli/opsmanager/servers/servers_test.go deleted file mode 100644 index b112241631..0000000000 --- a/internal/cli/opsmanager/servers/servers_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package servers - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/capture.go b/internal/cli/opsmanager/serverusage/capture.go deleted file mode 100644 index f6caeb60c4..0000000000 --- a/internal/cli/opsmanager/serverusage/capture.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package serverusage - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/spf13/cobra" -) - -type CaptureOpts struct { - store store.SnapshotGenerator -} - -func (opts *CaptureOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *CaptureOpts) Run() error { - err := opts.store.GenerateSnapshot() - if err != nil { - return err - } - fmt.Print("Snapshot captured.\n") - return nil -} - -// mongocli om serverUsage capture. -func CaptureBuilder() *cobra.Command { - opts := &CaptureOpts{} - cmd := &cobra.Command{ - Use: "capture", - Short: "Capture a snapshot of usage for the processes Ops Manager manages.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/capture_test.go b/internal/cli/opsmanager/serverusage/capture_test.go deleted file mode 100644 index 5722f2e97b..0000000000 --- a/internal/cli/opsmanager/serverusage/capture_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverusage - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestCapture_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockSnapshotGenerator(ctrl) - - opts := CaptureOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - GenerateSnapshot(). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestCaptureBuilder(t *testing.T) { - test.CmdValidator( - t, - CaptureBuilder(), - 0, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/download.go b/internal/cli/opsmanager/serverusage/download.go deleted file mode 100644 index 074a03a140..0000000000 --- a/internal/cli/opsmanager/serverusage/download.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package serverusage - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/afero" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type DownloadOpts struct { - cli.DownloaderOpts - startDate string - endDate string - format string - skipRedaction bool - store store.ServerUsageReportDownloader -} - -var downloadMessage = "Download of %s completed.\n" - -func (opts *DownloadOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DownloadOpts) Run() error { - f, err := opts.NewWriteCloser() - if err != nil { - return err - } - - if err := opts.store.DownloadServerUsageReport(opts.newServerTypeOptions(), f); err != nil { - _ = opts.OnError(f) - return err - } - if !opts.ShouldDownloadToStdout() { - fmt.Printf(downloadMessage, opts.Out) - } - return f.Close() -} - -func (opts *DownloadOpts) newServerTypeOptions() *opsmngr.ServerTypeOptions { - redact := !opts.skipRedaction - return &opsmngr.ServerTypeOptions{ - StartDate: opts.startDate, - EndDate: opts.endDate, - FileFormat: opts.format, - Redact: &redact, - } -} - -func (opts *DownloadOpts) initDefaultOut() { - if opts.Out == "" { - opts.Out = fmt.Sprintf("serverUsage-%s-%s.%s", opts.startDate, opts.endDate, opts.format) - } -} - -// mongocli om serverUsage download [--startDate startDate] [--endDate endDate] [--format format] [--force] [--output destination] [--projectId projectId]. -func DownloadBuilder() *cobra.Command { - opts := &DownloadOpts{} - opts.Fs = afero.NewOsFs() - cmd := &cobra.Command{ - Use: "download", - Short: "Download the server usage report.", - Example: ` mongocli ops-manager serverUsage download --endDate 2022-12-12 --startDate 2022-01-01`, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.initDefaultOut() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.startDate, flag.StartDate, "", usage.ServerUsageStartDate) - cmd.Flags().StringVar(&opts.endDate, flag.EndDate, "", usage.ServerUsageEndDate) - cmd.Flags().StringVar(&opts.format, flag.Format, "tar.gz", usage.ServerUsageFormat) - cmd.Flags().StringVar(&opts.Out, flag.Out, "", usage.LogOut) - cmd.Flags().BoolVar(&opts.skipRedaction, flag.SkipRedaction, false, usage.ServerUsageSkipRedacted) - cmd.Flags().BoolVar(&opts.Force, flag.Force, false, usage.ForceFile) - - _ = cmd.MarkFlagRequired(flag.StartDate) - _ = cmd.MarkFlagRequired(flag.EndDate) - cmd.MarkFlagsRequiredTogether(flag.StartDate, flag.EndDate) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/download_test.go b/internal/cli/opsmanager/serverusage/download_test.go deleted file mode 100644 index d4732e64e0..0000000000 --- a/internal/cli/opsmanager/serverusage/download_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverusage - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "github.com/spf13/afero" -) - -func TestLogsDownloadOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockServerUsageReportDownloader(ctrl) - - opts := &DownloadOpts{ - store: mockStore, - } - opts.Fs = afero.NewMemMapFs() - opts.Out = "fake_report.tar.gz" - - mockStore. - EXPECT(). - DownloadServerUsageReport(opts.newServerTypeOptions(), gomock.Any()). - Return(nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDownloadBuilder(t *testing.T) { - test.CmdValidator( - t, - DownloadBuilder(), - 0, - []string{flag.Out, flag.Force, flag.StartDate, flag.EndDate, flag.Format}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/organizations/hosts/hosts.go b/internal/cli/opsmanager/serverusage/organizations/hosts/hosts.go deleted file mode 100644 index 1b9c2c7fd7..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/hosts/hosts.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package hosts - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "hosts" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage host assignment for an organization.", - } - - cmd.AddCommand( - ListBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/organizations/hosts/hosts_test.go b/internal/cli/opsmanager/serverusage/organizations/hosts/hosts_test.go deleted file mode 100644 index 009e4b3deb..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/hosts/hosts_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package hosts - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/organizations/hosts/list.go b/internal/cli/opsmanager/serverusage/organizations/hosts/list.go deleted file mode 100644 index b9a0013d68..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/hosts/list.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package hosts - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.OrganizationHostAssignmentLister - startDate string - endDate string -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `HOSTNAME SERVER TYPE MEM SIZE MB CHARGEABLE{{- range valueOrEmptySlice .Results}} -{{.Hostname}} {{.ServerType.Name}} {{.MemSizeMB}} {{.IsChargeable}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.OrganizationHostAssignments(opts.ConfigOrgID(), opts.newServerTypeOptions()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *ListOpts) newServerTypeOptions() *opsmngr.ServerTypeOptions { - return &opsmngr.ServerTypeOptions{ - ListOptions: *opts.NewListOptions(), - StartDate: opts.startDate, - EndDate: opts.endDate, - } -} - -// mongocli om serverUsage project(s) hosts list [--orgId orgId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "List all host assignments for one organization.", - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.startDate, flag.StartDate, "", usage.ServerUsageStartDate) - cmd.Flags().StringVar(&opts.endDate, flag.EndDate, "", usage.ServerUsageEndDate) - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.StartDate) - _ = cmd.MarkFlagRequired(flag.EndDate) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/organizations/hosts/list_test.go b/internal/cli/opsmanager/serverusage/organizations/hosts/list_test.go deleted file mode 100644 index eeadd06b8a..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/hosts/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package hosts - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationHostAssignmentLister(ctrl) - - expected := &opsmngr.HostAssignments{} - - listOpts := ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - OrganizationHostAssignments(listOpts.ProjectID, listOpts.newServerTypeOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.OrgID, flag.Output, flag.Page, flag.Limit, flag.EndDate, flag.StartDate}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/organizations/organizations.go b/internal/cli/opsmanager/serverusage/organizations/organizations.go deleted file mode 100644 index 46713c50b7..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/organizations.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package organizations - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/serverusage/organizations/hosts" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/serverusage/organizations/servertype" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "organizations" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage your server usage for an organization.", - } - - cmd.AddCommand( - servertype.Builder(), - hosts.Builder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/organizations/organizations_test.go b/internal/cli/opsmanager/serverusage/organizations/organizations_test.go deleted file mode 100644 index 9884bec692..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/organizations_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package organizations - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/organizations/servertype/describe.go b/internal/cli/opsmanager/serverusage/organizations/servertype/describe.go deleted file mode 100644 index 7cceb06521..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/servertype/describe.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package servertype - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var getTemplate = `NAME LABEL -{{.Name}} {{.Label}} -` - -type DescribeOpts struct { - cli.OutputOpts - cli.GlobalOpts - store store.OrganizationServerTypeGetter -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.OrganizationServerType(opts.ConfigOrgID()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager serverUsage organization(s) serverType get [--orgId orgId]. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe", - Aliases: []string{"get"}, - Short: "Get the default server type for an organization.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), getTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/organizations/servertype/describe_test.go b/internal/cli/opsmanager/serverusage/organizations/servertype/describe_test.go deleted file mode 100644 index 454688c638..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/servertype/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package servertype - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestGetOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationServerTypeGetter(ctrl) - - expected := &opsmngr.ServerType{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT().OrganizationServerType(opts.ConfigOrgID()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.Output, flag.OrgID}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/organizations/servertype/server_type.go b/internal/cli/opsmanager/serverusage/organizations/servertype/server_type.go deleted file mode 100644 index 75711f4081..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/servertype/server_type.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package servertype - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "serverType" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage your server type for an organization.", - } - - cmd.AddCommand( - DescribeBuilder(), - SetBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/organizations/servertype/server_type_test.go b/internal/cli/opsmanager/serverusage/organizations/servertype/server_type_test.go deleted file mode 100644 index 6f47b62322..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/servertype/server_type_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package servertype - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/organizations/servertype/set.go b/internal/cli/opsmanager/serverusage/organizations/servertype/set.go deleted file mode 100644 index d838ef9d58..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/servertype/set.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package servertype - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type SetOpts struct { - cli.GlobalOpts - store store.OrganizationServerTypeUpdater - serverType string -} - -func (opts *SetOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *SetOpts) Run() error { - err := opts.store.UpdateOrganizationServerType(opts.ConfigOrgID(), opts.newServerTypeRequest()) - if err != nil { - return err - } - fmt.Printf("Serve type %s correctly set\n", opts.serverType) - return nil -} - -func (opts *SetOpts) newServerTypeRequest() *opsmngr.ServerTypeRequest { - return &opsmngr.ServerTypeRequest{ - ServerType: &opsmngr.ServerType{ - Name: opts.serverType, - }, - } -} - -// mongocli ops-manager serverUsage organization(s) serverType set [--orgId orgId]. -func SetBuilder() *cobra.Command { - opts := &SetOpts{} - cmd := &cobra.Command{ - Use: "set ", - Args: require.ExactValidArgs(1), - ValidArgs: []string{"DEV_SERVER", "TEST_SERVER", "PRODUCTION_SERVER", "RAM_POOL"}, - Short: "Set the default server type for an organization.", - Annotations: map[string]string{ - "typeDesc": "Server type to set.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateOrgID, - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.serverType = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.OrgID, flag.OrgID, "", usage.OrgID) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/organizations/servertype/set_test.go b/internal/cli/opsmanager/serverusage/organizations/servertype/set_test.go deleted file mode 100644 index 6a9fa84d9f..0000000000 --- a/internal/cli/opsmanager/serverusage/organizations/servertype/set_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package servertype - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestSetOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockOrganizationServerTypeUpdater(ctrl) - - opts := &SetOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateOrganizationServerType(opts.ConfigOrgID(), opts.newServerTypeRequest()). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestSetBuilder(t *testing.T) { - test.CmdValidator( - t, - SetBuilder(), - 0, - []string{flag.OrgID}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/projects/hosts/hosts.go b/internal/cli/opsmanager/serverusage/projects/hosts/hosts.go deleted file mode 100644 index 71790f631b..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/hosts/hosts.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package hosts - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "hosts" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage host assignment for a project.", - } - - cmd.AddCommand( - ListBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/projects/hosts/hosts_test.go b/internal/cli/opsmanager/serverusage/projects/hosts/hosts_test.go deleted file mode 100644 index f71fd56f9e..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/hosts/hosts_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//go:build unit - -package hosts - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/projects/hosts/list.go b/internal/cli/opsmanager/serverusage/projects/hosts/list.go deleted file mode 100644 index 52f2f5e696..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/hosts/list.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package hosts - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type ListOpts struct { - cli.GlobalOpts - cli.OutputOpts - cli.ListOpts - store store.ProjectHostAssignmentLister - startDate string - endDate string -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `HOSTNAME SERVER TYPE MEM SIZE MB CHARGEABLE{{- range valueOrEmptySlice .Results}} -{{.Hostname}} {{.ServerType.Name}} {{.MemSizeMB}} {{.IsChargeable}}{{end}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.ProjectHostAssignments(opts.ConfigProjectID(), opts.newServerTypeOptions()) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *ListOpts) newServerTypeOptions() *opsmngr.ServerTypeOptions { - return &opsmngr.ServerTypeOptions{ - ListOptions: *opts.NewListOptions(), - StartDate: opts.startDate, - EndDate: opts.endDate, - } -} - -// mongocli om serverUsage project(s) hosts list [--projectId projectId]. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "List all host assignments for one project.", - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), listTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.startDate, flag.StartDate, "", usage.ServerUsageStartDate) - cmd.Flags().StringVar(&opts.endDate, flag.EndDate, "", usage.ServerUsageEndDate) - - cmd.Flags().IntVar(&opts.PageNum, flag.Page, cli.DefaultPage, usage.Page) - cmd.Flags().IntVar(&opts.ItemsPerPage, flag.Limit, cli.DefaultPageLimit, usage.Limit) - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - _ = cmd.MarkFlagRequired(flag.StartDate) - _ = cmd.MarkFlagRequired(flag.EndDate) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/projects/hosts/list_test.go b/internal/cli/opsmanager/serverusage/projects/hosts/list_test.go deleted file mode 100644 index 7554122c21..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/hosts/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package hosts - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectHostAssignmentLister(ctrl) - - expected := &opsmngr.HostAssignments{} - - listOpts := ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - ProjectHostAssignments(listOpts.ProjectID, listOpts.newServerTypeOptions()). - Return(expected, nil). - Times(1) - - if err := listOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.ProjectID, flag.Output, flag.Page, flag.Limit, flag.EndDate, flag.StartDate}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/projects/projects.go b/internal/cli/opsmanager/serverusage/projects/projects.go deleted file mode 100644 index d6673298a3..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/projects.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package projects - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/serverusage/projects/hosts" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/serverusage/projects/servertype" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "projects" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage your server usage for a project.", - } - - cmd.AddCommand( - servertype.Builder(), - hosts.Builder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/projects/projects_test.go b/internal/cli/opsmanager/serverusage/projects/projects_test.go deleted file mode 100644 index 034bf3f30a..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/projects_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package projects - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/projects/servertype/describe.go b/internal/cli/opsmanager/serverusage/projects/servertype/describe.go deleted file mode 100644 index 8fd455c3e7..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/servertype/describe.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package servertype - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -var getTemplate = `NAME LABEL -{{.Name}} {{.Label}} -` - -type DescribeOpts struct { - cli.OutputOpts - cli.GlobalOpts - store store.ProjectServerTypeGetter -} - -func (opts *DescribeOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *DescribeOpts) Run() error { - r, err := opts.store.ProjectServerType(opts.ConfigProjectID()) - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli ops-manager serverUsage project(s) serverType get [--orgId orgId]. -func DescribeBuilder() *cobra.Command { - opts := &DescribeOpts{} - cmd := &cobra.Command{ - Use: "describe", - Aliases: []string{"get"}, - Short: "Get the default server type for a project.", - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - opts.InitOutput(cmd.OutOrStdout(), getTemplate), - ) - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/projects/servertype/describe_test.go b/internal/cli/opsmanager/serverusage/projects/servertype/describe_test.go deleted file mode 100644 index a2bb5df211..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/servertype/describe_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package servertype - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestGetOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectServerTypeGetter(ctrl) - - expected := &opsmngr.ServerType{} - - opts := &DescribeOpts{ - store: mockStore, - } - - mockStore. - EXPECT().ProjectServerType(opts.ConfigProjectID()). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestDescribeBuilder(t *testing.T) { - test.CmdValidator( - t, - DescribeBuilder(), - 0, - []string{flag.Output, flag.ProjectID}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/projects/servertype/server_type.go b/internal/cli/opsmanager/serverusage/projects/servertype/server_type.go deleted file mode 100644 index 3b0e5b7533..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/servertype/server_type.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package servertype - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "serverType" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage your server type for a project.", - } - - cmd.AddCommand( - DescribeBuilder(), - SetBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/projects/servertype/server_type_test.go b/internal/cli/opsmanager/serverusage/projects/servertype/server_type_test.go deleted file mode 100644 index 6f47b62322..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/servertype/server_type_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package servertype - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 2, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/projects/servertype/set.go b/internal/cli/opsmanager/serverusage/projects/servertype/set.go deleted file mode 100644 index 6488ab1ada..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/servertype/set.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package servertype - -import ( - "context" - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" - "go.mongodb.org/ops-manager/opsmngr" -) - -type SetOpts struct { - cli.GlobalOpts - store store.ProjectServerTypeUpdater - serverType string -} - -func (opts *SetOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -func (opts *SetOpts) Run() error { - err := opts.store.UpdateProjectServerType(opts.ConfigProjectID(), opts.newServerTypeRequest()) - if err != nil { - return err - } - fmt.Printf("Serve type %s correctly set\n", opts.serverType) - return nil -} - -func (opts *SetOpts) newServerTypeRequest() *opsmngr.ServerTypeRequest { - return &opsmngr.ServerTypeRequest{ - ServerType: &opsmngr.ServerType{ - Name: opts.serverType, - }, - } -} - -// mongocli ops-manager serverUsage projects(s) serverType set [--projectId projectId]. -func SetBuilder() *cobra.Command { - opts := &SetOpts{} - cmd := &cobra.Command{ - Use: "set ", - Args: require.ExactValidArgs(1), - ValidArgs: []string{"DEV_SERVER", "TEST_SERVER", "PRODUCTION_SERVER", "RAM_POOL"}, - Short: "Set the default server type for a project.", - Annotations: map[string]string{ - "typeDesc": "Server type to set.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - return opts.PreRunE( - opts.ValidateProjectID, - opts.initStore(cmd.Context()), - ) - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.serverType = args[0] - return opts.Run() - }, - } - - cmd.Flags().StringVar(&opts.ProjectID, flag.ProjectID, "", usage.ProjectID) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/projects/servertype/set_test.go b/internal/cli/opsmanager/serverusage/projects/servertype/set_test.go deleted file mode 100644 index ab1f68e584..0000000000 --- a/internal/cli/opsmanager/serverusage/projects/servertype/set_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package servertype - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestSetOpts_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockProjectServerTypeUpdater(ctrl) - - opts := &SetOpts{ - store: mockStore, - } - - mockStore. - EXPECT().UpdateProjectServerType(opts.ConfigProjectID(), opts.newServerTypeRequest()). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestSetBuilder(t *testing.T) { - test.CmdValidator( - t, - SetBuilder(), - 0, - []string{flag.ProjectID}, - ) -} diff --git a/internal/cli/opsmanager/serverusage/server_usage.go b/internal/cli/opsmanager/serverusage/server_usage.go deleted file mode 100644 index b250d05dd7..0000000000 --- a/internal/cli/opsmanager/serverusage/server_usage.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package serverusage - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/serverusage/organizations" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager/serverusage/projects" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "serverUsage" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage your server usage.", - } - - cmd.AddCommand( - projects.Builder(), - organizations.Builder(), - CaptureBuilder(), - DownloadBuilder(), - ) - - return cmd -} diff --git a/internal/cli/opsmanager/serverusage/server_usage_test.go b/internal/cli/opsmanager/serverusage/server_usage_test.go deleted file mode 100644 index f30b91984f..0000000000 --- a/internal/cli/opsmanager/serverusage/server_usage_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package serverusage - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 4, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/softwarecomponents/list.go b/internal/cli/opsmanager/softwarecomponents/list.go deleted file mode 100644 index d9e278fe7c..0000000000 --- a/internal/cli/opsmanager/softwarecomponents/list.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package softwarecompotents - -import ( - "context" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -type ListOpts struct { - cli.OutputOpts - store store.AgentGlobalVersionsLister -} - -func (opts *ListOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - return err - } -} - -var listTemplate = `AUTOMATION VERSION BI CONNECTOR VERSION MONGODB TOOLS VERSION -{{.AutomationVersion}} {{.BiConnectorVersion}} {{.MongoDBToolsVersion}} -` - -func (opts *ListOpts) Run() error { - r, err := opts.store.AgentGlobalVersions() - if err != nil { - return err - } - - return opts.Print(r) -} - -// mongocli om softwareComponent(s) list. -func ListBuilder() *cobra.Command { - opts := &ListOpts{} - opts.Template = listTemplate - cmd := &cobra.Command{ - Use: "list", - Aliases: []string{"ls"}, - Short: "List versions of MongoDB Agent, MongoDB Tools, and BI Connector in your environment.", - Args: require.NoArgs, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, _ []string) error { - return opts.Run() - }, - } - - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/softwarecomponents/list_test.go b/internal/cli/opsmanager/softwarecomponents/list_test.go deleted file mode 100644 index f58507f824..0000000000 --- a/internal/cli/opsmanager/softwarecomponents/list_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package softwarecompotents - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestList_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockAgentGlobalVersionsLister(ctrl) - - expected := &opsmngr.SoftwareVersions{} - - opts := ListOpts{ - store: mockStore, - } - - mockStore. - EXPECT(). - AgentGlobalVersions(). - Return(expected, nil). - Times(1) - - if err := opts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } -} - -func TestListBuilder(t *testing.T) { - test.CmdValidator( - t, - ListBuilder(), - 0, - []string{flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/softwarecomponents/software_components.go b/internal/cli/opsmanager/softwarecomponents/software_components.go deleted file mode 100644 index fc9e72b6d5..0000000000 --- a/internal/cli/opsmanager/softwarecomponents/software_components.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package softwarecompotents - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "softwareComponents" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage earliest and latest versions of MongoDB Agent, MongoDB Tools, and BI Connector in your environment.", - } - - cmd.AddCommand(ListBuilder()) - return cmd -} diff --git a/internal/cli/opsmanager/softwarecomponents/software_components_test.go b/internal/cli/opsmanager/softwarecomponents/software_components_test.go deleted file mode 100644 index c956bec6e2..0000000000 --- a/internal/cli/opsmanager/softwarecomponents/software_components_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package softwarecompotents - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/opsmanager/versionmanifest/update.go b/internal/cli/opsmanager/versionmanifest/update.go deleted file mode 100644 index 800ef4c2da..0000000000 --- a/internal/cli/opsmanager/versionmanifest/update.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package versionmanifest - -import ( - "context" - "fmt" - "strings" - - "github.com/Masterminds/semver/v3" - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/require" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/store" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/spf13/cobra" -) - -const updateTemplate = "Version manifest updated.\n" - -type UpdateOpts struct { - cli.OutputOpts - versionManifest string - SkipVersionValidation bool - store store.VersionManifestUpdaterServiceVersionDescriber - storeStaticPath store.VersionManifestGetter -} - -func (opts *UpdateOpts) initStore(ctx context.Context) func() error { - return func() error { - var err error - opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)) - if err != nil { - return err - } - opts.storeStaticPath, err = store.NewVersionManifest(ctx, config.Default()) - return err - } -} - -func (opts *UpdateOpts) Run() error { - svManifest, err := semver.NewVersion(opts.versionManifest) - if err != nil { - return fmt.Errorf("version '%s' is invalid, use the format x.y", opts.versionManifest) - } - - if !opts.SkipVersionValidation { - v, e := opts.store.ServiceVersion() - if e != nil { - return e - } - - svOM, e := cli.ParseServiceVersion(v) - if e != nil { - return err - } - - if svOM.Compare(svManifest) != 0 { - return fmt.Errorf("version '%s' is incompatible with Ops Manager version '%s'", opts.versionManifest, v.Version) - } - } - - versionManifest, err := opts.storeStaticPath.GetVersionManifest(opts.version()) - if err != nil { - return err - } - - r, err := opts.store.UpdateVersionManifest(versionManifest) - if err != nil { - return err - } - - return opts.Print(r) -} - -func (opts *UpdateOpts) version() string { - if strings.Contains(opts.versionManifest, ".json") { - return opts.versionManifest - } - return opts.versionManifest + ".json" -} - -// mongocli om versionManifest(s) update . -func UpdateBuilder() *cobra.Command { - opts := &UpdateOpts{} - opts.Template = updateTemplate - cmd := &cobra.Command{ - Use: "update ", - Short: "Update Ops Manager version manifest.", - Args: require.ExactArgs(1), - Annotations: map[string]string{ - "versionDesc": "Manifest version.", - }, - PreRunE: func(cmd *cobra.Command, _ []string) error { - opts.OutWriter = cmd.OutOrStdout() - return opts.initStore(cmd.Context())() - }, - RunE: func(_ *cobra.Command, args []string) error { - opts.versionManifest = args[0] - return opts.Run() - }, - } - - cmd.Flags().BoolVar(&opts.SkipVersionValidation, flag.Force, false, usage.ForceVersionManifest) - cmd.Flags().StringVarP(&opts.Output, flag.Output, flag.OutputShort, "", usage.FormatOut) - _ = cmd.RegisterFlagCompletionFunc(flag.Output, opts.AutoCompleteOutputFlag()) - - return cmd -} diff --git a/internal/cli/opsmanager/versionmanifest/update_test.go b/internal/cli/opsmanager/versionmanifest/update_test.go deleted file mode 100644 index cc7ddd158e..0000000000 --- a/internal/cli/opsmanager/versionmanifest/update_test.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package versionmanifest - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/test" - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestVersionManifestUpdate_Run(t *testing.T) { - ctrl := gomock.NewController(t) - mockStore := mocks.NewMockVersionManifestUpdaterServiceVersionDescriber(ctrl) - mockStoreStaticPath := mocks.NewMockVersionManifestGetter(ctrl) - - tests := []struct { - name string - versionManifest string - omVersion string - wantErr bool - }{ - { - name: "OM 4.4", - versionManifest: "4.4", - omVersion: "4.4.0.100.20210101T0000Z", - wantErr: false, - }, - { - name: "Invalid Format", - versionManifest: "bad version", - omVersion: "", - wantErr: true, - }, - { - name: "Invalid OM Version", - versionManifest: "4.4", - omVersion: "5.0.0.100.20210101T0000Z", - wantErr: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - updateOpts := &UpdateOpts{ - versionManifest: tt.versionManifest, - store: mockStore, - storeStaticPath: mockStoreStaticPath, - } - - if tt.omVersion != "" { - mockStore. - EXPECT().ServiceVersion(). - Return(&opsmngr.ServiceVersion{Version: tt.omVersion}, nil). - Times(1) - } - - if tt.wantErr { - if err := updateOpts.Run(); err == nil { - t.Fatalf("Run() expected error to be returned") - } - return - } - - mockStoreStaticPath. - EXPECT().GetVersionManifest(updateOpts.version()). - Return(&opsmngr.VersionManifest{}, nil). - Times(1) - - mockStore. - EXPECT().UpdateVersionManifest(&opsmngr.VersionManifest{}). - Return(&opsmngr.VersionManifest{}, nil). - Times(1) - - if err := updateOpts.Run(); err != nil { - t.Fatalf("Run() unexpected error: %v", err) - } - }) - } -} - -func TestUpdateBuilder(t *testing.T) { - test.CmdValidator( - t, - UpdateBuilder(), - 0, - []string{flag.Output}, - ) -} diff --git a/internal/cli/opsmanager/versionmanifest/version_manifest.go b/internal/cli/opsmanager/versionmanifest/version_manifest.go deleted file mode 100644 index 56db228d75..0000000000 --- a/internal/cli/opsmanager/versionmanifest/version_manifest.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package versionmanifest - -import ( - "github.com/mongodb/mongodb-atlas-cli/internal/cli" - "github.com/spf13/cobra" -) - -func Builder() *cobra.Command { - const use = "versionManifest" - cmd := &cobra.Command{ - Use: use, - Aliases: cli.GenerateAliases(use), - Short: "Manage Ops Manager version manifest.", - } - - cmd.AddCommand(UpdateBuilder()) - return cmd -} diff --git a/internal/cli/opsmanager/versionmanifest/version_manifest_test.go b/internal/cli/opsmanager/versionmanifest/version_manifest_test.go deleted file mode 100644 index 007d9794a5..0000000000 --- a/internal/cli/opsmanager/versionmanifest/version_manifest_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package versionmanifest - -import ( - "testing" - - "github.com/mongodb/mongodb-atlas-cli/internal/test" -) - -func TestVersionManifestBuilder(t *testing.T) { - test.CmdValidator( - t, - Builder(), - 1, - []string{}, - ) -} diff --git a/internal/cli/parse_service_version.go b/internal/cli/parse_service_version.go deleted file mode 100644 index 0737c29aa0..0000000000 --- a/internal/cli/parse_service_version.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cli - -import ( - "strings" - - "github.com/Masterminds/semver/v3" - "go.mongodb.org/ops-manager/opsmngr" -) - -// ParseServiceVersion parses service version into semver.Version. -func ParseServiceVersion(v *opsmngr.ServiceVersion) (*semver.Version, error) { - versionParts := strings.Split(v.Version, ".") - - const maxVersionParts = 2 - - if len(versionParts) > maxVersionParts { - versionParts = versionParts[0:maxVersionParts] // ops manager versions are not semantic this is converting it to x.y - } - - newVersion := strings.Join(versionParts, ".") - - return semver.NewVersion(newVersion) -} diff --git a/internal/cli/parse_service_version_test.go b/internal/cli/parse_service_version_test.go deleted file mode 100644 index 74e1c000f2..0000000000 --- a/internal/cli/parse_service_version_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package cli - -import ( - "testing" - - "go.mongodb.org/ops-manager/opsmngr" -) - -func TestParseServiceVersion(t *testing.T) { - tests := []struct { - name string - serviceVersion *opsmngr.ServiceVersion - expected string - wantErr bool - }{ - { - name: "OM 5.0", - serviceVersion: &opsmngr.ServiceVersion{Version: "5.0.0.100.20210101T0000Z"}, - expected: "5.0.0", - wantErr: false, - }, - { - name: "OM 5.0-rc1", - serviceVersion: &opsmngr.ServiceVersion{Version: "5.0.0-rc1.100.20210101T0000Z"}, - expected: "5.0.0", - wantErr: false, - }, - { - name: "OM 5.0.1", - serviceVersion: &opsmngr.ServiceVersion{Version: "5.0.1.100.20210101T0000Z"}, - expected: "5.0.0", - wantErr: false, - }, - { - name: "master", - serviceVersion: &opsmngr.ServiceVersion{Version: "master"}, - expected: "", - wantErr: true, - }, - { - name: "v20210101", - serviceVersion: &opsmngr.ServiceVersion{Version: "v20210101"}, - expected: "20210101.0.0", - wantErr: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r, err := ParseServiceVersion(tt.serviceVersion) - if tt.wantErr { - if err == nil { - t.Fatalf("Run() expected error to be returned") - } - return - } - - if err != nil { - t.Fatalf("ParseServiceVersion() unexpected error: %v", err) - } - if r.String() != tt.expected { - t.Fatalf("ParseServiceVersion() expected: %v got: %v", tt.expected, r.String()) - } - }) - } -} diff --git a/internal/cli/root/mongocli/builder.go b/internal/cli/root/mongocli/builder.go deleted file mode 100644 index 4fb204591a..0000000000 --- a/internal/cli/root/mongocli/builder.go +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mongocli - -import ( - "fmt" - "io" - "runtime" - "strings" - "time" - - "github.com/mongodb/mongodb-atlas-cli/internal/cli/atlas" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/auth" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/cloudmanager" - cliconfig "github.com/mongodb/mongodb-atlas-cli/internal/cli/config" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/iam" - "github.com/mongodb/mongodb-atlas-cli/internal/cli/opsmanager" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/flag" - "github.com/mongodb/mongodb-atlas-cli/internal/homebrew" - "github.com/mongodb/mongodb-atlas-cli/internal/latestrelease" - "github.com/mongodb/mongodb-atlas-cli/internal/search" - "github.com/mongodb/mongodb-atlas-cli/internal/terminal" - "github.com/mongodb/mongodb-atlas-cli/internal/usage" - "github.com/mongodb/mongodb-atlas-cli/internal/version" - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -type Notifier struct { - currentVersion string - finder latestrelease.VersionFinder - filesystem afero.Fs - writer io.Writer -} - -// Builder conditionally adds children commands as needed. -// This is important in particular for Atlas as it dynamically sets flags for cluster creation and -// this can be slow to timeout on environments with limited internet access (Ops Manager). -func Builder(profile *string, argsWithoutProg []string) *cobra.Command { - rootCmd := &cobra.Command{ - Version: version.Version, - Use: config.ToolName, - Short: "CLI tool to manage your MongoDB Cloud", - Long: fmt.Sprintf("Use %s command help for information on a specific command", config.ToolName), - Example: ` # Display the help menu for the config command: - mongocli config --help -`, - SilenceUsage: true, - Annotations: map[string]string{ - "toc": "true", - }, - PersistentPostRun: func(cmd *cobra.Command, _ []string) { - // we don't run the release alert feature on the completion command - if strings.HasPrefix(cmd.CommandPath(), "mongocli completion") { - return - } - - w := cmd.ErrOrStderr() - fs := afero.NewOsFs() - f, _ := latestrelease.NewVersionFinder(fs, version.NewReleaseVersionDescriber()) - - notifier := &Notifier{ - currentVersion: latestrelease.VersionFromTag(version.Version, config.ToolName), - finder: f, - filesystem: fs, - writer: w, - } - - if check, isHb := notifier.shouldCheck(); check { - _ = notifier.notifyIfApplicable(isHb) - } - }, - } - rootCmd.SetVersionTemplate(formattedVersion()) - hasArgs := len(argsWithoutProg) != 0 - - if hasArgs && (argsWithoutProg[0] == "--version" || argsWithoutProg[0] == "-v") { - return rootCmd - } - rootCmd.AddCommand(cliconfig.Builder()) - - shouldIncludeAtlas := []string{ - atlas.Use, - "help", - "--help", - "-h", - "completion", - "__complete", - } - if !hasArgs || search.StringInSlice(shouldIncludeAtlas, argsWithoutProg[0]) { - rootCmd.AddCommand(atlas.Builder()) - } - // hidden shortcuts - loginCmd := auth.LoginBuilder() - loginCmd.Hidden = true - logoutCmd := auth.LogoutBuilder() - logoutCmd.Hidden = true - whoCmd := auth.WhoAmIBuilder() - whoCmd.Hidden = true - - rootCmd.AddCommand( - cloudmanager.Builder(), - opsmanager.Builder(), - iam.Builder(), - auth.Builder(), - loginCmd, - logoutCmd, - whoCmd, - ) - - rootCmd.PersistentFlags().StringVarP(profile, flag.Profile, flag.ProfileShort, "", usage.Profile) - _ = rootCmd.RegisterFlagCompletionFunc(flag.Profile, func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { - return config.List(), cobra.ShellCompDirectiveDefault - }) - return rootCmd -} - -const verTemplate = `%s version: %s -git version: %s -Go version: %s - os: %s - arch: %s - compiler: %s -` - -func formattedVersion() string { - return fmt.Sprintf(verTemplate, - config.ToolName, - version.Version, - version.GitCommit, - runtime.Version(), - runtime.GOOS, - runtime.GOARCH, - runtime.Compiler) -} - -func (n *Notifier) shouldCheck() (shouldCheck, isHb bool) { - shouldCheck = !config.SkipUpdateCheck() && terminal.IsTerminal(n.writer) - isHb = false - - if !shouldCheck { - return shouldCheck, isHb - } - - c, _ := homebrew.NewChecker(n.filesystem) - isHb = c.IsHomebrew() - - return shouldCheck, isHb -} - -func (n *Notifier) notifyIfApplicable(isHb bool) error { - release, err := n.finder.Find() - if err != nil || release == nil { - return err - } - - // homebrew is an external dependency we give them 24h to have the cli available there - if isHb && !isAtLeast24HoursPast(release.PublishedAt) { - return nil - } - - var upgradeInstructions string - if isHb { - upgradeInstructions = fmt.Sprintf(`To upgrade, run "brew update && brew upgrade %s".`, homebrew.FormulaName(config.ToolName)) - } else { - upgradeInstructions = "To upgrade, see: https://dochub.mongodb.org/core/install-mongocli." - } - - newVersionTemplate := ` -A new version of %s is available '%s'! -%s - -To disable this alert, run "%s config set skip_update_check true". -` - _, err = fmt.Fprintf(n.writer, newVersionTemplate, config.ToolName, release.Version, upgradeInstructions, config.BinName()) - return err -} - -func isAtLeast24HoursPast(t time.Time) bool { - return !t.IsZero() && time.Since(t) >= time.Hour*24 -} diff --git a/internal/cli/root/mongocli/builder_test.go b/internal/cli/root/mongocli/builder_test.go deleted file mode 100644 index 3048fcab0a..0000000000 --- a/internal/cli/root/mongocli/builder_test.go +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package mongocli - -import ( - "bytes" - "fmt" - "testing" - - "github.com/golang/mock/gomock" - "github.com/google/go-github/v50/github" - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/latestrelease" - "github.com/mongodb/mongodb-atlas-cli/internal/mocks" - "github.com/mongodb/mongodb-atlas-cli/internal/version" - "github.com/spf13/afero" -) - -func TestBuilder(t *testing.T) { - type args struct { - argsWithoutProg []string - } - tests := []struct { - name string - args args - want int - }{ - { - name: "atlas", - want: 9, - args: args{ - argsWithoutProg: []string{"atlas"}, - }, - }, - { - name: "ops-manager", - want: 8, - args: args{ - argsWithoutProg: []string{"ops-manager"}, - }, - }, - { - name: "cloud-manager", - want: 8, - args: args{ - argsWithoutProg: []string{"cloud-manager"}, - }, - }, - { - name: "ops-manager alias", - want: 8, - args: args{ - argsWithoutProg: []string{"om"}, - }, - }, - { - name: "cloud-manager alias", - want: 8, - args: args{ - argsWithoutProg: []string{"cm"}, - }, - }, - { - name: "iam", - want: 8, - args: args{ - argsWithoutProg: []string{"iam"}, - }, - }, - { - name: "empty", - want: 9, - args: args{ - argsWithoutProg: []string{}, - }, - }, - { - name: "autocomplete", - want: 9, - args: args{ - argsWithoutProg: []string{"__complete"}, - }, - }, - { - name: "completion", - want: 9, - args: args{ - argsWithoutProg: []string{"completion"}, - }, - }, - { - name: "fig-autocompletion", - want: 9, - args: args{ - argsWithoutProg: []string{}, - }, - }, - { - name: "--version", - want: 9, - args: args{ - argsWithoutProg: []string{"completion"}, - }, - }, - } - var profile string - for _, tt := range tests { - name := tt.name - args := tt.args - want := tt.want - t.Run(name, func(t *testing.T) { - got := Builder(&profile, args.argsWithoutProg) - if len(got.Commands()) != want { - t.Fatalf("got=%d, want=%d", len(got.Commands()), want) - } - }) - } -} - -func TestOutputOpts_notifyIfApplicable(t *testing.T) { - tests := testCases() - for _, tt := range tests { - t.Run(fmt.Sprintf("%v/%v", tt.currentVersion, tt.release), func(t *testing.T) { - prevVersion := version.Version - version.Version = tt.currentVersion - defer func() { - version.Version = prevVersion - }() - - ctrl := gomock.NewController(t) - mockDescriber := mocks.NewMockReleaseVersionDescriber(ctrl) - - mockDescriber. - EXPECT(). - LatestWithCriteria(gomock.Any(), gomock.Any(), gomock.Any()). - Return(tt.release, nil). - Times(1) - - bufOut := new(bytes.Buffer) - fs := afero.NewMemMapFs() - finder, _ := latestrelease.NewVersionFinder(fs, mockDescriber) - - notifier := &Notifier{ - currentVersion: latestrelease.VersionFromTag(version.Version, config.ToolName), - finder: finder, - filesystem: fs, - writer: bufOut, - } - - if err := notifier.notifyIfApplicable(false); err != nil { - t.Errorf("notifyIfApplicable() unexpected error:%v", err) - } - - v := "" - if tt.release != nil { - v = latestrelease.VersionFromTag(tt.release.GetTagName(), config.ToolName) - } - - want := "" - if tt.expectNewVersion { - want = fmt.Sprintf(` -A new version of %s is available '%v'! -To upgrade, see: https://dochub.mongodb.org/core/install-%s. - -To disable this alert, run "%s config set skip_update_check true". -`, config.ToolName, v, config.ToolName, config.BinName()) - } - - if got := bufOut.String(); got != want { - t.Errorf("notifyIfApplicable() got = %v, want %v", got, want) - } - }) - } -} - -type testCase struct { - currentVersion string - expectNewVersion bool - release *github.RepositoryRelease -} - -func testCases() []testCase { - f := false - mcliV := "mongocli/v2.0.0" - mcliOldV := "v2.0.0" - - tests := []testCase{ - { - currentVersion: "v1.0.0", - expectNewVersion: true, - release: &github.RepositoryRelease{TagName: &mcliOldV, Prerelease: &f, Draft: &f}, - }, - { - currentVersion: "mongocli/v1.0.0", - expectNewVersion: true, - release: &github.RepositoryRelease{TagName: &mcliOldV, Prerelease: &f, Draft: &f}, - }, - { - currentVersion: "v1.0.0", - expectNewVersion: true, - release: &github.RepositoryRelease{TagName: &mcliV, Prerelease: &f, Draft: &f}, - }, - { - currentVersion: "v3.0.0", - expectNewVersion: false, - release: &github.RepositoryRelease{TagName: &mcliOldV, Prerelease: &f, Draft: &f}, - }, - { - currentVersion: "v3.0.0-123", - expectNewVersion: false, - release: &github.RepositoryRelease{TagName: &mcliV, Prerelease: &f, Draft: &f}, - }, - { - currentVersion: "v2.0.0", - expectNewVersion: false, - release: &github.RepositoryRelease{TagName: &mcliV, Prerelease: &f, Draft: &f}, - }, - { - currentVersion: "v2.0.0-123", - expectNewVersion: false, - release: &github.RepositoryRelease{TagName: &mcliV, Prerelease: &f, Draft: &f}, - }, - { - currentVersion: "v3.0.0-123", - expectNewVersion: false, - release: nil, - }, - } - return tests -} diff --git a/internal/convert/automation_config.go b/internal/convert/automation_config.go deleted file mode 100644 index 686993fb49..0000000000 --- a/internal/convert/automation_config.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package convert - -import ( - "go.mongodb.org/ops-manager/opsmngr" -) - -// FromAutomationConfig convert from opsmngr.AutomationConfig format to []*ClusterConfig -// the given opsmngr.AutomationConfig will be modified. -func FromAutomationConfig(c *opsmngr.AutomationConfig) []*ClusterConfig { - out := make([]*ClusterConfig, 0, len(c.ReplicaSets)) - - for _, s := range c.Sharding { - newSC := newShardedCluster(s) - for j, ss := range s.Shards { - id := ss.ID - newSC.Shards[j] = newRSConfig(c, id) - } - - newSC.Config = newRSConfig(c, s.ConfigServerReplica) - for j := len(c.Processes) - 1; j >= 0; j-- { - p := c.Processes[j] - if p.Cluster == s.Name { - newSC.Mongos = append(newSC.Mongos, newMongosProcessConfig(p)) - newSC.addToMongoURI(p) - c.Processes = removeProcess(c.Processes, j) - } - } - out = append(out, newSC) - } - for _, rs := range c.ReplicaSets { - newRS := newReplicaSetCluster(rs.ID, len(rs.Members)) - for j, m := range rs.Members { - for k := len(c.Processes) - 1; k >= 0; k-- { - p := c.Processes[k] - if p.Name == m.Host { - newRS.Processes[j] = newReplicaSetProcessConfig(&rs.Members[j], p) - newRS.addToMongoURI(p) - c.Processes = removeProcess(c.Processes, k) - } - } - } - out = append(out, newRS) - } - - return out -} - -func removeProcess(in []*opsmngr.Process, i int) []*opsmngr.Process { - return append(in[:i], in[i+1:]...) -} diff --git a/internal/convert/automation_config_test.go b/internal/convert/automation_config_test.go deleted file mode 100644 index 17f64cba46..0000000000 --- a/internal/convert/automation_config_test.go +++ /dev/null @@ -1,403 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build unit - -package convert - -import ( - "testing" - - "github.com/go-test/deep" - "github.com/mongodb/mongodb-atlas-cli/internal/pointer" - "github.com/mongodb/mongodb-atlas-cli/internal/test/fixture" -) - -func TestFromAutomationConfig(t *testing.T) { - name := "cluster_1" - fipsMode := true - t.Run("replica set", func(t *testing.T) { - t.Parallel() - config := fixture.AutomationConfigWithOneReplicaSet(name, false) - expected := []*ClusterConfig{ - { - RSConfig: RSConfig{ - Name: name, - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data/db/", - Disabled: false, - Hidden: pointer.Get(false), - Hostname: "host0", - LogPath: "/data/db/mongodb.log", - LogDestination: file, - AuditLogDestination: file, - AuditLogPath: "/data/db/audit.log", - Port: 27017, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SlaveDelay: pointer.Get[float64](1), - SecondaryDelaySecs: pointer.Get[float64](1), - Votes: pointer.Get[float64](1), - FeatureCompatibilityVersion: "4.2", - Version: "4.2.2", - Name: name + "_0", - OplogSizeMB: pointer.Get(10), - TLS: &TLS{ - CAFile: "CAFile", - CertificateKeyFile: "CertificateKeyFile", - CertificateKeyFilePassword: "CertificateKeyFilePassword", - CertificateSelector: "CertificateSelector", - ClusterCertificateSelector: "ClusterCertificateSelector", - ClusterFile: "ClusterFile", - ClusterPassword: "ClusterPassword", - CRLFile: "CRLFile", - DisabledProtocols: "DisabledProtocols", - FIPSMode: &fipsMode, - Mode: "Mode", - PEMKeyFile: "PEMKeyFile", - }, - Security: &map[string]interface{}{ - "test": "test", - }, - }, - }, - }, - MongoURI: "mongodb://host0:27017", - }, - } - - result := FromAutomationConfig(config) - if diff := deep.Equal(result, expected); diff != nil { - t.Error(diff) - } - }) - t.Run("sharded cluster", func(t *testing.T) { - t.Parallel() - config := fixture.AutomationConfigWithOneShardedCluster(name, false) - - expected := []*ClusterConfig{ - { - MongoURI: "mongodb://example:3", - RSConfig: RSConfig{ - Name: name, - }, - Shards: []*RSConfig{ - { - Name: "myShard_0", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data/myShard_0", - Disabled: false, - Hidden: pointer.Get(false), - Hostname: "example", - LogPath: "/log/myShard_0", - LogDestination: file, - Port: 1, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SlaveDelay: pointer.Get[float64](1), - SecondaryDelaySecs: pointer.Get[float64](1), - Votes: pointer.Get[float64](1), - FeatureCompatibilityVersion: "4.2", - Version: "4.2.2", - Name: name + "_myShard_0_0", - }, - }, - }, - }, - Config: &RSConfig{ - Name: "configRS", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data/configRS", - Disabled: false, - Hidden: pointer.Get(false), - Hostname: "example", - LogPath: "/log/configRS", - LogDestination: file, - Port: 2, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SlaveDelay: pointer.Get[float64](1), - SecondaryDelaySecs: pointer.Get[float64](1), - Votes: pointer.Get[float64](1), - FeatureCompatibilityVersion: "4.2", - Version: "4.2.2", - Name: name + "_configRS_1", - }, - }, - }, - Mongos: []*ProcessConfig{ - { - Disabled: false, - Hostname: "example", - LogPath: "/log/mongos", - LogDestination: file, - Port: 3, - ProcessType: "mongos", - FeatureCompatibilityVersion: "4.2", - Version: "4.2.2", - Name: name + "_mongos_2", - }, - }, - }, - } - result := FromAutomationConfig(config) - if diff := deep.Equal(result, expected); diff != nil { - t.Error(diff) - } - }) - t.Run("Sharded multi mongos cluster", func(t *testing.T) { - t.Parallel() - config := fixture.MultiMongosAutomationConfig() - - engineConfig := make(map[string]interface{}) - engineConfig["cacheSizeGB"] = 0.5 - expected := []*ClusterConfig{ - { - MongoURI: "mongodb://ip-172-31-43-144.eu-west-1.compute.internal:27021,ip-172-31-39-241.eu-west-1.compute.internal:27021,ip-172-31-37-180.eu-west-1.compute.internal:27021,ip-172-31-35-62.eu-west-1.compute.internal:27021", - RSConfig: RSConfig{ - Name: "myCluster", - }, - Shards: []*RSConfig{ - { - Name: "myShard_0", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data", - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hidden: pointer.Get(false), - Hostname: "ip-172-31-33-34.eu-west-1.compute.internal", - LogPath: "/data/mongodb.log", - Name: "myCluster_myShard_0_1", - LogDestination: "file", - Port: 27017, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SecondaryDelaySecs: pointer.Get[float64](0), - Votes: pointer.Get[float64](1), - Version: "6.0.6-ent", - WiredTiger: &engineConfig, - }, - }, - }, - { - Name: "myShard_1", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data", - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hidden: pointer.Get(false), - Hostname: "ip-172-31-35-62.eu-west-1.compute.internal", - LogPath: "/data/mongodb.log", - LogDestination: "file", - Name: "myCluster_myShard_1_2", - Port: 27017, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SecondaryDelaySecs: pointer.Get[float64](0), - Votes: pointer.Get[float64](1), - Version: "6.0.6-ent", - WiredTiger: &engineConfig, - }, - }, - }, - { - Name: "myShard_2", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data", - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hidden: pointer.Get(false), - Hostname: "ip-172-31-37-180.eu-west-1.compute.internal", - LogPath: "/data/mongodb.log", - LogDestination: "file", - Name: "myCluster_myShard_2_3", - Port: 27017, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SecondaryDelaySecs: pointer.Get[float64](0), - Votes: pointer.Get[float64](1), - Version: "6.0.6-ent", - WiredTiger: &engineConfig, - }, - }, - }, - { - Name: "myShard_3", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data", - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hidden: pointer.Get(false), - Hostname: "ip-172-31-39-241.eu-west-1.compute.internal", - LogPath: "/data/mongodb.log", - LogDestination: "file", - Name: "myCluster_myShard_3_4", - Port: 27017, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SecondaryDelaySecs: pointer.Get[float64](0), - Votes: pointer.Get[float64](1), - Version: "6.0.6-ent", - WiredTiger: &engineConfig, - }, - }, - }, - { - Name: "myShard_4", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data", - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hidden: pointer.Get(false), - Hostname: "ip-172-31-43-144.eu-west-1.compute.internal", - LogPath: "/data/mongodb.log", - LogDestination: "file", - Name: "myCluster_myShard_4_5", - Port: 27017, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SecondaryDelaySecs: pointer.Get[float64](0), - Votes: pointer.Get[float64](1), - Version: "6.0.6-ent", - WiredTiger: &engineConfig, - }, - }, - }, - { - Name: "myShard_5", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data", - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hidden: pointer.Get(false), - Hostname: "ip-172-31-43-246.eu-west-1.compute.internal", - LogPath: "/data/mongodb.log", - LogDestination: "file", - Name: "myCluster_myShard_5_6", - Port: 27017, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SecondaryDelaySecs: pointer.Get[float64](0), - Votes: pointer.Get[float64](1), - Version: "6.0.6-ent", - WiredTiger: &engineConfig, - }, - }, - }, - }, - Config: &RSConfig{ - Name: "configRS", - Processes: []*ProcessConfig{ - { - ArbiterOnly: pointer.Get(false), - BuildIndexes: pointer.Get(true), - DBPath: "/data/n12", - Disabled: false, - Hidden: pointer.Get(false), - Hostname: "ip-172-31-33-34.eu-west-1.compute.internal", - LogPath: "/data/n12/mongodb.log", - LogDestination: "file", - Port: 27020, - Priority: pointer.Get[float64](1), - ProcessType: mongod, - SecondaryDelaySecs: pointer.Get[float64](0), - Votes: pointer.Get[float64](1), - FeatureCompatibilityVersion: "6.0", - Version: "6.0.6-ent", - Name: "myCluster_configRS_7", - WiredTiger: &engineConfig, - }, - }, - }, - Mongos: []*ProcessConfig{ - { - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hostname: "ip-172-31-43-144.eu-west-1.compute.internal", - LogDestination: "file", - LogPath: "/data/n1/mongodb.log", - Name: "myCluster_mongos_11", - Port: 27021, - ProcessType: "mongos", - Version: "6.0.6-ent", - }, - { - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hostname: "ip-172-31-39-241.eu-west-1.compute.internal", - LogDestination: "file", - LogPath: "/data/n1/mongodb.log", - Name: "myCluster_mongos_10", - Port: 27021, - ProcessType: "mongos", - Version: "6.0.6-ent", - }, - { - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hostname: "ip-172-31-37-180.eu-west-1.compute.internal", - LogDestination: "file", - LogPath: "/data/n1/mongodb.log", - Name: "myCluster_mongos_9", - Port: 27021, - ProcessType: "mongos", - Version: "6.0.6-ent", - }, - { - Disabled: false, - FeatureCompatibilityVersion: "6.0", - Hostname: "ip-172-31-35-62.eu-west-1.compute.internal", - LogDestination: "file", - LogPath: "/data/n1/mongodb.log", - Name: "myCluster_mongos_8", - Port: 27021, - ProcessType: "mongos", - Version: "6.0.6-ent", - }, - }, - }, - } - result := FromAutomationConfig(config) - if diff := deep.Equal(result, expected); diff != nil { - t.Error(diff) - } - }) -} diff --git a/internal/convert/cluster_config.go b/internal/convert/cluster_config.go index 6c0be34057..145ef97f5d 100644 --- a/internal/convert/cluster_config.go +++ b/internal/convert/cluster_config.go @@ -15,7 +15,6 @@ package convert import ( - "fmt" "strconv" "go.mongodb.org/ops-manager/opsmngr" @@ -40,26 +39,6 @@ type ClusterConfig struct { Mongos []*ProcessConfig `yaml:"mongos,omitempty" json:"mongos,omitempty"` } -// newReplicaSetCluster when config is a replicaset. -func newReplicaSetCluster(name string, s int) *ClusterConfig { - rs := &ClusterConfig{} - rs.Name = name - rs.Processes = make([]*ProcessConfig, s) - - return rs -} - -// newShardedCluster when config is a sharded cluster. -func newShardedCluster(s *opsmngr.ShardingConfig) *ClusterConfig { - rs := &ClusterConfig{} - rs.Name = s.Name - rs.Shards = make([]*RSConfig, len(s.Shards)) - rs.Mongos = make([]*ProcessConfig, 0, 1) - rs.Tags = s.Tags - - return rs -} - // PatchAutomationConfig adds the ClusterConfig to a opsmngr.AutomationConfig // this method will modify the given AutomationConfig to add the new replica set or sharded cluster information. func (c *ClusterConfig) PatchAutomationConfig(out *opsmngr.AutomationConfig) error { @@ -110,14 +89,6 @@ func (c *ClusterConfig) patchSharding(out *opsmngr.AutomationConfig) error { return nil } -func (c *ClusterConfig) addToMongoURI(p *opsmngr.Process) { - if c.MongoURI == "" { - c.MongoURI = fmt.Sprintf("mongodb://%s:%d", p.Hostname, p.Args26.NET.Port) - } else { - c.MongoURI = fmt.Sprintf("%s,%s:%d", c.MongoURI, p.Hostname, p.Args26.NET.Port) - } -} - func newShard(rsConfig *RSConfig) *opsmngr.Shard { s := &opsmngr.Shard{ ID: rsConfig.Name, diff --git a/internal/convert/rs_config.go b/internal/convert/rs_config.go index 535ee50e0b..bbcb487900 100644 --- a/internal/convert/rs_config.go +++ b/internal/convert/rs_config.go @@ -19,7 +19,6 @@ import ( "github.com/Masterminds/semver/v3" "go.mongodb.org/ops-manager/opsmngr" - "go.mongodb.org/ops-manager/search" ) // RSConfig shared properties of replica sets, config servers, and sharded clusters. @@ -117,30 +116,3 @@ func newReplicaSet(c *RSConfig) (*opsmngr.ReplicaSet, error) { return rs, nil } - -// newRSConfig. -func newRSConfig(in *opsmngr.AutomationConfig, id string) *RSConfig { - rsi, found := search.ReplicaSets(in.ReplicaSets, func(rs *opsmngr.ReplicaSet) bool { - return rs.ID == id - }) - if !found { - return nil - } - rs := in.ReplicaSets[rsi] - out := &RSConfig{ - Name: rs.ID, - Processes: make([]*ProcessConfig, len(rs.Members)), - } - - for i, m := range rs.Members { - for l, p := range in.Processes { - if p.Name == m.Host { - out.Processes[i] = newReplicaSetProcessConfig(&rs.Members[i], p) - in.Processes = append(in.Processes[:l], in.Processes[l+1:]...) - break - } - } - } - in.ReplicaSets = append(in.ReplicaSets[:rsi], in.ReplicaSets[rsi+1:]...) - return out -} diff --git a/internal/mocks/atlas/mock_service_version.go b/internal/mocks/atlas/mock_service_version.go deleted file mode 100644 index cff90953ce..0000000000 --- a/internal/mocks/atlas/mock_service_version.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: ServiceVersionDescriber) - -// Package atlas is a generated GoMock package. -package atlas - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockServiceVersionDescriber is a mock of ServiceVersionDescriber interface. -type MockServiceVersionDescriber struct { - ctrl *gomock.Controller - recorder *MockServiceVersionDescriberMockRecorder -} - -// MockServiceVersionDescriberMockRecorder is the mock recorder for MockServiceVersionDescriber. -type MockServiceVersionDescriberMockRecorder struct { - mock *MockServiceVersionDescriber -} - -// NewMockServiceVersionDescriber creates a new mock instance. -func NewMockServiceVersionDescriber(ctrl *gomock.Controller) *MockServiceVersionDescriber { - mock := &MockServiceVersionDescriber{ctrl: ctrl} - mock.recorder = &MockServiceVersionDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockServiceVersionDescriber) EXPECT() *MockServiceVersionDescriberMockRecorder { - return m.recorder -} - -// ServiceVersion mocks base method. -func (m *MockServiceVersionDescriber) ServiceVersion() (*mongodbatlas.ServiceVersion, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServiceVersion") - ret0, _ := ret[0].(*mongodbatlas.ServiceVersion) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ServiceVersion indicates an expected call of ServiceVersion. -func (mr *MockServiceVersionDescriberMockRecorder) ServiceVersion() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceVersion", reflect.TypeOf((*MockServiceVersionDescriber)(nil).ServiceVersion)) -} diff --git a/internal/mocks/mock_agents.go b/internal/mocks/mock_agents.go deleted file mode 100644 index 080f11137c..0000000000 --- a/internal/mocks/mock_agents.go +++ /dev/null @@ -1,278 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: AgentLister,AgentUpgrader,AgentAPIKeyLister,AgentAPIKeyCreator,AgentAPIKeyDeleter,AgentGlobalVersionsLister,AgentProjectVersionsLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockAgentLister is a mock of AgentLister interface. -type MockAgentLister struct { - ctrl *gomock.Controller - recorder *MockAgentListerMockRecorder -} - -// MockAgentListerMockRecorder is the mock recorder for MockAgentLister. -type MockAgentListerMockRecorder struct { - mock *MockAgentLister -} - -// NewMockAgentLister creates a new mock instance. -func NewMockAgentLister(ctrl *gomock.Controller) *MockAgentLister { - mock := &MockAgentLister{ctrl: ctrl} - mock.recorder = &MockAgentListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAgentLister) EXPECT() *MockAgentListerMockRecorder { - return m.recorder -} - -// Agents mocks base method. -func (m *MockAgentLister) Agents(arg0, arg1 string, arg2 *mongodbatlas.ListOptions) (*opsmngr.Agents, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Agents", arg0, arg1, arg2) - ret0, _ := ret[0].(*opsmngr.Agents) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Agents indicates an expected call of Agents. -func (mr *MockAgentListerMockRecorder) Agents(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Agents", reflect.TypeOf((*MockAgentLister)(nil).Agents), arg0, arg1, arg2) -} - -// MockAgentUpgrader is a mock of AgentUpgrader interface. -type MockAgentUpgrader struct { - ctrl *gomock.Controller - recorder *MockAgentUpgraderMockRecorder -} - -// MockAgentUpgraderMockRecorder is the mock recorder for MockAgentUpgrader. -type MockAgentUpgraderMockRecorder struct { - mock *MockAgentUpgrader -} - -// NewMockAgentUpgrader creates a new mock instance. -func NewMockAgentUpgrader(ctrl *gomock.Controller) *MockAgentUpgrader { - mock := &MockAgentUpgrader{ctrl: ctrl} - mock.recorder = &MockAgentUpgraderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAgentUpgrader) EXPECT() *MockAgentUpgraderMockRecorder { - return m.recorder -} - -// UpgradeAgent mocks base method. -func (m *MockAgentUpgrader) UpgradeAgent(arg0 string) (*opsmngr.AutomationConfigAgent, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpgradeAgent", arg0) - ret0, _ := ret[0].(*opsmngr.AutomationConfigAgent) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpgradeAgent indicates an expected call of UpgradeAgent. -func (mr *MockAgentUpgraderMockRecorder) UpgradeAgent(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpgradeAgent", reflect.TypeOf((*MockAgentUpgrader)(nil).UpgradeAgent), arg0) -} - -// MockAgentAPIKeyLister is a mock of AgentAPIKeyLister interface. -type MockAgentAPIKeyLister struct { - ctrl *gomock.Controller - recorder *MockAgentAPIKeyListerMockRecorder -} - -// MockAgentAPIKeyListerMockRecorder is the mock recorder for MockAgentAPIKeyLister. -type MockAgentAPIKeyListerMockRecorder struct { - mock *MockAgentAPIKeyLister -} - -// NewMockAgentAPIKeyLister creates a new mock instance. -func NewMockAgentAPIKeyLister(ctrl *gomock.Controller) *MockAgentAPIKeyLister { - mock := &MockAgentAPIKeyLister{ctrl: ctrl} - mock.recorder = &MockAgentAPIKeyListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAgentAPIKeyLister) EXPECT() *MockAgentAPIKeyListerMockRecorder { - return m.recorder -} - -// AgentAPIKeys mocks base method. -func (m *MockAgentAPIKeyLister) AgentAPIKeys(arg0 string) ([]*opsmngr.AgentAPIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AgentAPIKeys", arg0) - ret0, _ := ret[0].([]*opsmngr.AgentAPIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AgentAPIKeys indicates an expected call of AgentAPIKeys. -func (mr *MockAgentAPIKeyListerMockRecorder) AgentAPIKeys(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AgentAPIKeys", reflect.TypeOf((*MockAgentAPIKeyLister)(nil).AgentAPIKeys), arg0) -} - -// MockAgentAPIKeyCreator is a mock of AgentAPIKeyCreator interface. -type MockAgentAPIKeyCreator struct { - ctrl *gomock.Controller - recorder *MockAgentAPIKeyCreatorMockRecorder -} - -// MockAgentAPIKeyCreatorMockRecorder is the mock recorder for MockAgentAPIKeyCreator. -type MockAgentAPIKeyCreatorMockRecorder struct { - mock *MockAgentAPIKeyCreator -} - -// NewMockAgentAPIKeyCreator creates a new mock instance. -func NewMockAgentAPIKeyCreator(ctrl *gomock.Controller) *MockAgentAPIKeyCreator { - mock := &MockAgentAPIKeyCreator{ctrl: ctrl} - mock.recorder = &MockAgentAPIKeyCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAgentAPIKeyCreator) EXPECT() *MockAgentAPIKeyCreatorMockRecorder { - return m.recorder -} - -// CreateAgentAPIKey mocks base method. -func (m *MockAgentAPIKeyCreator) CreateAgentAPIKey(arg0 string, arg1 *opsmngr.AgentAPIKeysRequest) (*opsmngr.AgentAPIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateAgentAPIKey", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.AgentAPIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateAgentAPIKey indicates an expected call of CreateAgentAPIKey. -func (mr *MockAgentAPIKeyCreatorMockRecorder) CreateAgentAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAgentAPIKey", reflect.TypeOf((*MockAgentAPIKeyCreator)(nil).CreateAgentAPIKey), arg0, arg1) -} - -// MockAgentAPIKeyDeleter is a mock of AgentAPIKeyDeleter interface. -type MockAgentAPIKeyDeleter struct { - ctrl *gomock.Controller - recorder *MockAgentAPIKeyDeleterMockRecorder -} - -// MockAgentAPIKeyDeleterMockRecorder is the mock recorder for MockAgentAPIKeyDeleter. -type MockAgentAPIKeyDeleterMockRecorder struct { - mock *MockAgentAPIKeyDeleter -} - -// NewMockAgentAPIKeyDeleter creates a new mock instance. -func NewMockAgentAPIKeyDeleter(ctrl *gomock.Controller) *MockAgentAPIKeyDeleter { - mock := &MockAgentAPIKeyDeleter{ctrl: ctrl} - mock.recorder = &MockAgentAPIKeyDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAgentAPIKeyDeleter) EXPECT() *MockAgentAPIKeyDeleterMockRecorder { - return m.recorder -} - -// DeleteAgentAPIKey mocks base method. -func (m *MockAgentAPIKeyDeleter) DeleteAgentAPIKey(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteAgentAPIKey", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteAgentAPIKey indicates an expected call of DeleteAgentAPIKey. -func (mr *MockAgentAPIKeyDeleterMockRecorder) DeleteAgentAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAgentAPIKey", reflect.TypeOf((*MockAgentAPIKeyDeleter)(nil).DeleteAgentAPIKey), arg0, arg1) -} - -// MockAgentGlobalVersionsLister is a mock of AgentGlobalVersionsLister interface. -type MockAgentGlobalVersionsLister struct { - ctrl *gomock.Controller - recorder *MockAgentGlobalVersionsListerMockRecorder -} - -// MockAgentGlobalVersionsListerMockRecorder is the mock recorder for MockAgentGlobalVersionsLister. -type MockAgentGlobalVersionsListerMockRecorder struct { - mock *MockAgentGlobalVersionsLister -} - -// NewMockAgentGlobalVersionsLister creates a new mock instance. -func NewMockAgentGlobalVersionsLister(ctrl *gomock.Controller) *MockAgentGlobalVersionsLister { - mock := &MockAgentGlobalVersionsLister{ctrl: ctrl} - mock.recorder = &MockAgentGlobalVersionsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAgentGlobalVersionsLister) EXPECT() *MockAgentGlobalVersionsListerMockRecorder { - return m.recorder -} - -// AgentGlobalVersions mocks base method. -func (m *MockAgentGlobalVersionsLister) AgentGlobalVersions() (*opsmngr.SoftwareVersions, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AgentGlobalVersions") - ret0, _ := ret[0].(*opsmngr.SoftwareVersions) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AgentGlobalVersions indicates an expected call of AgentGlobalVersions. -func (mr *MockAgentGlobalVersionsListerMockRecorder) AgentGlobalVersions() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AgentGlobalVersions", reflect.TypeOf((*MockAgentGlobalVersionsLister)(nil).AgentGlobalVersions)) -} - -// MockAgentProjectVersionsLister is a mock of AgentProjectVersionsLister interface. -type MockAgentProjectVersionsLister struct { - ctrl *gomock.Controller - recorder *MockAgentProjectVersionsListerMockRecorder -} - -// MockAgentProjectVersionsListerMockRecorder is the mock recorder for MockAgentProjectVersionsLister. -type MockAgentProjectVersionsListerMockRecorder struct { - mock *MockAgentProjectVersionsLister -} - -// NewMockAgentProjectVersionsLister creates a new mock instance. -func NewMockAgentProjectVersionsLister(ctrl *gomock.Controller) *MockAgentProjectVersionsLister { - mock := &MockAgentProjectVersionsLister{ctrl: ctrl} - mock.recorder = &MockAgentProjectVersionsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAgentProjectVersionsLister) EXPECT() *MockAgentProjectVersionsListerMockRecorder { - return m.recorder -} - -// AgentProjectVersions mocks base method. -func (m *MockAgentProjectVersionsLister) AgentProjectVersions(arg0 string) (*opsmngr.AgentVersions, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AgentProjectVersions", arg0) - ret0, _ := ret[0].(*opsmngr.AgentVersions) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AgentProjectVersions indicates an expected call of AgentProjectVersions. -func (mr *MockAgentProjectVersionsListerMockRecorder) AgentProjectVersions(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AgentProjectVersions", reflect.TypeOf((*MockAgentProjectVersionsLister)(nil).AgentProjectVersions), arg0) -} diff --git a/internal/mocks/mock_alert_configuration.go b/internal/mocks/mock_alert_configuration.go deleted file mode 100644 index 2d1bdbc8e8..0000000000 --- a/internal/mocks/mock_alert_configuration.go +++ /dev/null @@ -1,277 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: AlertConfigurationLister,AlertConfigurationCreator,AlertConfigurationDeleter,AlertConfigurationUpdater,MatcherFieldsLister,AlertConfigurationEnabler,AlertConfigurationDisabler) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockAlertConfigurationLister is a mock of AlertConfigurationLister interface. -type MockAlertConfigurationLister struct { - ctrl *gomock.Controller - recorder *MockAlertConfigurationListerMockRecorder -} - -// MockAlertConfigurationListerMockRecorder is the mock recorder for MockAlertConfigurationLister. -type MockAlertConfigurationListerMockRecorder struct { - mock *MockAlertConfigurationLister -} - -// NewMockAlertConfigurationLister creates a new mock instance. -func NewMockAlertConfigurationLister(ctrl *gomock.Controller) *MockAlertConfigurationLister { - mock := &MockAlertConfigurationLister{ctrl: ctrl} - mock.recorder = &MockAlertConfigurationListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertConfigurationLister) EXPECT() *MockAlertConfigurationListerMockRecorder { - return m.recorder -} - -// AlertConfigurations mocks base method. -func (m *MockAlertConfigurationLister) AlertConfigurations(arg0 string, arg1 *mongodbatlas.ListOptions) ([]mongodbatlas.AlertConfiguration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AlertConfigurations", arg0, arg1) - ret0, _ := ret[0].([]mongodbatlas.AlertConfiguration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AlertConfigurations indicates an expected call of AlertConfigurations. -func (mr *MockAlertConfigurationListerMockRecorder) AlertConfigurations(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AlertConfigurations", reflect.TypeOf((*MockAlertConfigurationLister)(nil).AlertConfigurations), arg0, arg1) -} - -// MockAlertConfigurationCreator is a mock of AlertConfigurationCreator interface. -type MockAlertConfigurationCreator struct { - ctrl *gomock.Controller - recorder *MockAlertConfigurationCreatorMockRecorder -} - -// MockAlertConfigurationCreatorMockRecorder is the mock recorder for MockAlertConfigurationCreator. -type MockAlertConfigurationCreatorMockRecorder struct { - mock *MockAlertConfigurationCreator -} - -// NewMockAlertConfigurationCreator creates a new mock instance. -func NewMockAlertConfigurationCreator(ctrl *gomock.Controller) *MockAlertConfigurationCreator { - mock := &MockAlertConfigurationCreator{ctrl: ctrl} - mock.recorder = &MockAlertConfigurationCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertConfigurationCreator) EXPECT() *MockAlertConfigurationCreatorMockRecorder { - return m.recorder -} - -// CreateAlertConfiguration mocks base method. -func (m *MockAlertConfigurationCreator) CreateAlertConfiguration(arg0 *mongodbatlas.AlertConfiguration) (*mongodbatlas.AlertConfiguration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateAlertConfiguration", arg0) - ret0, _ := ret[0].(*mongodbatlas.AlertConfiguration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateAlertConfiguration indicates an expected call of CreateAlertConfiguration. -func (mr *MockAlertConfigurationCreatorMockRecorder) CreateAlertConfiguration(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAlertConfiguration", reflect.TypeOf((*MockAlertConfigurationCreator)(nil).CreateAlertConfiguration), arg0) -} - -// MockAlertConfigurationDeleter is a mock of AlertConfigurationDeleter interface. -type MockAlertConfigurationDeleter struct { - ctrl *gomock.Controller - recorder *MockAlertConfigurationDeleterMockRecorder -} - -// MockAlertConfigurationDeleterMockRecorder is the mock recorder for MockAlertConfigurationDeleter. -type MockAlertConfigurationDeleterMockRecorder struct { - mock *MockAlertConfigurationDeleter -} - -// NewMockAlertConfigurationDeleter creates a new mock instance. -func NewMockAlertConfigurationDeleter(ctrl *gomock.Controller) *MockAlertConfigurationDeleter { - mock := &MockAlertConfigurationDeleter{ctrl: ctrl} - mock.recorder = &MockAlertConfigurationDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertConfigurationDeleter) EXPECT() *MockAlertConfigurationDeleterMockRecorder { - return m.recorder -} - -// DeleteAlertConfiguration mocks base method. -func (m *MockAlertConfigurationDeleter) DeleteAlertConfiguration(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteAlertConfiguration", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteAlertConfiguration indicates an expected call of DeleteAlertConfiguration. -func (mr *MockAlertConfigurationDeleterMockRecorder) DeleteAlertConfiguration(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAlertConfiguration", reflect.TypeOf((*MockAlertConfigurationDeleter)(nil).DeleteAlertConfiguration), arg0, arg1) -} - -// MockAlertConfigurationUpdater is a mock of AlertConfigurationUpdater interface. -type MockAlertConfigurationUpdater struct { - ctrl *gomock.Controller - recorder *MockAlertConfigurationUpdaterMockRecorder -} - -// MockAlertConfigurationUpdaterMockRecorder is the mock recorder for MockAlertConfigurationUpdater. -type MockAlertConfigurationUpdaterMockRecorder struct { - mock *MockAlertConfigurationUpdater -} - -// NewMockAlertConfigurationUpdater creates a new mock instance. -func NewMockAlertConfigurationUpdater(ctrl *gomock.Controller) *MockAlertConfigurationUpdater { - mock := &MockAlertConfigurationUpdater{ctrl: ctrl} - mock.recorder = &MockAlertConfigurationUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertConfigurationUpdater) EXPECT() *MockAlertConfigurationUpdaterMockRecorder { - return m.recorder -} - -// UpdateAlertConfiguration mocks base method. -func (m *MockAlertConfigurationUpdater) UpdateAlertConfiguration(arg0 *mongodbatlas.AlertConfiguration) (*mongodbatlas.AlertConfiguration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateAlertConfiguration", arg0) - ret0, _ := ret[0].(*mongodbatlas.AlertConfiguration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateAlertConfiguration indicates an expected call of UpdateAlertConfiguration. -func (mr *MockAlertConfigurationUpdaterMockRecorder) UpdateAlertConfiguration(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAlertConfiguration", reflect.TypeOf((*MockAlertConfigurationUpdater)(nil).UpdateAlertConfiguration), arg0) -} - -// MockMatcherFieldsLister is a mock of MatcherFieldsLister interface. -type MockMatcherFieldsLister struct { - ctrl *gomock.Controller - recorder *MockMatcherFieldsListerMockRecorder -} - -// MockMatcherFieldsListerMockRecorder is the mock recorder for MockMatcherFieldsLister. -type MockMatcherFieldsListerMockRecorder struct { - mock *MockMatcherFieldsLister -} - -// NewMockMatcherFieldsLister creates a new mock instance. -func NewMockMatcherFieldsLister(ctrl *gomock.Controller) *MockMatcherFieldsLister { - mock := &MockMatcherFieldsLister{ctrl: ctrl} - mock.recorder = &MockMatcherFieldsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockMatcherFieldsLister) EXPECT() *MockMatcherFieldsListerMockRecorder { - return m.recorder -} - -// MatcherFields mocks base method. -func (m *MockMatcherFieldsLister) MatcherFields() ([]string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MatcherFields") - ret0, _ := ret[0].([]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// MatcherFields indicates an expected call of MatcherFields. -func (mr *MockMatcherFieldsListerMockRecorder) MatcherFields() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MatcherFields", reflect.TypeOf((*MockMatcherFieldsLister)(nil).MatcherFields)) -} - -// MockAlertConfigurationEnabler is a mock of AlertConfigurationEnabler interface. -type MockAlertConfigurationEnabler struct { - ctrl *gomock.Controller - recorder *MockAlertConfigurationEnablerMockRecorder -} - -// MockAlertConfigurationEnablerMockRecorder is the mock recorder for MockAlertConfigurationEnabler. -type MockAlertConfigurationEnablerMockRecorder struct { - mock *MockAlertConfigurationEnabler -} - -// NewMockAlertConfigurationEnabler creates a new mock instance. -func NewMockAlertConfigurationEnabler(ctrl *gomock.Controller) *MockAlertConfigurationEnabler { - mock := &MockAlertConfigurationEnabler{ctrl: ctrl} - mock.recorder = &MockAlertConfigurationEnablerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertConfigurationEnabler) EXPECT() *MockAlertConfigurationEnablerMockRecorder { - return m.recorder -} - -// EnableAlertConfiguration mocks base method. -func (m *MockAlertConfigurationEnabler) EnableAlertConfiguration(arg0, arg1 string) (*mongodbatlas.AlertConfiguration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "EnableAlertConfiguration", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.AlertConfiguration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// EnableAlertConfiguration indicates an expected call of EnableAlertConfiguration. -func (mr *MockAlertConfigurationEnablerMockRecorder) EnableAlertConfiguration(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnableAlertConfiguration", reflect.TypeOf((*MockAlertConfigurationEnabler)(nil).EnableAlertConfiguration), arg0, arg1) -} - -// MockAlertConfigurationDisabler is a mock of AlertConfigurationDisabler interface. -type MockAlertConfigurationDisabler struct { - ctrl *gomock.Controller - recorder *MockAlertConfigurationDisablerMockRecorder -} - -// MockAlertConfigurationDisablerMockRecorder is the mock recorder for MockAlertConfigurationDisabler. -type MockAlertConfigurationDisablerMockRecorder struct { - mock *MockAlertConfigurationDisabler -} - -// NewMockAlertConfigurationDisabler creates a new mock instance. -func NewMockAlertConfigurationDisabler(ctrl *gomock.Controller) *MockAlertConfigurationDisabler { - mock := &MockAlertConfigurationDisabler{ctrl: ctrl} - mock.recorder = &MockAlertConfigurationDisablerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertConfigurationDisabler) EXPECT() *MockAlertConfigurationDisablerMockRecorder { - return m.recorder -} - -// DisableAlertConfiguration mocks base method. -func (m *MockAlertConfigurationDisabler) DisableAlertConfiguration(arg0, arg1 string) (*mongodbatlas.AlertConfiguration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DisableAlertConfiguration", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.AlertConfiguration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DisableAlertConfiguration indicates an expected call of DisableAlertConfiguration. -func (mr *MockAlertConfigurationDisablerMockRecorder) DisableAlertConfiguration(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DisableAlertConfiguration", reflect.TypeOf((*MockAlertConfigurationDisabler)(nil).DisableAlertConfiguration), arg0, arg1) -} diff --git a/internal/mocks/mock_alerts.go b/internal/mocks/mock_alerts.go deleted file mode 100644 index 5f7bfaa946..0000000000 --- a/internal/mocks/mock_alerts.go +++ /dev/null @@ -1,126 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: AlertDescriber,AlertLister,AlertAcknowledger) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockAlertDescriber is a mock of AlertDescriber interface. -type MockAlertDescriber struct { - ctrl *gomock.Controller - recorder *MockAlertDescriberMockRecorder -} - -// MockAlertDescriberMockRecorder is the mock recorder for MockAlertDescriber. -type MockAlertDescriberMockRecorder struct { - mock *MockAlertDescriber -} - -// NewMockAlertDescriber creates a new mock instance. -func NewMockAlertDescriber(ctrl *gomock.Controller) *MockAlertDescriber { - mock := &MockAlertDescriber{ctrl: ctrl} - mock.recorder = &MockAlertDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertDescriber) EXPECT() *MockAlertDescriberMockRecorder { - return m.recorder -} - -// Alert mocks base method. -func (m *MockAlertDescriber) Alert(arg0, arg1 string) (*mongodbatlas.Alert, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Alert", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.Alert) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Alert indicates an expected call of Alert. -func (mr *MockAlertDescriberMockRecorder) Alert(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Alert", reflect.TypeOf((*MockAlertDescriber)(nil).Alert), arg0, arg1) -} - -// MockAlertLister is a mock of AlertLister interface. -type MockAlertLister struct { - ctrl *gomock.Controller - recorder *MockAlertListerMockRecorder -} - -// MockAlertListerMockRecorder is the mock recorder for MockAlertLister. -type MockAlertListerMockRecorder struct { - mock *MockAlertLister -} - -// NewMockAlertLister creates a new mock instance. -func NewMockAlertLister(ctrl *gomock.Controller) *MockAlertLister { - mock := &MockAlertLister{ctrl: ctrl} - mock.recorder = &MockAlertListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertLister) EXPECT() *MockAlertListerMockRecorder { - return m.recorder -} - -// Alerts mocks base method. -func (m *MockAlertLister) Alerts(arg0 string, arg1 *mongodbatlas.AlertsListOptions) (*mongodbatlas.AlertsResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Alerts", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.AlertsResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Alerts indicates an expected call of Alerts. -func (mr *MockAlertListerMockRecorder) Alerts(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Alerts", reflect.TypeOf((*MockAlertLister)(nil).Alerts), arg0, arg1) -} - -// MockAlertAcknowledger is a mock of AlertAcknowledger interface. -type MockAlertAcknowledger struct { - ctrl *gomock.Controller - recorder *MockAlertAcknowledgerMockRecorder -} - -// MockAlertAcknowledgerMockRecorder is the mock recorder for MockAlertAcknowledger. -type MockAlertAcknowledgerMockRecorder struct { - mock *MockAlertAcknowledger -} - -// NewMockAlertAcknowledger creates a new mock instance. -func NewMockAlertAcknowledger(ctrl *gomock.Controller) *MockAlertAcknowledger { - mock := &MockAlertAcknowledger{ctrl: ctrl} - mock.recorder = &MockAlertAcknowledgerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAlertAcknowledger) EXPECT() *MockAlertAcknowledgerMockRecorder { - return m.recorder -} - -// AcknowledgeAlert mocks base method. -func (m *MockAlertAcknowledger) AcknowledgeAlert(arg0, arg1 string, arg2 *mongodbatlas.AcknowledgeRequest) (*mongodbatlas.Alert, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AcknowledgeAlert", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.Alert) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AcknowledgeAlert indicates an expected call of AcknowledgeAlert. -func (mr *MockAlertAcknowledgerMockRecorder) AcknowledgeAlert(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcknowledgeAlert", reflect.TypeOf((*MockAlertAcknowledger)(nil).AcknowledgeAlert), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_api_keys.go b/internal/mocks/mock_api_keys.go deleted file mode 100644 index 95e618ec3f..0000000000 --- a/internal/mocks/mock_api_keys.go +++ /dev/null @@ -1,351 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: ProjectAPIKeyLister,ProjectAPIKeyCreator,OrganizationAPIKeyLister,OrganizationAPIKeyDescriber,OrganizationAPIKeyUpdater,OrganizationAPIKeyCreator,OrganizationAPIKeyDeleter,ProjectAPIKeyDeleter,ProjectAPIKeyAssigner) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockProjectAPIKeyLister is a mock of ProjectAPIKeyLister interface. -type MockProjectAPIKeyLister struct { - ctrl *gomock.Controller - recorder *MockProjectAPIKeyListerMockRecorder -} - -// MockProjectAPIKeyListerMockRecorder is the mock recorder for MockProjectAPIKeyLister. -type MockProjectAPIKeyListerMockRecorder struct { - mock *MockProjectAPIKeyLister -} - -// NewMockProjectAPIKeyLister creates a new mock instance. -func NewMockProjectAPIKeyLister(ctrl *gomock.Controller) *MockProjectAPIKeyLister { - mock := &MockProjectAPIKeyLister{ctrl: ctrl} - mock.recorder = &MockProjectAPIKeyListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectAPIKeyLister) EXPECT() *MockProjectAPIKeyListerMockRecorder { - return m.recorder -} - -// ProjectAPIKeys mocks base method. -func (m *MockProjectAPIKeyLister) ProjectAPIKeys(arg0 string, arg1 *mongodbatlas.ListOptions) ([]mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectAPIKeys", arg0, arg1) - ret0, _ := ret[0].([]mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectAPIKeys indicates an expected call of ProjectAPIKeys. -func (mr *MockProjectAPIKeyListerMockRecorder) ProjectAPIKeys(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectAPIKeys", reflect.TypeOf((*MockProjectAPIKeyLister)(nil).ProjectAPIKeys), arg0, arg1) -} - -// MockProjectAPIKeyCreator is a mock of ProjectAPIKeyCreator interface. -type MockProjectAPIKeyCreator struct { - ctrl *gomock.Controller - recorder *MockProjectAPIKeyCreatorMockRecorder -} - -// MockProjectAPIKeyCreatorMockRecorder is the mock recorder for MockProjectAPIKeyCreator. -type MockProjectAPIKeyCreatorMockRecorder struct { - mock *MockProjectAPIKeyCreator -} - -// NewMockProjectAPIKeyCreator creates a new mock instance. -func NewMockProjectAPIKeyCreator(ctrl *gomock.Controller) *MockProjectAPIKeyCreator { - mock := &MockProjectAPIKeyCreator{ctrl: ctrl} - mock.recorder = &MockProjectAPIKeyCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectAPIKeyCreator) EXPECT() *MockProjectAPIKeyCreatorMockRecorder { - return m.recorder -} - -// CreateProjectAPIKey mocks base method. -func (m *MockProjectAPIKeyCreator) CreateProjectAPIKey(arg0 string, arg1 *mongodbatlas.APIKeyInput) (*mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateProjectAPIKey", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateProjectAPIKey indicates an expected call of CreateProjectAPIKey. -func (mr *MockProjectAPIKeyCreatorMockRecorder) CreateProjectAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateProjectAPIKey", reflect.TypeOf((*MockProjectAPIKeyCreator)(nil).CreateProjectAPIKey), arg0, arg1) -} - -// MockOrganizationAPIKeyLister is a mock of OrganizationAPIKeyLister interface. -type MockOrganizationAPIKeyLister struct { - ctrl *gomock.Controller - recorder *MockOrganizationAPIKeyListerMockRecorder -} - -// MockOrganizationAPIKeyListerMockRecorder is the mock recorder for MockOrganizationAPIKeyLister. -type MockOrganizationAPIKeyListerMockRecorder struct { - mock *MockOrganizationAPIKeyLister -} - -// NewMockOrganizationAPIKeyLister creates a new mock instance. -func NewMockOrganizationAPIKeyLister(ctrl *gomock.Controller) *MockOrganizationAPIKeyLister { - mock := &MockOrganizationAPIKeyLister{ctrl: ctrl} - mock.recorder = &MockOrganizationAPIKeyListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationAPIKeyLister) EXPECT() *MockOrganizationAPIKeyListerMockRecorder { - return m.recorder -} - -// OrganizationAPIKeys mocks base method. -func (m *MockOrganizationAPIKeyLister) OrganizationAPIKeys(arg0 string, arg1 *mongodbatlas.ListOptions) ([]mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationAPIKeys", arg0, arg1) - ret0, _ := ret[0].([]mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationAPIKeys indicates an expected call of OrganizationAPIKeys. -func (mr *MockOrganizationAPIKeyListerMockRecorder) OrganizationAPIKeys(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationAPIKeys", reflect.TypeOf((*MockOrganizationAPIKeyLister)(nil).OrganizationAPIKeys), arg0, arg1) -} - -// MockOrganizationAPIKeyDescriber is a mock of OrganizationAPIKeyDescriber interface. -type MockOrganizationAPIKeyDescriber struct { - ctrl *gomock.Controller - recorder *MockOrganizationAPIKeyDescriberMockRecorder -} - -// MockOrganizationAPIKeyDescriberMockRecorder is the mock recorder for MockOrganizationAPIKeyDescriber. -type MockOrganizationAPIKeyDescriberMockRecorder struct { - mock *MockOrganizationAPIKeyDescriber -} - -// NewMockOrganizationAPIKeyDescriber creates a new mock instance. -func NewMockOrganizationAPIKeyDescriber(ctrl *gomock.Controller) *MockOrganizationAPIKeyDescriber { - mock := &MockOrganizationAPIKeyDescriber{ctrl: ctrl} - mock.recorder = &MockOrganizationAPIKeyDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationAPIKeyDescriber) EXPECT() *MockOrganizationAPIKeyDescriberMockRecorder { - return m.recorder -} - -// OrganizationAPIKey mocks base method. -func (m *MockOrganizationAPIKeyDescriber) OrganizationAPIKey(arg0, arg1 string) (*mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationAPIKey", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationAPIKey indicates an expected call of OrganizationAPIKey. -func (mr *MockOrganizationAPIKeyDescriberMockRecorder) OrganizationAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationAPIKey", reflect.TypeOf((*MockOrganizationAPIKeyDescriber)(nil).OrganizationAPIKey), arg0, arg1) -} - -// MockOrganizationAPIKeyUpdater is a mock of OrganizationAPIKeyUpdater interface. -type MockOrganizationAPIKeyUpdater struct { - ctrl *gomock.Controller - recorder *MockOrganizationAPIKeyUpdaterMockRecorder -} - -// MockOrganizationAPIKeyUpdaterMockRecorder is the mock recorder for MockOrganizationAPIKeyUpdater. -type MockOrganizationAPIKeyUpdaterMockRecorder struct { - mock *MockOrganizationAPIKeyUpdater -} - -// NewMockOrganizationAPIKeyUpdater creates a new mock instance. -func NewMockOrganizationAPIKeyUpdater(ctrl *gomock.Controller) *MockOrganizationAPIKeyUpdater { - mock := &MockOrganizationAPIKeyUpdater{ctrl: ctrl} - mock.recorder = &MockOrganizationAPIKeyUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationAPIKeyUpdater) EXPECT() *MockOrganizationAPIKeyUpdaterMockRecorder { - return m.recorder -} - -// UpdateOrganizationAPIKey mocks base method. -func (m *MockOrganizationAPIKeyUpdater) UpdateOrganizationAPIKey(arg0, arg1 string, arg2 *mongodbatlas.APIKeyInput) (*mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateOrganizationAPIKey", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateOrganizationAPIKey indicates an expected call of UpdateOrganizationAPIKey. -func (mr *MockOrganizationAPIKeyUpdaterMockRecorder) UpdateOrganizationAPIKey(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateOrganizationAPIKey", reflect.TypeOf((*MockOrganizationAPIKeyUpdater)(nil).UpdateOrganizationAPIKey), arg0, arg1, arg2) -} - -// MockOrganizationAPIKeyCreator is a mock of OrganizationAPIKeyCreator interface. -type MockOrganizationAPIKeyCreator struct { - ctrl *gomock.Controller - recorder *MockOrganizationAPIKeyCreatorMockRecorder -} - -// MockOrganizationAPIKeyCreatorMockRecorder is the mock recorder for MockOrganizationAPIKeyCreator. -type MockOrganizationAPIKeyCreatorMockRecorder struct { - mock *MockOrganizationAPIKeyCreator -} - -// NewMockOrganizationAPIKeyCreator creates a new mock instance. -func NewMockOrganizationAPIKeyCreator(ctrl *gomock.Controller) *MockOrganizationAPIKeyCreator { - mock := &MockOrganizationAPIKeyCreator{ctrl: ctrl} - mock.recorder = &MockOrganizationAPIKeyCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationAPIKeyCreator) EXPECT() *MockOrganizationAPIKeyCreatorMockRecorder { - return m.recorder -} - -// CreateOrganizationAPIKey mocks base method. -func (m *MockOrganizationAPIKeyCreator) CreateOrganizationAPIKey(arg0 string, arg1 *mongodbatlas.APIKeyInput) (*mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrganizationAPIKey", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateOrganizationAPIKey indicates an expected call of CreateOrganizationAPIKey. -func (mr *MockOrganizationAPIKeyCreatorMockRecorder) CreateOrganizationAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrganizationAPIKey", reflect.TypeOf((*MockOrganizationAPIKeyCreator)(nil).CreateOrganizationAPIKey), arg0, arg1) -} - -// MockOrganizationAPIKeyDeleter is a mock of OrganizationAPIKeyDeleter interface. -type MockOrganizationAPIKeyDeleter struct { - ctrl *gomock.Controller - recorder *MockOrganizationAPIKeyDeleterMockRecorder -} - -// MockOrganizationAPIKeyDeleterMockRecorder is the mock recorder for MockOrganizationAPIKeyDeleter. -type MockOrganizationAPIKeyDeleterMockRecorder struct { - mock *MockOrganizationAPIKeyDeleter -} - -// NewMockOrganizationAPIKeyDeleter creates a new mock instance. -func NewMockOrganizationAPIKeyDeleter(ctrl *gomock.Controller) *MockOrganizationAPIKeyDeleter { - mock := &MockOrganizationAPIKeyDeleter{ctrl: ctrl} - mock.recorder = &MockOrganizationAPIKeyDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationAPIKeyDeleter) EXPECT() *MockOrganizationAPIKeyDeleterMockRecorder { - return m.recorder -} - -// DeleteOrganizationAPIKey mocks base method. -func (m *MockOrganizationAPIKeyDeleter) DeleteOrganizationAPIKey(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteOrganizationAPIKey", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteOrganizationAPIKey indicates an expected call of DeleteOrganizationAPIKey. -func (mr *MockOrganizationAPIKeyDeleterMockRecorder) DeleteOrganizationAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteOrganizationAPIKey", reflect.TypeOf((*MockOrganizationAPIKeyDeleter)(nil).DeleteOrganizationAPIKey), arg0, arg1) -} - -// MockProjectAPIKeyDeleter is a mock of ProjectAPIKeyDeleter interface. -type MockProjectAPIKeyDeleter struct { - ctrl *gomock.Controller - recorder *MockProjectAPIKeyDeleterMockRecorder -} - -// MockProjectAPIKeyDeleterMockRecorder is the mock recorder for MockProjectAPIKeyDeleter. -type MockProjectAPIKeyDeleterMockRecorder struct { - mock *MockProjectAPIKeyDeleter -} - -// NewMockProjectAPIKeyDeleter creates a new mock instance. -func NewMockProjectAPIKeyDeleter(ctrl *gomock.Controller) *MockProjectAPIKeyDeleter { - mock := &MockProjectAPIKeyDeleter{ctrl: ctrl} - mock.recorder = &MockProjectAPIKeyDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectAPIKeyDeleter) EXPECT() *MockProjectAPIKeyDeleterMockRecorder { - return m.recorder -} - -// DeleteProjectAPIKey mocks base method. -func (m *MockProjectAPIKeyDeleter) DeleteProjectAPIKey(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteProjectAPIKey", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteProjectAPIKey indicates an expected call of DeleteProjectAPIKey. -func (mr *MockProjectAPIKeyDeleterMockRecorder) DeleteProjectAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteProjectAPIKey", reflect.TypeOf((*MockProjectAPIKeyDeleter)(nil).DeleteProjectAPIKey), arg0, arg1) -} - -// MockProjectAPIKeyAssigner is a mock of ProjectAPIKeyAssigner interface. -type MockProjectAPIKeyAssigner struct { - ctrl *gomock.Controller - recorder *MockProjectAPIKeyAssignerMockRecorder -} - -// MockProjectAPIKeyAssignerMockRecorder is the mock recorder for MockProjectAPIKeyAssigner. -type MockProjectAPIKeyAssignerMockRecorder struct { - mock *MockProjectAPIKeyAssigner -} - -// NewMockProjectAPIKeyAssigner creates a new mock instance. -func NewMockProjectAPIKeyAssigner(ctrl *gomock.Controller) *MockProjectAPIKeyAssigner { - mock := &MockProjectAPIKeyAssigner{ctrl: ctrl} - mock.recorder = &MockProjectAPIKeyAssignerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectAPIKeyAssigner) EXPECT() *MockProjectAPIKeyAssignerMockRecorder { - return m.recorder -} - -// AssignProjectAPIKey mocks base method. -func (m *MockProjectAPIKeyAssigner) AssignProjectAPIKey(arg0, arg1 string, arg2 *mongodbatlas.AssignAPIKey) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AssignProjectAPIKey", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// AssignProjectAPIKey indicates an expected call of AssignProjectAPIKey. -func (mr *MockProjectAPIKeyAssignerMockRecorder) AssignProjectAPIKey(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AssignProjectAPIKey", reflect.TypeOf((*MockProjectAPIKeyAssigner)(nil).AssignProjectAPIKey), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_api_keys_access_list.go b/internal/mocks/mock_api_keys_access_list.go deleted file mode 100644 index e36d6c3929..0000000000 --- a/internal/mocks/mock_api_keys_access_list.go +++ /dev/null @@ -1,125 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: OrganizationAPIKeyAccessListCreator,OrganizationAPIKeyAccessListDeleter,OrganizationAPIKeyAccessListLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockOrganizationAPIKeyAccessListCreator is a mock of OrganizationAPIKeyAccessListCreator interface. -type MockOrganizationAPIKeyAccessListCreator struct { - ctrl *gomock.Controller - recorder *MockOrganizationAPIKeyAccessListCreatorMockRecorder -} - -// MockOrganizationAPIKeyAccessListCreatorMockRecorder is the mock recorder for MockOrganizationAPIKeyAccessListCreator. -type MockOrganizationAPIKeyAccessListCreatorMockRecorder struct { - mock *MockOrganizationAPIKeyAccessListCreator -} - -// NewMockOrganizationAPIKeyAccessListCreator creates a new mock instance. -func NewMockOrganizationAPIKeyAccessListCreator(ctrl *gomock.Controller) *MockOrganizationAPIKeyAccessListCreator { - mock := &MockOrganizationAPIKeyAccessListCreator{ctrl: ctrl} - mock.recorder = &MockOrganizationAPIKeyAccessListCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationAPIKeyAccessListCreator) EXPECT() *MockOrganizationAPIKeyAccessListCreatorMockRecorder { - return m.recorder -} - -// CreateOrganizationAPIKeyAccessList mocks base method. -func (m *MockOrganizationAPIKeyAccessListCreator) CreateOrganizationAPIKeyAccessList(arg0, arg1 string, arg2 []*mongodbatlas.AccessListAPIKeysReq) (*mongodbatlas.AccessListAPIKeys, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrganizationAPIKeyAccessList", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.AccessListAPIKeys) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateOrganizationAPIKeyAccessList indicates an expected call of CreateOrganizationAPIKeyAccessList. -func (mr *MockOrganizationAPIKeyAccessListCreatorMockRecorder) CreateOrganizationAPIKeyAccessList(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrganizationAPIKeyAccessList", reflect.TypeOf((*MockOrganizationAPIKeyAccessListCreator)(nil).CreateOrganizationAPIKeyAccessList), arg0, arg1, arg2) -} - -// MockOrganizationAPIKeyAccessListDeleter is a mock of OrganizationAPIKeyAccessListDeleter interface. -type MockOrganizationAPIKeyAccessListDeleter struct { - ctrl *gomock.Controller - recorder *MockOrganizationAPIKeyAccessListDeleterMockRecorder -} - -// MockOrganizationAPIKeyAccessListDeleterMockRecorder is the mock recorder for MockOrganizationAPIKeyAccessListDeleter. -type MockOrganizationAPIKeyAccessListDeleterMockRecorder struct { - mock *MockOrganizationAPIKeyAccessListDeleter -} - -// NewMockOrganizationAPIKeyAccessListDeleter creates a new mock instance. -func NewMockOrganizationAPIKeyAccessListDeleter(ctrl *gomock.Controller) *MockOrganizationAPIKeyAccessListDeleter { - mock := &MockOrganizationAPIKeyAccessListDeleter{ctrl: ctrl} - mock.recorder = &MockOrganizationAPIKeyAccessListDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationAPIKeyAccessListDeleter) EXPECT() *MockOrganizationAPIKeyAccessListDeleterMockRecorder { - return m.recorder -} - -// DeleteOrganizationAPIKeyAccessList mocks base method. -func (m *MockOrganizationAPIKeyAccessListDeleter) DeleteOrganizationAPIKeyAccessList(arg0, arg1, arg2 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteOrganizationAPIKeyAccessList", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteOrganizationAPIKeyAccessList indicates an expected call of DeleteOrganizationAPIKeyAccessList. -func (mr *MockOrganizationAPIKeyAccessListDeleterMockRecorder) DeleteOrganizationAPIKeyAccessList(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteOrganizationAPIKeyAccessList", reflect.TypeOf((*MockOrganizationAPIKeyAccessListDeleter)(nil).DeleteOrganizationAPIKeyAccessList), arg0, arg1, arg2) -} - -// MockOrganizationAPIKeyAccessListLister is a mock of OrganizationAPIKeyAccessListLister interface. -type MockOrganizationAPIKeyAccessListLister struct { - ctrl *gomock.Controller - recorder *MockOrganizationAPIKeyAccessListListerMockRecorder -} - -// MockOrganizationAPIKeyAccessListListerMockRecorder is the mock recorder for MockOrganizationAPIKeyAccessListLister. -type MockOrganizationAPIKeyAccessListListerMockRecorder struct { - mock *MockOrganizationAPIKeyAccessListLister -} - -// NewMockOrganizationAPIKeyAccessListLister creates a new mock instance. -func NewMockOrganizationAPIKeyAccessListLister(ctrl *gomock.Controller) *MockOrganizationAPIKeyAccessListLister { - mock := &MockOrganizationAPIKeyAccessListLister{ctrl: ctrl} - mock.recorder = &MockOrganizationAPIKeyAccessListListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationAPIKeyAccessListLister) EXPECT() *MockOrganizationAPIKeyAccessListListerMockRecorder { - return m.recorder -} - -// OrganizationAPIKeyAccessLists mocks base method. -func (m *MockOrganizationAPIKeyAccessListLister) OrganizationAPIKeyAccessLists(arg0, arg1 string, arg2 *mongodbatlas.ListOptions) (*mongodbatlas.AccessListAPIKeys, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationAPIKeyAccessLists", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.AccessListAPIKeys) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationAPIKeyAccessLists indicates an expected call of OrganizationAPIKeyAccessLists. -func (mr *MockOrganizationAPIKeyAccessListListerMockRecorder) OrganizationAPIKeyAccessLists(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationAPIKeyAccessLists", reflect.TypeOf((*MockOrganizationAPIKeyAccessListLister)(nil).OrganizationAPIKeyAccessLists), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_automation.go b/internal/mocks/mock_automation.go deleted file mode 100644 index 9deed333f4..0000000000 --- a/internal/mocks/mock_automation.go +++ /dev/null @@ -1,395 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: AutomationGetter,AutomationUpdater,AutomationStatusGetter,AutomationPatcher,CloudManagerClustersLister,CloudManagerClustersDescriber,CloudManagerClustersDeleter) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockAutomationGetter is a mock of AutomationGetter interface. -type MockAutomationGetter struct { - ctrl *gomock.Controller - recorder *MockAutomationGetterMockRecorder -} - -// MockAutomationGetterMockRecorder is the mock recorder for MockAutomationGetter. -type MockAutomationGetterMockRecorder struct { - mock *MockAutomationGetter -} - -// NewMockAutomationGetter creates a new mock instance. -func NewMockAutomationGetter(ctrl *gomock.Controller) *MockAutomationGetter { - mock := &MockAutomationGetter{ctrl: ctrl} - mock.recorder = &MockAutomationGetterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAutomationGetter) EXPECT() *MockAutomationGetterMockRecorder { - return m.recorder -} - -// GetAutomationConfig mocks base method. -func (m *MockAutomationGetter) GetAutomationConfig(arg0 string) (*opsmngr.AutomationConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAutomationConfig", arg0) - ret0, _ := ret[0].(*opsmngr.AutomationConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAutomationConfig indicates an expected call of GetAutomationConfig. -func (mr *MockAutomationGetterMockRecorder) GetAutomationConfig(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAutomationConfig", reflect.TypeOf((*MockAutomationGetter)(nil).GetAutomationConfig), arg0) -} - -// MockAutomationUpdater is a mock of AutomationUpdater interface. -type MockAutomationUpdater struct { - ctrl *gomock.Controller - recorder *MockAutomationUpdaterMockRecorder -} - -// MockAutomationUpdaterMockRecorder is the mock recorder for MockAutomationUpdater. -type MockAutomationUpdaterMockRecorder struct { - mock *MockAutomationUpdater -} - -// NewMockAutomationUpdater creates a new mock instance. -func NewMockAutomationUpdater(ctrl *gomock.Controller) *MockAutomationUpdater { - mock := &MockAutomationUpdater{ctrl: ctrl} - mock.recorder = &MockAutomationUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAutomationUpdater) EXPECT() *MockAutomationUpdaterMockRecorder { - return m.recorder -} - -// UpdateAutomationConfig mocks base method. -func (m *MockAutomationUpdater) UpdateAutomationConfig(arg0 string, arg1 *opsmngr.AutomationConfig) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateAutomationConfig", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateAutomationConfig indicates an expected call of UpdateAutomationConfig. -func (mr *MockAutomationUpdaterMockRecorder) UpdateAutomationConfig(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAutomationConfig", reflect.TypeOf((*MockAutomationUpdater)(nil).UpdateAutomationConfig), arg0, arg1) -} - -// MockAutomationStatusGetter is a mock of AutomationStatusGetter interface. -type MockAutomationStatusGetter struct { - ctrl *gomock.Controller - recorder *MockAutomationStatusGetterMockRecorder -} - -// MockAutomationStatusGetterMockRecorder is the mock recorder for MockAutomationStatusGetter. -type MockAutomationStatusGetterMockRecorder struct { - mock *MockAutomationStatusGetter -} - -// NewMockAutomationStatusGetter creates a new mock instance. -func NewMockAutomationStatusGetter(ctrl *gomock.Controller) *MockAutomationStatusGetter { - mock := &MockAutomationStatusGetter{ctrl: ctrl} - mock.recorder = &MockAutomationStatusGetterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAutomationStatusGetter) EXPECT() *MockAutomationStatusGetterMockRecorder { - return m.recorder -} - -// GetAutomationStatus mocks base method. -func (m *MockAutomationStatusGetter) GetAutomationStatus(arg0 string) (*opsmngr.AutomationStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAutomationStatus", arg0) - ret0, _ := ret[0].(*opsmngr.AutomationStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAutomationStatus indicates an expected call of GetAutomationStatus. -func (mr *MockAutomationStatusGetterMockRecorder) GetAutomationStatus(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAutomationStatus", reflect.TypeOf((*MockAutomationStatusGetter)(nil).GetAutomationStatus), arg0) -} - -// MockAutomationPatcher is a mock of AutomationPatcher interface. -type MockAutomationPatcher struct { - ctrl *gomock.Controller - recorder *MockAutomationPatcherMockRecorder -} - -// MockAutomationPatcherMockRecorder is the mock recorder for MockAutomationPatcher. -type MockAutomationPatcherMockRecorder struct { - mock *MockAutomationPatcher -} - -// NewMockAutomationPatcher creates a new mock instance. -func NewMockAutomationPatcher(ctrl *gomock.Controller) *MockAutomationPatcher { - mock := &MockAutomationPatcher{ctrl: ctrl} - mock.recorder = &MockAutomationPatcherMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAutomationPatcher) EXPECT() *MockAutomationPatcherMockRecorder { - return m.recorder -} - -// GetAutomationConfig mocks base method. -func (m *MockAutomationPatcher) GetAutomationConfig(arg0 string) (*opsmngr.AutomationConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAutomationConfig", arg0) - ret0, _ := ret[0].(*opsmngr.AutomationConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAutomationConfig indicates an expected call of GetAutomationConfig. -func (mr *MockAutomationPatcherMockRecorder) GetAutomationConfig(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAutomationConfig", reflect.TypeOf((*MockAutomationPatcher)(nil).GetAutomationConfig), arg0) -} - -// UpdateAutomationConfig mocks base method. -func (m *MockAutomationPatcher) UpdateAutomationConfig(arg0 string, arg1 *opsmngr.AutomationConfig) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateAutomationConfig", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateAutomationConfig indicates an expected call of UpdateAutomationConfig. -func (mr *MockAutomationPatcherMockRecorder) UpdateAutomationConfig(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAutomationConfig", reflect.TypeOf((*MockAutomationPatcher)(nil).UpdateAutomationConfig), arg0, arg1) -} - -// MockCloudManagerClustersLister is a mock of CloudManagerClustersLister interface. -type MockCloudManagerClustersLister struct { - ctrl *gomock.Controller - recorder *MockCloudManagerClustersListerMockRecorder -} - -// MockCloudManagerClustersListerMockRecorder is the mock recorder for MockCloudManagerClustersLister. -type MockCloudManagerClustersListerMockRecorder struct { - mock *MockCloudManagerClustersLister -} - -// NewMockCloudManagerClustersLister creates a new mock instance. -func NewMockCloudManagerClustersLister(ctrl *gomock.Controller) *MockCloudManagerClustersLister { - mock := &MockCloudManagerClustersLister{ctrl: ctrl} - mock.recorder = &MockCloudManagerClustersListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockCloudManagerClustersLister) EXPECT() *MockCloudManagerClustersListerMockRecorder { - return m.recorder -} - -// GetAutomationConfig mocks base method. -func (m *MockCloudManagerClustersLister) GetAutomationConfig(arg0 string) (*opsmngr.AutomationConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAutomationConfig", arg0) - ret0, _ := ret[0].(*opsmngr.AutomationConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAutomationConfig indicates an expected call of GetAutomationConfig. -func (mr *MockCloudManagerClustersListerMockRecorder) GetAutomationConfig(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAutomationConfig", reflect.TypeOf((*MockCloudManagerClustersLister)(nil).GetAutomationConfig), arg0) -} - -// ListAllProjectClusters mocks base method. -func (m *MockCloudManagerClustersLister) ListAllProjectClusters() (*opsmngr.AllClustersProjects, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListAllProjectClusters") - ret0, _ := ret[0].(*opsmngr.AllClustersProjects) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListAllProjectClusters indicates an expected call of ListAllProjectClusters. -func (mr *MockCloudManagerClustersListerMockRecorder) ListAllProjectClusters() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListAllProjectClusters", reflect.TypeOf((*MockCloudManagerClustersLister)(nil).ListAllProjectClusters)) -} - -// ProjectClusters mocks base method. -func (m *MockCloudManagerClustersLister) ProjectClusters(arg0 string, arg1 *mongodbatlas.ListOptions) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectClusters", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectClusters indicates an expected call of ProjectClusters. -func (mr *MockCloudManagerClustersListerMockRecorder) ProjectClusters(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectClusters", reflect.TypeOf((*MockCloudManagerClustersLister)(nil).ProjectClusters), arg0, arg1) -} - -// MockCloudManagerClustersDescriber is a mock of CloudManagerClustersDescriber interface. -type MockCloudManagerClustersDescriber struct { - ctrl *gomock.Controller - recorder *MockCloudManagerClustersDescriberMockRecorder -} - -// MockCloudManagerClustersDescriberMockRecorder is the mock recorder for MockCloudManagerClustersDescriber. -type MockCloudManagerClustersDescriberMockRecorder struct { - mock *MockCloudManagerClustersDescriber -} - -// NewMockCloudManagerClustersDescriber creates a new mock instance. -func NewMockCloudManagerClustersDescriber(ctrl *gomock.Controller) *MockCloudManagerClustersDescriber { - mock := &MockCloudManagerClustersDescriber{ctrl: ctrl} - mock.recorder = &MockCloudManagerClustersDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockCloudManagerClustersDescriber) EXPECT() *MockCloudManagerClustersDescriberMockRecorder { - return m.recorder -} - -// GetAutomationConfig mocks base method. -func (m *MockCloudManagerClustersDescriber) GetAutomationConfig(arg0 string) (*opsmngr.AutomationConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAutomationConfig", arg0) - ret0, _ := ret[0].(*opsmngr.AutomationConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAutomationConfig indicates an expected call of GetAutomationConfig. -func (mr *MockCloudManagerClustersDescriberMockRecorder) GetAutomationConfig(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAutomationConfig", reflect.TypeOf((*MockCloudManagerClustersDescriber)(nil).GetAutomationConfig), arg0) -} - -// OpsManagerCluster mocks base method. -func (m *MockCloudManagerClustersDescriber) OpsManagerCluster(arg0, arg1 string) (*opsmngr.Cluster, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OpsManagerCluster", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.Cluster) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpsManagerCluster indicates an expected call of OpsManagerCluster. -func (mr *MockCloudManagerClustersDescriberMockRecorder) OpsManagerCluster(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpsManagerCluster", reflect.TypeOf((*MockCloudManagerClustersDescriber)(nil).OpsManagerCluster), arg0, arg1) -} - -// MockCloudManagerClustersDeleter is a mock of CloudManagerClustersDeleter interface. -type MockCloudManagerClustersDeleter struct { - ctrl *gomock.Controller - recorder *MockCloudManagerClustersDeleterMockRecorder -} - -// MockCloudManagerClustersDeleterMockRecorder is the mock recorder for MockCloudManagerClustersDeleter. -type MockCloudManagerClustersDeleterMockRecorder struct { - mock *MockCloudManagerClustersDeleter -} - -// NewMockCloudManagerClustersDeleter creates a new mock instance. -func NewMockCloudManagerClustersDeleter(ctrl *gomock.Controller) *MockCloudManagerClustersDeleter { - mock := &MockCloudManagerClustersDeleter{ctrl: ctrl} - mock.recorder = &MockCloudManagerClustersDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockCloudManagerClustersDeleter) EXPECT() *MockCloudManagerClustersDeleterMockRecorder { - return m.recorder -} - -// GetAutomationConfig mocks base method. -func (m *MockCloudManagerClustersDeleter) GetAutomationConfig(arg0 string) (*opsmngr.AutomationConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAutomationConfig", arg0) - ret0, _ := ret[0].(*opsmngr.AutomationConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAutomationConfig indicates an expected call of GetAutomationConfig. -func (mr *MockCloudManagerClustersDeleterMockRecorder) GetAutomationConfig(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAutomationConfig", reflect.TypeOf((*MockCloudManagerClustersDeleter)(nil).GetAutomationConfig), arg0) -} - -// GetAutomationStatus mocks base method. -func (m *MockCloudManagerClustersDeleter) GetAutomationStatus(arg0 string) (*opsmngr.AutomationStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAutomationStatus", arg0) - ret0, _ := ret[0].(*opsmngr.AutomationStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAutomationStatus indicates an expected call of GetAutomationStatus. -func (mr *MockCloudManagerClustersDeleterMockRecorder) GetAutomationStatus(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAutomationStatus", reflect.TypeOf((*MockCloudManagerClustersDeleter)(nil).GetAutomationStatus), arg0) -} - -// HostByHostname mocks base method. -func (m *MockCloudManagerClustersDeleter) HostByHostname(arg0, arg1 string, arg2 int) (*opsmngr.Host, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HostByHostname", arg0, arg1, arg2) - ret0, _ := ret[0].(*opsmngr.Host) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HostByHostname indicates an expected call of HostByHostname. -func (mr *MockCloudManagerClustersDeleterMockRecorder) HostByHostname(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostByHostname", reflect.TypeOf((*MockCloudManagerClustersDeleter)(nil).HostByHostname), arg0, arg1, arg2) -} - -// StopMonitoring mocks base method. -func (m *MockCloudManagerClustersDeleter) StopMonitoring(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "StopMonitoring", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// StopMonitoring indicates an expected call of StopMonitoring. -func (mr *MockCloudManagerClustersDeleterMockRecorder) StopMonitoring(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StopMonitoring", reflect.TypeOf((*MockCloudManagerClustersDeleter)(nil).StopMonitoring), arg0, arg1) -} - -// UpdateAutomationConfig mocks base method. -func (m *MockCloudManagerClustersDeleter) UpdateAutomationConfig(arg0 string, arg1 *opsmngr.AutomationConfig) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateAutomationConfig", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateAutomationConfig indicates an expected call of UpdateAutomationConfig. -func (mr *MockCloudManagerClustersDeleterMockRecorder) UpdateAutomationConfig(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateAutomationConfig", reflect.TypeOf((*MockCloudManagerClustersDeleter)(nil).UpdateAutomationConfig), arg0, arg1) -} diff --git a/internal/mocks/mock_backup_blockstores.go b/internal/mocks/mock_backup_blockstores.go deleted file mode 100644 index d873da202b..0000000000 --- a/internal/mocks/mock_backup_blockstores.go +++ /dev/null @@ -1,202 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: BlockstoresLister,BlockstoresDescriber,BlockstoresCreator,BlockstoresUpdater,BlockstoresDeleter) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockBlockstoresLister is a mock of BlockstoresLister interface. -type MockBlockstoresLister struct { - ctrl *gomock.Controller - recorder *MockBlockstoresListerMockRecorder -} - -// MockBlockstoresListerMockRecorder is the mock recorder for MockBlockstoresLister. -type MockBlockstoresListerMockRecorder struct { - mock *MockBlockstoresLister -} - -// NewMockBlockstoresLister creates a new mock instance. -func NewMockBlockstoresLister(ctrl *gomock.Controller) *MockBlockstoresLister { - mock := &MockBlockstoresLister{ctrl: ctrl} - mock.recorder = &MockBlockstoresListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBlockstoresLister) EXPECT() *MockBlockstoresListerMockRecorder { - return m.recorder -} - -// ListBlockstores mocks base method. -func (m *MockBlockstoresLister) ListBlockstores(arg0 *mongodbatlas.ListOptions) (*opsmngr.BackupStores, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListBlockstores", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStores) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListBlockstores indicates an expected call of ListBlockstores. -func (mr *MockBlockstoresListerMockRecorder) ListBlockstores(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListBlockstores", reflect.TypeOf((*MockBlockstoresLister)(nil).ListBlockstores), arg0) -} - -// MockBlockstoresDescriber is a mock of BlockstoresDescriber interface. -type MockBlockstoresDescriber struct { - ctrl *gomock.Controller - recorder *MockBlockstoresDescriberMockRecorder -} - -// MockBlockstoresDescriberMockRecorder is the mock recorder for MockBlockstoresDescriber. -type MockBlockstoresDescriberMockRecorder struct { - mock *MockBlockstoresDescriber -} - -// NewMockBlockstoresDescriber creates a new mock instance. -func NewMockBlockstoresDescriber(ctrl *gomock.Controller) *MockBlockstoresDescriber { - mock := &MockBlockstoresDescriber{ctrl: ctrl} - mock.recorder = &MockBlockstoresDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBlockstoresDescriber) EXPECT() *MockBlockstoresDescriberMockRecorder { - return m.recorder -} - -// DescribeBlockstore mocks base method. -func (m *MockBlockstoresDescriber) DescribeBlockstore(arg0 string) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DescribeBlockstore", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DescribeBlockstore indicates an expected call of DescribeBlockstore. -func (mr *MockBlockstoresDescriberMockRecorder) DescribeBlockstore(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeBlockstore", reflect.TypeOf((*MockBlockstoresDescriber)(nil).DescribeBlockstore), arg0) -} - -// MockBlockstoresCreator is a mock of BlockstoresCreator interface. -type MockBlockstoresCreator struct { - ctrl *gomock.Controller - recorder *MockBlockstoresCreatorMockRecorder -} - -// MockBlockstoresCreatorMockRecorder is the mock recorder for MockBlockstoresCreator. -type MockBlockstoresCreatorMockRecorder struct { - mock *MockBlockstoresCreator -} - -// NewMockBlockstoresCreator creates a new mock instance. -func NewMockBlockstoresCreator(ctrl *gomock.Controller) *MockBlockstoresCreator { - mock := &MockBlockstoresCreator{ctrl: ctrl} - mock.recorder = &MockBlockstoresCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBlockstoresCreator) EXPECT() *MockBlockstoresCreatorMockRecorder { - return m.recorder -} - -// CreateBlockstore mocks base method. -func (m *MockBlockstoresCreator) CreateBlockstore(arg0 *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateBlockstore", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateBlockstore indicates an expected call of CreateBlockstore. -func (mr *MockBlockstoresCreatorMockRecorder) CreateBlockstore(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateBlockstore", reflect.TypeOf((*MockBlockstoresCreator)(nil).CreateBlockstore), arg0) -} - -// MockBlockstoresUpdater is a mock of BlockstoresUpdater interface. -type MockBlockstoresUpdater struct { - ctrl *gomock.Controller - recorder *MockBlockstoresUpdaterMockRecorder -} - -// MockBlockstoresUpdaterMockRecorder is the mock recorder for MockBlockstoresUpdater. -type MockBlockstoresUpdaterMockRecorder struct { - mock *MockBlockstoresUpdater -} - -// NewMockBlockstoresUpdater creates a new mock instance. -func NewMockBlockstoresUpdater(ctrl *gomock.Controller) *MockBlockstoresUpdater { - mock := &MockBlockstoresUpdater{ctrl: ctrl} - mock.recorder = &MockBlockstoresUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBlockstoresUpdater) EXPECT() *MockBlockstoresUpdaterMockRecorder { - return m.recorder -} - -// UpdateBlockstore mocks base method. -func (m *MockBlockstoresUpdater) UpdateBlockstore(arg0 *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateBlockstore", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateBlockstore indicates an expected call of UpdateBlockstore. -func (mr *MockBlockstoresUpdaterMockRecorder) UpdateBlockstore(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateBlockstore", reflect.TypeOf((*MockBlockstoresUpdater)(nil).UpdateBlockstore), arg0) -} - -// MockBlockstoresDeleter is a mock of BlockstoresDeleter interface. -type MockBlockstoresDeleter struct { - ctrl *gomock.Controller - recorder *MockBlockstoresDeleterMockRecorder -} - -// MockBlockstoresDeleterMockRecorder is the mock recorder for MockBlockstoresDeleter. -type MockBlockstoresDeleterMockRecorder struct { - mock *MockBlockstoresDeleter -} - -// NewMockBlockstoresDeleter creates a new mock instance. -func NewMockBlockstoresDeleter(ctrl *gomock.Controller) *MockBlockstoresDeleter { - mock := &MockBlockstoresDeleter{ctrl: ctrl} - mock.recorder = &MockBlockstoresDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBlockstoresDeleter) EXPECT() *MockBlockstoresDeleterMockRecorder { - return m.recorder -} - -// DeleteBlockstore mocks base method. -func (m *MockBlockstoresDeleter) DeleteBlockstore(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteBlockstore", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteBlockstore indicates an expected call of DeleteBlockstore. -func (mr *MockBlockstoresDeleterMockRecorder) DeleteBlockstore(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBlockstore", reflect.TypeOf((*MockBlockstoresDeleter)(nil).DeleteBlockstore), arg0) -} diff --git a/internal/mocks/mock_backup_config.go b/internal/mocks/mock_backup_config.go deleted file mode 100644 index 699fa6b2f7..0000000000 --- a/internal/mocks/mock_backup_config.go +++ /dev/null @@ -1,127 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: BackupConfigGetter,BackupConfigLister,BackupConfigUpdater) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockBackupConfigGetter is a mock of BackupConfigGetter interface. -type MockBackupConfigGetter struct { - ctrl *gomock.Controller - recorder *MockBackupConfigGetterMockRecorder -} - -// MockBackupConfigGetterMockRecorder is the mock recorder for MockBackupConfigGetter. -type MockBackupConfigGetterMockRecorder struct { - mock *MockBackupConfigGetter -} - -// NewMockBackupConfigGetter creates a new mock instance. -func NewMockBackupConfigGetter(ctrl *gomock.Controller) *MockBackupConfigGetter { - mock := &MockBackupConfigGetter{ctrl: ctrl} - mock.recorder = &MockBackupConfigGetterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBackupConfigGetter) EXPECT() *MockBackupConfigGetterMockRecorder { - return m.recorder -} - -// GetBackupConfig mocks base method. -func (m *MockBackupConfigGetter) GetBackupConfig(arg0, arg1 string) (*opsmngr.BackupConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBackupConfig", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.BackupConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetBackupConfig indicates an expected call of GetBackupConfig. -func (mr *MockBackupConfigGetterMockRecorder) GetBackupConfig(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBackupConfig", reflect.TypeOf((*MockBackupConfigGetter)(nil).GetBackupConfig), arg0, arg1) -} - -// MockBackupConfigLister is a mock of BackupConfigLister interface. -type MockBackupConfigLister struct { - ctrl *gomock.Controller - recorder *MockBackupConfigListerMockRecorder -} - -// MockBackupConfigListerMockRecorder is the mock recorder for MockBackupConfigLister. -type MockBackupConfigListerMockRecorder struct { - mock *MockBackupConfigLister -} - -// NewMockBackupConfigLister creates a new mock instance. -func NewMockBackupConfigLister(ctrl *gomock.Controller) *MockBackupConfigLister { - mock := &MockBackupConfigLister{ctrl: ctrl} - mock.recorder = &MockBackupConfigListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBackupConfigLister) EXPECT() *MockBackupConfigListerMockRecorder { - return m.recorder -} - -// ListBackupConfigs mocks base method. -func (m *MockBackupConfigLister) ListBackupConfigs(arg0 string, arg1 *mongodbatlas.ListOptions) (*opsmngr.BackupConfigs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListBackupConfigs", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.BackupConfigs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListBackupConfigs indicates an expected call of ListBackupConfigs. -func (mr *MockBackupConfigListerMockRecorder) ListBackupConfigs(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListBackupConfigs", reflect.TypeOf((*MockBackupConfigLister)(nil).ListBackupConfigs), arg0, arg1) -} - -// MockBackupConfigUpdater is a mock of BackupConfigUpdater interface. -type MockBackupConfigUpdater struct { - ctrl *gomock.Controller - recorder *MockBackupConfigUpdaterMockRecorder -} - -// MockBackupConfigUpdaterMockRecorder is the mock recorder for MockBackupConfigUpdater. -type MockBackupConfigUpdaterMockRecorder struct { - mock *MockBackupConfigUpdater -} - -// NewMockBackupConfigUpdater creates a new mock instance. -func NewMockBackupConfigUpdater(ctrl *gomock.Controller) *MockBackupConfigUpdater { - mock := &MockBackupConfigUpdater{ctrl: ctrl} - mock.recorder = &MockBackupConfigUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBackupConfigUpdater) EXPECT() *MockBackupConfigUpdaterMockRecorder { - return m.recorder -} - -// UpdateBackupConfig mocks base method. -func (m *MockBackupConfigUpdater) UpdateBackupConfig(arg0 *opsmngr.BackupConfig) (*opsmngr.BackupConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateBackupConfig", arg0) - ret0, _ := ret[0].(*opsmngr.BackupConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateBackupConfig indicates an expected call of UpdateBackupConfig. -func (mr *MockBackupConfigUpdaterMockRecorder) UpdateBackupConfig(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateBackupConfig", reflect.TypeOf((*MockBackupConfigUpdater)(nil).UpdateBackupConfig), arg0) -} diff --git a/internal/mocks/mock_backup_file_systems.go b/internal/mocks/mock_backup_file_systems.go deleted file mode 100644 index fe47b371fd..0000000000 --- a/internal/mocks/mock_backup_file_systems.go +++ /dev/null @@ -1,202 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: FileSystemsLister,FileSystemsDescriber,FileSystemsDeleter,FileSystemsCreator,FileSystemsUpdater) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockFileSystemsLister is a mock of FileSystemsLister interface. -type MockFileSystemsLister struct { - ctrl *gomock.Controller - recorder *MockFileSystemsListerMockRecorder -} - -// MockFileSystemsListerMockRecorder is the mock recorder for MockFileSystemsLister. -type MockFileSystemsListerMockRecorder struct { - mock *MockFileSystemsLister -} - -// NewMockFileSystemsLister creates a new mock instance. -func NewMockFileSystemsLister(ctrl *gomock.Controller) *MockFileSystemsLister { - mock := &MockFileSystemsLister{ctrl: ctrl} - mock.recorder = &MockFileSystemsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFileSystemsLister) EXPECT() *MockFileSystemsListerMockRecorder { - return m.recorder -} - -// ListFileSystems mocks base method. -func (m *MockFileSystemsLister) ListFileSystems(arg0 *mongodbatlas.ListOptions) (*opsmngr.FileSystemStoreConfigurations, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListFileSystems", arg0) - ret0, _ := ret[0].(*opsmngr.FileSystemStoreConfigurations) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListFileSystems indicates an expected call of ListFileSystems. -func (mr *MockFileSystemsListerMockRecorder) ListFileSystems(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFileSystems", reflect.TypeOf((*MockFileSystemsLister)(nil).ListFileSystems), arg0) -} - -// MockFileSystemsDescriber is a mock of FileSystemsDescriber interface. -type MockFileSystemsDescriber struct { - ctrl *gomock.Controller - recorder *MockFileSystemsDescriberMockRecorder -} - -// MockFileSystemsDescriberMockRecorder is the mock recorder for MockFileSystemsDescriber. -type MockFileSystemsDescriberMockRecorder struct { - mock *MockFileSystemsDescriber -} - -// NewMockFileSystemsDescriber creates a new mock instance. -func NewMockFileSystemsDescriber(ctrl *gomock.Controller) *MockFileSystemsDescriber { - mock := &MockFileSystemsDescriber{ctrl: ctrl} - mock.recorder = &MockFileSystemsDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFileSystemsDescriber) EXPECT() *MockFileSystemsDescriberMockRecorder { - return m.recorder -} - -// DescribeFileSystem mocks base method. -func (m *MockFileSystemsDescriber) DescribeFileSystem(arg0 string) (*opsmngr.FileSystemStoreConfiguration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DescribeFileSystem", arg0) - ret0, _ := ret[0].(*opsmngr.FileSystemStoreConfiguration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DescribeFileSystem indicates an expected call of DescribeFileSystem. -func (mr *MockFileSystemsDescriberMockRecorder) DescribeFileSystem(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeFileSystem", reflect.TypeOf((*MockFileSystemsDescriber)(nil).DescribeFileSystem), arg0) -} - -// MockFileSystemsDeleter is a mock of FileSystemsDeleter interface. -type MockFileSystemsDeleter struct { - ctrl *gomock.Controller - recorder *MockFileSystemsDeleterMockRecorder -} - -// MockFileSystemsDeleterMockRecorder is the mock recorder for MockFileSystemsDeleter. -type MockFileSystemsDeleterMockRecorder struct { - mock *MockFileSystemsDeleter -} - -// NewMockFileSystemsDeleter creates a new mock instance. -func NewMockFileSystemsDeleter(ctrl *gomock.Controller) *MockFileSystemsDeleter { - mock := &MockFileSystemsDeleter{ctrl: ctrl} - mock.recorder = &MockFileSystemsDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFileSystemsDeleter) EXPECT() *MockFileSystemsDeleterMockRecorder { - return m.recorder -} - -// DeleteFileSystem mocks base method. -func (m *MockFileSystemsDeleter) DeleteFileSystem(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteFileSystem", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteFileSystem indicates an expected call of DeleteFileSystem. -func (mr *MockFileSystemsDeleterMockRecorder) DeleteFileSystem(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteFileSystem", reflect.TypeOf((*MockFileSystemsDeleter)(nil).DeleteFileSystem), arg0) -} - -// MockFileSystemsCreator is a mock of FileSystemsCreator interface. -type MockFileSystemsCreator struct { - ctrl *gomock.Controller - recorder *MockFileSystemsCreatorMockRecorder -} - -// MockFileSystemsCreatorMockRecorder is the mock recorder for MockFileSystemsCreator. -type MockFileSystemsCreatorMockRecorder struct { - mock *MockFileSystemsCreator -} - -// NewMockFileSystemsCreator creates a new mock instance. -func NewMockFileSystemsCreator(ctrl *gomock.Controller) *MockFileSystemsCreator { - mock := &MockFileSystemsCreator{ctrl: ctrl} - mock.recorder = &MockFileSystemsCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFileSystemsCreator) EXPECT() *MockFileSystemsCreatorMockRecorder { - return m.recorder -} - -// CreateFileSystems mocks base method. -func (m *MockFileSystemsCreator) CreateFileSystems(arg0 *opsmngr.FileSystemStoreConfiguration) (*opsmngr.FileSystemStoreConfiguration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateFileSystems", arg0) - ret0, _ := ret[0].(*opsmngr.FileSystemStoreConfiguration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateFileSystems indicates an expected call of CreateFileSystems. -func (mr *MockFileSystemsCreatorMockRecorder) CreateFileSystems(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateFileSystems", reflect.TypeOf((*MockFileSystemsCreator)(nil).CreateFileSystems), arg0) -} - -// MockFileSystemsUpdater is a mock of FileSystemsUpdater interface. -type MockFileSystemsUpdater struct { - ctrl *gomock.Controller - recorder *MockFileSystemsUpdaterMockRecorder -} - -// MockFileSystemsUpdaterMockRecorder is the mock recorder for MockFileSystemsUpdater. -type MockFileSystemsUpdaterMockRecorder struct { - mock *MockFileSystemsUpdater -} - -// NewMockFileSystemsUpdater creates a new mock instance. -func NewMockFileSystemsUpdater(ctrl *gomock.Controller) *MockFileSystemsUpdater { - mock := &MockFileSystemsUpdater{ctrl: ctrl} - mock.recorder = &MockFileSystemsUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFileSystemsUpdater) EXPECT() *MockFileSystemsUpdaterMockRecorder { - return m.recorder -} - -// UpdateFileSystems mocks base method. -func (m *MockFileSystemsUpdater) UpdateFileSystems(arg0 *opsmngr.FileSystemStoreConfiguration) (*opsmngr.FileSystemStoreConfiguration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateFileSystems", arg0) - ret0, _ := ret[0].(*opsmngr.FileSystemStoreConfiguration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateFileSystems indicates an expected call of UpdateFileSystems. -func (mr *MockFileSystemsUpdaterMockRecorder) UpdateFileSystems(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateFileSystems", reflect.TypeOf((*MockFileSystemsUpdater)(nil).UpdateFileSystems), arg0) -} diff --git a/internal/mocks/mock_backup_oplogs.go b/internal/mocks/mock_backup_oplogs.go deleted file mode 100644 index dd0847b4ce..0000000000 --- a/internal/mocks/mock_backup_oplogs.go +++ /dev/null @@ -1,202 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: OplogsLister,OplogsDescriber,OplogsCreator,OplogsUpdater,OplogsDeleter) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockOplogsLister is a mock of OplogsLister interface. -type MockOplogsLister struct { - ctrl *gomock.Controller - recorder *MockOplogsListerMockRecorder -} - -// MockOplogsListerMockRecorder is the mock recorder for MockOplogsLister. -type MockOplogsListerMockRecorder struct { - mock *MockOplogsLister -} - -// NewMockOplogsLister creates a new mock instance. -func NewMockOplogsLister(ctrl *gomock.Controller) *MockOplogsLister { - mock := &MockOplogsLister{ctrl: ctrl} - mock.recorder = &MockOplogsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOplogsLister) EXPECT() *MockOplogsListerMockRecorder { - return m.recorder -} - -// ListOplogs mocks base method. -func (m *MockOplogsLister) ListOplogs(arg0 *mongodbatlas.ListOptions) (*opsmngr.BackupStores, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListOplogs", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStores) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListOplogs indicates an expected call of ListOplogs. -func (mr *MockOplogsListerMockRecorder) ListOplogs(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListOplogs", reflect.TypeOf((*MockOplogsLister)(nil).ListOplogs), arg0) -} - -// MockOplogsDescriber is a mock of OplogsDescriber interface. -type MockOplogsDescriber struct { - ctrl *gomock.Controller - recorder *MockOplogsDescriberMockRecorder -} - -// MockOplogsDescriberMockRecorder is the mock recorder for MockOplogsDescriber. -type MockOplogsDescriberMockRecorder struct { - mock *MockOplogsDescriber -} - -// NewMockOplogsDescriber creates a new mock instance. -func NewMockOplogsDescriber(ctrl *gomock.Controller) *MockOplogsDescriber { - mock := &MockOplogsDescriber{ctrl: ctrl} - mock.recorder = &MockOplogsDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOplogsDescriber) EXPECT() *MockOplogsDescriberMockRecorder { - return m.recorder -} - -// GetOplog mocks base method. -func (m *MockOplogsDescriber) GetOplog(arg0 string) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetOplog", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetOplog indicates an expected call of GetOplog. -func (mr *MockOplogsDescriberMockRecorder) GetOplog(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOplog", reflect.TypeOf((*MockOplogsDescriber)(nil).GetOplog), arg0) -} - -// MockOplogsCreator is a mock of OplogsCreator interface. -type MockOplogsCreator struct { - ctrl *gomock.Controller - recorder *MockOplogsCreatorMockRecorder -} - -// MockOplogsCreatorMockRecorder is the mock recorder for MockOplogsCreator. -type MockOplogsCreatorMockRecorder struct { - mock *MockOplogsCreator -} - -// NewMockOplogsCreator creates a new mock instance. -func NewMockOplogsCreator(ctrl *gomock.Controller) *MockOplogsCreator { - mock := &MockOplogsCreator{ctrl: ctrl} - mock.recorder = &MockOplogsCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOplogsCreator) EXPECT() *MockOplogsCreatorMockRecorder { - return m.recorder -} - -// CreateOplog mocks base method. -func (m *MockOplogsCreator) CreateOplog(arg0 *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOplog", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateOplog indicates an expected call of CreateOplog. -func (mr *MockOplogsCreatorMockRecorder) CreateOplog(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOplog", reflect.TypeOf((*MockOplogsCreator)(nil).CreateOplog), arg0) -} - -// MockOplogsUpdater is a mock of OplogsUpdater interface. -type MockOplogsUpdater struct { - ctrl *gomock.Controller - recorder *MockOplogsUpdaterMockRecorder -} - -// MockOplogsUpdaterMockRecorder is the mock recorder for MockOplogsUpdater. -type MockOplogsUpdaterMockRecorder struct { - mock *MockOplogsUpdater -} - -// NewMockOplogsUpdater creates a new mock instance. -func NewMockOplogsUpdater(ctrl *gomock.Controller) *MockOplogsUpdater { - mock := &MockOplogsUpdater{ctrl: ctrl} - mock.recorder = &MockOplogsUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOplogsUpdater) EXPECT() *MockOplogsUpdaterMockRecorder { - return m.recorder -} - -// UpdateOplog mocks base method. -func (m *MockOplogsUpdater) UpdateOplog(arg0 string, arg1 *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateOplog", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateOplog indicates an expected call of UpdateOplog. -func (mr *MockOplogsUpdaterMockRecorder) UpdateOplog(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateOplog", reflect.TypeOf((*MockOplogsUpdater)(nil).UpdateOplog), arg0, arg1) -} - -// MockOplogsDeleter is a mock of OplogsDeleter interface. -type MockOplogsDeleter struct { - ctrl *gomock.Controller - recorder *MockOplogsDeleterMockRecorder -} - -// MockOplogsDeleterMockRecorder is the mock recorder for MockOplogsDeleter. -type MockOplogsDeleterMockRecorder struct { - mock *MockOplogsDeleter -} - -// NewMockOplogsDeleter creates a new mock instance. -func NewMockOplogsDeleter(ctrl *gomock.Controller) *MockOplogsDeleter { - mock := &MockOplogsDeleter{ctrl: ctrl} - mock.recorder = &MockOplogsDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOplogsDeleter) EXPECT() *MockOplogsDeleterMockRecorder { - return m.recorder -} - -// DeleteOplog mocks base method. -func (m *MockOplogsDeleter) DeleteOplog(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteOplog", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteOplog indicates an expected call of DeleteOplog. -func (mr *MockOplogsDeleterMockRecorder) DeleteOplog(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteOplog", reflect.TypeOf((*MockOplogsDeleter)(nil).DeleteOplog), arg0) -} diff --git a/internal/mocks/mock_backup_s3_blockstores.go b/internal/mocks/mock_backup_s3_blockstores.go deleted file mode 100644 index b92176594c..0000000000 --- a/internal/mocks/mock_backup_s3_blockstores.go +++ /dev/null @@ -1,202 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: S3BlockstoresLister,S3BlockstoresDeleter,S3BlockstoresCreator,S3BlockstoresUpdater,S3BlockstoresDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockS3BlockstoresLister is a mock of S3BlockstoresLister interface. -type MockS3BlockstoresLister struct { - ctrl *gomock.Controller - recorder *MockS3BlockstoresListerMockRecorder -} - -// MockS3BlockstoresListerMockRecorder is the mock recorder for MockS3BlockstoresLister. -type MockS3BlockstoresListerMockRecorder struct { - mock *MockS3BlockstoresLister -} - -// NewMockS3BlockstoresLister creates a new mock instance. -func NewMockS3BlockstoresLister(ctrl *gomock.Controller) *MockS3BlockstoresLister { - mock := &MockS3BlockstoresLister{ctrl: ctrl} - mock.recorder = &MockS3BlockstoresListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockS3BlockstoresLister) EXPECT() *MockS3BlockstoresListerMockRecorder { - return m.recorder -} - -// ListS3Blockstores mocks base method. -func (m *MockS3BlockstoresLister) ListS3Blockstores(arg0 *mongodbatlas.ListOptions) (*opsmngr.S3Blockstores, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListS3Blockstores", arg0) - ret0, _ := ret[0].(*opsmngr.S3Blockstores) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListS3Blockstores indicates an expected call of ListS3Blockstores. -func (mr *MockS3BlockstoresListerMockRecorder) ListS3Blockstores(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListS3Blockstores", reflect.TypeOf((*MockS3BlockstoresLister)(nil).ListS3Blockstores), arg0) -} - -// MockS3BlockstoresDeleter is a mock of S3BlockstoresDeleter interface. -type MockS3BlockstoresDeleter struct { - ctrl *gomock.Controller - recorder *MockS3BlockstoresDeleterMockRecorder -} - -// MockS3BlockstoresDeleterMockRecorder is the mock recorder for MockS3BlockstoresDeleter. -type MockS3BlockstoresDeleterMockRecorder struct { - mock *MockS3BlockstoresDeleter -} - -// NewMockS3BlockstoresDeleter creates a new mock instance. -func NewMockS3BlockstoresDeleter(ctrl *gomock.Controller) *MockS3BlockstoresDeleter { - mock := &MockS3BlockstoresDeleter{ctrl: ctrl} - mock.recorder = &MockS3BlockstoresDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockS3BlockstoresDeleter) EXPECT() *MockS3BlockstoresDeleterMockRecorder { - return m.recorder -} - -// DeleteS3Blockstore mocks base method. -func (m *MockS3BlockstoresDeleter) DeleteS3Blockstore(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteS3Blockstore", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteS3Blockstore indicates an expected call of DeleteS3Blockstore. -func (mr *MockS3BlockstoresDeleterMockRecorder) DeleteS3Blockstore(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteS3Blockstore", reflect.TypeOf((*MockS3BlockstoresDeleter)(nil).DeleteS3Blockstore), arg0) -} - -// MockS3BlockstoresCreator is a mock of S3BlockstoresCreator interface. -type MockS3BlockstoresCreator struct { - ctrl *gomock.Controller - recorder *MockS3BlockstoresCreatorMockRecorder -} - -// MockS3BlockstoresCreatorMockRecorder is the mock recorder for MockS3BlockstoresCreator. -type MockS3BlockstoresCreatorMockRecorder struct { - mock *MockS3BlockstoresCreator -} - -// NewMockS3BlockstoresCreator creates a new mock instance. -func NewMockS3BlockstoresCreator(ctrl *gomock.Controller) *MockS3BlockstoresCreator { - mock := &MockS3BlockstoresCreator{ctrl: ctrl} - mock.recorder = &MockS3BlockstoresCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockS3BlockstoresCreator) EXPECT() *MockS3BlockstoresCreatorMockRecorder { - return m.recorder -} - -// CreateS3Blockstores mocks base method. -func (m *MockS3BlockstoresCreator) CreateS3Blockstores(arg0 *opsmngr.S3Blockstore) (*opsmngr.S3Blockstore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateS3Blockstores", arg0) - ret0, _ := ret[0].(*opsmngr.S3Blockstore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateS3Blockstores indicates an expected call of CreateS3Blockstores. -func (mr *MockS3BlockstoresCreatorMockRecorder) CreateS3Blockstores(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateS3Blockstores", reflect.TypeOf((*MockS3BlockstoresCreator)(nil).CreateS3Blockstores), arg0) -} - -// MockS3BlockstoresUpdater is a mock of S3BlockstoresUpdater interface. -type MockS3BlockstoresUpdater struct { - ctrl *gomock.Controller - recorder *MockS3BlockstoresUpdaterMockRecorder -} - -// MockS3BlockstoresUpdaterMockRecorder is the mock recorder for MockS3BlockstoresUpdater. -type MockS3BlockstoresUpdaterMockRecorder struct { - mock *MockS3BlockstoresUpdater -} - -// NewMockS3BlockstoresUpdater creates a new mock instance. -func NewMockS3BlockstoresUpdater(ctrl *gomock.Controller) *MockS3BlockstoresUpdater { - mock := &MockS3BlockstoresUpdater{ctrl: ctrl} - mock.recorder = &MockS3BlockstoresUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockS3BlockstoresUpdater) EXPECT() *MockS3BlockstoresUpdaterMockRecorder { - return m.recorder -} - -// UpdateS3Blockstores mocks base method. -func (m *MockS3BlockstoresUpdater) UpdateS3Blockstores(arg0 string, arg1 *opsmngr.S3Blockstore) (*opsmngr.S3Blockstore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateS3Blockstores", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.S3Blockstore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateS3Blockstores indicates an expected call of UpdateS3Blockstores. -func (mr *MockS3BlockstoresUpdaterMockRecorder) UpdateS3Blockstores(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateS3Blockstores", reflect.TypeOf((*MockS3BlockstoresUpdater)(nil).UpdateS3Blockstores), arg0, arg1) -} - -// MockS3BlockstoresDescriber is a mock of S3BlockstoresDescriber interface. -type MockS3BlockstoresDescriber struct { - ctrl *gomock.Controller - recorder *MockS3BlockstoresDescriberMockRecorder -} - -// MockS3BlockstoresDescriberMockRecorder is the mock recorder for MockS3BlockstoresDescriber. -type MockS3BlockstoresDescriberMockRecorder struct { - mock *MockS3BlockstoresDescriber -} - -// NewMockS3BlockstoresDescriber creates a new mock instance. -func NewMockS3BlockstoresDescriber(ctrl *gomock.Controller) *MockS3BlockstoresDescriber { - mock := &MockS3BlockstoresDescriber{ctrl: ctrl} - mock.recorder = &MockS3BlockstoresDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockS3BlockstoresDescriber) EXPECT() *MockS3BlockstoresDescriberMockRecorder { - return m.recorder -} - -// GetS3Blockstore mocks base method. -func (m *MockS3BlockstoresDescriber) GetS3Blockstore(arg0 string) (*opsmngr.S3Blockstore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetS3Blockstore", arg0) - ret0, _ := ret[0].(*opsmngr.S3Blockstore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetS3Blockstore indicates an expected call of GetS3Blockstore. -func (mr *MockS3BlockstoresDescriberMockRecorder) GetS3Blockstore(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetS3Blockstore", reflect.TypeOf((*MockS3BlockstoresDescriber)(nil).GetS3Blockstore), arg0) -} diff --git a/internal/mocks/mock_backup_snapshot_schedule.go b/internal/mocks/mock_backup_snapshot_schedule.go deleted file mode 100644 index 200849df1c..0000000000 --- a/internal/mocks/mock_backup_snapshot_schedule.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: SnapshotScheduleDescriber,SnapshotScheduleUpdater) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockSnapshotScheduleDescriber is a mock of SnapshotScheduleDescriber interface. -type MockSnapshotScheduleDescriber struct { - ctrl *gomock.Controller - recorder *MockSnapshotScheduleDescriberMockRecorder -} - -// MockSnapshotScheduleDescriberMockRecorder is the mock recorder for MockSnapshotScheduleDescriber. -type MockSnapshotScheduleDescriberMockRecorder struct { - mock *MockSnapshotScheduleDescriber -} - -// NewMockSnapshotScheduleDescriber creates a new mock instance. -func NewMockSnapshotScheduleDescriber(ctrl *gomock.Controller) *MockSnapshotScheduleDescriber { - mock := &MockSnapshotScheduleDescriber{ctrl: ctrl} - mock.recorder = &MockSnapshotScheduleDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSnapshotScheduleDescriber) EXPECT() *MockSnapshotScheduleDescriberMockRecorder { - return m.recorder -} - -// GetSnapshotSchedule mocks base method. -func (m *MockSnapshotScheduleDescriber) GetSnapshotSchedule(arg0, arg1 string) (*opsmngr.SnapshotSchedule, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSnapshotSchedule", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.SnapshotSchedule) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSnapshotSchedule indicates an expected call of GetSnapshotSchedule. -func (mr *MockSnapshotScheduleDescriberMockRecorder) GetSnapshotSchedule(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSnapshotSchedule", reflect.TypeOf((*MockSnapshotScheduleDescriber)(nil).GetSnapshotSchedule), arg0, arg1) -} - -// MockSnapshotScheduleUpdater is a mock of SnapshotScheduleUpdater interface. -type MockSnapshotScheduleUpdater struct { - ctrl *gomock.Controller - recorder *MockSnapshotScheduleUpdaterMockRecorder -} - -// MockSnapshotScheduleUpdaterMockRecorder is the mock recorder for MockSnapshotScheduleUpdater. -type MockSnapshotScheduleUpdaterMockRecorder struct { - mock *MockSnapshotScheduleUpdater -} - -// NewMockSnapshotScheduleUpdater creates a new mock instance. -func NewMockSnapshotScheduleUpdater(ctrl *gomock.Controller) *MockSnapshotScheduleUpdater { - mock := &MockSnapshotScheduleUpdater{ctrl: ctrl} - mock.recorder = &MockSnapshotScheduleUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSnapshotScheduleUpdater) EXPECT() *MockSnapshotScheduleUpdaterMockRecorder { - return m.recorder -} - -// UpdateSnapshotSchedule mocks base method. -func (m *MockSnapshotScheduleUpdater) UpdateSnapshotSchedule(arg0, arg1 string, arg2 *opsmngr.SnapshotSchedule) (*opsmngr.SnapshotSchedule, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateSnapshotSchedule", arg0, arg1, arg2) - ret0, _ := ret[0].(*opsmngr.SnapshotSchedule) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateSnapshotSchedule indicates an expected call of UpdateSnapshotSchedule. -func (mr *MockSnapshotScheduleUpdaterMockRecorder) UpdateSnapshotSchedule(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateSnapshotSchedule", reflect.TypeOf((*MockSnapshotScheduleUpdater)(nil).UpdateSnapshotSchedule), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_backup_sync.go b/internal/mocks/mock_backup_sync.go deleted file mode 100644 index 9d5a970aed..0000000000 --- a/internal/mocks/mock_backup_sync.go +++ /dev/null @@ -1,202 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: SyncsLister,SyncsDescriber,SyncsCreator,SyncsUpdater,SyncsDeleter) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockSyncsLister is a mock of SyncsLister interface. -type MockSyncsLister struct { - ctrl *gomock.Controller - recorder *MockSyncsListerMockRecorder -} - -// MockSyncsListerMockRecorder is the mock recorder for MockSyncsLister. -type MockSyncsListerMockRecorder struct { - mock *MockSyncsLister -} - -// NewMockSyncsLister creates a new mock instance. -func NewMockSyncsLister(ctrl *gomock.Controller) *MockSyncsLister { - mock := &MockSyncsLister{ctrl: ctrl} - mock.recorder = &MockSyncsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSyncsLister) EXPECT() *MockSyncsListerMockRecorder { - return m.recorder -} - -// ListSyncs mocks base method. -func (m *MockSyncsLister) ListSyncs(arg0 *mongodbatlas.ListOptions) (*opsmngr.BackupStores, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListSyncs", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStores) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListSyncs indicates an expected call of ListSyncs. -func (mr *MockSyncsListerMockRecorder) ListSyncs(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListSyncs", reflect.TypeOf((*MockSyncsLister)(nil).ListSyncs), arg0) -} - -// MockSyncsDescriber is a mock of SyncsDescriber interface. -type MockSyncsDescriber struct { - ctrl *gomock.Controller - recorder *MockSyncsDescriberMockRecorder -} - -// MockSyncsDescriberMockRecorder is the mock recorder for MockSyncsDescriber. -type MockSyncsDescriberMockRecorder struct { - mock *MockSyncsDescriber -} - -// NewMockSyncsDescriber creates a new mock instance. -func NewMockSyncsDescriber(ctrl *gomock.Controller) *MockSyncsDescriber { - mock := &MockSyncsDescriber{ctrl: ctrl} - mock.recorder = &MockSyncsDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSyncsDescriber) EXPECT() *MockSyncsDescriberMockRecorder { - return m.recorder -} - -// GetSync mocks base method. -func (m *MockSyncsDescriber) GetSync(arg0 string) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSync", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSync indicates an expected call of GetSync. -func (mr *MockSyncsDescriberMockRecorder) GetSync(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSync", reflect.TypeOf((*MockSyncsDescriber)(nil).GetSync), arg0) -} - -// MockSyncsCreator is a mock of SyncsCreator interface. -type MockSyncsCreator struct { - ctrl *gomock.Controller - recorder *MockSyncsCreatorMockRecorder -} - -// MockSyncsCreatorMockRecorder is the mock recorder for MockSyncsCreator. -type MockSyncsCreatorMockRecorder struct { - mock *MockSyncsCreator -} - -// NewMockSyncsCreator creates a new mock instance. -func NewMockSyncsCreator(ctrl *gomock.Controller) *MockSyncsCreator { - mock := &MockSyncsCreator{ctrl: ctrl} - mock.recorder = &MockSyncsCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSyncsCreator) EXPECT() *MockSyncsCreatorMockRecorder { - return m.recorder -} - -// CreateSync mocks base method. -func (m *MockSyncsCreator) CreateSync(arg0 *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateSync", arg0) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateSync indicates an expected call of CreateSync. -func (mr *MockSyncsCreatorMockRecorder) CreateSync(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSync", reflect.TypeOf((*MockSyncsCreator)(nil).CreateSync), arg0) -} - -// MockSyncsUpdater is a mock of SyncsUpdater interface. -type MockSyncsUpdater struct { - ctrl *gomock.Controller - recorder *MockSyncsUpdaterMockRecorder -} - -// MockSyncsUpdaterMockRecorder is the mock recorder for MockSyncsUpdater. -type MockSyncsUpdaterMockRecorder struct { - mock *MockSyncsUpdater -} - -// NewMockSyncsUpdater creates a new mock instance. -func NewMockSyncsUpdater(ctrl *gomock.Controller) *MockSyncsUpdater { - mock := &MockSyncsUpdater{ctrl: ctrl} - mock.recorder = &MockSyncsUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSyncsUpdater) EXPECT() *MockSyncsUpdaterMockRecorder { - return m.recorder -} - -// UpdateSync mocks base method. -func (m *MockSyncsUpdater) UpdateSync(arg0 string, arg1 *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateSync", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.BackupStore) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateSync indicates an expected call of UpdateSync. -func (mr *MockSyncsUpdaterMockRecorder) UpdateSync(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateSync", reflect.TypeOf((*MockSyncsUpdater)(nil).UpdateSync), arg0, arg1) -} - -// MockSyncsDeleter is a mock of SyncsDeleter interface. -type MockSyncsDeleter struct { - ctrl *gomock.Controller - recorder *MockSyncsDeleterMockRecorder -} - -// MockSyncsDeleterMockRecorder is the mock recorder for MockSyncsDeleter. -type MockSyncsDeleterMockRecorder struct { - mock *MockSyncsDeleter -} - -// NewMockSyncsDeleter creates a new mock instance. -func NewMockSyncsDeleter(ctrl *gomock.Controller) *MockSyncsDeleter { - mock := &MockSyncsDeleter{ctrl: ctrl} - mock.recorder = &MockSyncsDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSyncsDeleter) EXPECT() *MockSyncsDeleterMockRecorder { - return m.recorder -} - -// DeleteSync mocks base method. -func (m *MockSyncsDeleter) DeleteSync(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteSync", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteSync indicates an expected call of DeleteSync. -func (mr *MockSyncsDeleterMockRecorder) DeleteSync(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSync", reflect.TypeOf((*MockSyncsDeleter)(nil).DeleteSync), arg0) -} diff --git a/internal/mocks/mock_continuous_backup.go b/internal/mocks/mock_continuous_backup.go deleted file mode 100644 index 16c7354488..0000000000 --- a/internal/mocks/mock_continuous_backup.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: CheckpointsLister,ContinuousJobLister,ContinuousJobCreator,ContinuousSnapshotsLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockCheckpointsLister is a mock of CheckpointsLister interface. -type MockCheckpointsLister struct { - ctrl *gomock.Controller - recorder *MockCheckpointsListerMockRecorder -} - -// MockCheckpointsListerMockRecorder is the mock recorder for MockCheckpointsLister. -type MockCheckpointsListerMockRecorder struct { - mock *MockCheckpointsLister -} - -// NewMockCheckpointsLister creates a new mock instance. -func NewMockCheckpointsLister(ctrl *gomock.Controller) *MockCheckpointsLister { - mock := &MockCheckpointsLister{ctrl: ctrl} - mock.recorder = &MockCheckpointsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockCheckpointsLister) EXPECT() *MockCheckpointsListerMockRecorder { - return m.recorder -} - -// Checkpoints mocks base method. -func (m *MockCheckpointsLister) Checkpoints(arg0, arg1 string, arg2 *mongodbatlas.ListOptions) (*mongodbatlas.Checkpoints, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Checkpoints", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.Checkpoints) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Checkpoints indicates an expected call of Checkpoints. -func (mr *MockCheckpointsListerMockRecorder) Checkpoints(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Checkpoints", reflect.TypeOf((*MockCheckpointsLister)(nil).Checkpoints), arg0, arg1, arg2) -} - -// MockContinuousJobLister is a mock of ContinuousJobLister interface. -type MockContinuousJobLister struct { - ctrl *gomock.Controller - recorder *MockContinuousJobListerMockRecorder -} - -// MockContinuousJobListerMockRecorder is the mock recorder for MockContinuousJobLister. -type MockContinuousJobListerMockRecorder struct { - mock *MockContinuousJobLister -} - -// NewMockContinuousJobLister creates a new mock instance. -func NewMockContinuousJobLister(ctrl *gomock.Controller) *MockContinuousJobLister { - mock := &MockContinuousJobLister{ctrl: ctrl} - mock.recorder = &MockContinuousJobListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockContinuousJobLister) EXPECT() *MockContinuousJobListerMockRecorder { - return m.recorder -} - -// ContinuousRestoreJobs mocks base method. -func (m *MockContinuousJobLister) ContinuousRestoreJobs(arg0, arg1 string, arg2 *mongodbatlas.ListOptions) (*mongodbatlas.ContinuousJobs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ContinuousRestoreJobs", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.ContinuousJobs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ContinuousRestoreJobs indicates an expected call of ContinuousRestoreJobs. -func (mr *MockContinuousJobListerMockRecorder) ContinuousRestoreJobs(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContinuousRestoreJobs", reflect.TypeOf((*MockContinuousJobLister)(nil).ContinuousRestoreJobs), arg0, arg1, arg2) -} - -// MockContinuousJobCreator is a mock of ContinuousJobCreator interface. -type MockContinuousJobCreator struct { - ctrl *gomock.Controller - recorder *MockContinuousJobCreatorMockRecorder -} - -// MockContinuousJobCreatorMockRecorder is the mock recorder for MockContinuousJobCreator. -type MockContinuousJobCreatorMockRecorder struct { - mock *MockContinuousJobCreator -} - -// NewMockContinuousJobCreator creates a new mock instance. -func NewMockContinuousJobCreator(ctrl *gomock.Controller) *MockContinuousJobCreator { - mock := &MockContinuousJobCreator{ctrl: ctrl} - mock.recorder = &MockContinuousJobCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockContinuousJobCreator) EXPECT() *MockContinuousJobCreatorMockRecorder { - return m.recorder -} - -// CreateContinuousRestoreJob mocks base method. -func (m *MockContinuousJobCreator) CreateContinuousRestoreJob(arg0, arg1 string, arg2 *mongodbatlas.ContinuousJobRequest) (*mongodbatlas.ContinuousJobs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateContinuousRestoreJob", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.ContinuousJobs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateContinuousRestoreJob indicates an expected call of CreateContinuousRestoreJob. -func (mr *MockContinuousJobCreatorMockRecorder) CreateContinuousRestoreJob(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateContinuousRestoreJob", reflect.TypeOf((*MockContinuousJobCreator)(nil).CreateContinuousRestoreJob), arg0, arg1, arg2) -} - -// MockContinuousSnapshotsLister is a mock of ContinuousSnapshotsLister interface. -type MockContinuousSnapshotsLister struct { - ctrl *gomock.Controller - recorder *MockContinuousSnapshotsListerMockRecorder -} - -// MockContinuousSnapshotsListerMockRecorder is the mock recorder for MockContinuousSnapshotsLister. -type MockContinuousSnapshotsListerMockRecorder struct { - mock *MockContinuousSnapshotsLister -} - -// NewMockContinuousSnapshotsLister creates a new mock instance. -func NewMockContinuousSnapshotsLister(ctrl *gomock.Controller) *MockContinuousSnapshotsLister { - mock := &MockContinuousSnapshotsLister{ctrl: ctrl} - mock.recorder = &MockContinuousSnapshotsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockContinuousSnapshotsLister) EXPECT() *MockContinuousSnapshotsListerMockRecorder { - return m.recorder -} - -// ContinuousSnapshots mocks base method. -func (m *MockContinuousSnapshotsLister) ContinuousSnapshots(arg0, arg1 string, arg2 *mongodbatlas.ListOptions) (*mongodbatlas.ContinuousSnapshots, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ContinuousSnapshots", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.ContinuousSnapshots) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ContinuousSnapshots indicates an expected call of ContinuousSnapshots. -func (mr *MockContinuousSnapshotsListerMockRecorder) ContinuousSnapshots(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ContinuousSnapshots", reflect.TypeOf((*MockContinuousSnapshotsLister)(nil).ContinuousSnapshots), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_data_federation.go b/internal/mocks/mock_data_federation.go deleted file mode 100644 index 19f6461ac2..0000000000 --- a/internal/mocks/mock_data_federation.go +++ /dev/null @@ -1,103 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: DataFederationLister,DataFederationStore) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockDataFederationLister is a mock of DataFederationLister interface. -type MockDataFederationLister struct { - ctrl *gomock.Controller - recorder *MockDataFederationListerMockRecorder -} - -// MockDataFederationListerMockRecorder is the mock recorder for MockDataFederationLister. -type MockDataFederationListerMockRecorder struct { - mock *MockDataFederationLister -} - -// NewMockDataFederationLister creates a new mock instance. -func NewMockDataFederationLister(ctrl *gomock.Controller) *MockDataFederationLister { - mock := &MockDataFederationLister{ctrl: ctrl} - mock.recorder = &MockDataFederationListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDataFederationLister) EXPECT() *MockDataFederationListerMockRecorder { - return m.recorder -} - -// DataFederationList mocks base method. -func (m *MockDataFederationLister) DataFederationList(arg0 string) ([]admin.DataLakeTenant, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DataFederationList", arg0) - ret0, _ := ret[0].([]admin.DataLakeTenant) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DataFederationList indicates an expected call of DataFederationList. -func (mr *MockDataFederationListerMockRecorder) DataFederationList(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DataFederationList", reflect.TypeOf((*MockDataFederationLister)(nil).DataFederationList), arg0) -} - -// MockDataFederationStore is a mock of DataFederationStore interface. -type MockDataFederationStore struct { - ctrl *gomock.Controller - recorder *MockDataFederationStoreMockRecorder -} - -// MockDataFederationStoreMockRecorder is the mock recorder for MockDataFederationStore. -type MockDataFederationStoreMockRecorder struct { - mock *MockDataFederationStore -} - -// NewMockDataFederationStore creates a new mock instance. -func NewMockDataFederationStore(ctrl *gomock.Controller) *MockDataFederationStore { - mock := &MockDataFederationStore{ctrl: ctrl} - mock.recorder = &MockDataFederationStoreMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDataFederationStore) EXPECT() *MockDataFederationStoreMockRecorder { - return m.recorder -} - -// DataFederation mocks base method. -func (m *MockDataFederationStore) DataFederation(arg0, arg1 string) (*admin.DataLakeTenant, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DataFederation", arg0, arg1) - ret0, _ := ret[0].(*admin.DataLakeTenant) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DataFederation indicates an expected call of DataFederation. -func (mr *MockDataFederationStoreMockRecorder) DataFederation(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DataFederation", reflect.TypeOf((*MockDataFederationStore)(nil).DataFederation), arg0, arg1) -} - -// DataFederationList mocks base method. -func (m *MockDataFederationStore) DataFederationList(arg0 string) ([]admin.DataLakeTenant, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DataFederationList", arg0) - ret0, _ := ret[0].([]admin.DataLakeTenant) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DataFederationList indicates an expected call of DataFederationList. -func (mr *MockDataFederationStoreMockRecorder) DataFederationList(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DataFederationList", reflect.TypeOf((*MockDataFederationStore)(nil).DataFederationList), arg0) -} diff --git a/internal/mocks/mock_deployments.go b/internal/mocks/mock_deployments.go deleted file mode 100644 index b745527ce9..0000000000 --- a/internal/mocks/mock_deployments.go +++ /dev/null @@ -1,203 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: HostLister,HostDescriber,HostDatabaseLister,HostDisksLister,HostByHostnameDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockHostLister is a mock of HostLister interface. -type MockHostLister struct { - ctrl *gomock.Controller - recorder *MockHostListerMockRecorder -} - -// MockHostListerMockRecorder is the mock recorder for MockHostLister. -type MockHostListerMockRecorder struct { - mock *MockHostLister -} - -// NewMockHostLister creates a new mock instance. -func NewMockHostLister(ctrl *gomock.Controller) *MockHostLister { - mock := &MockHostLister{ctrl: ctrl} - mock.recorder = &MockHostListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHostLister) EXPECT() *MockHostListerMockRecorder { - return m.recorder -} - -// Hosts mocks base method. -func (m *MockHostLister) Hosts(arg0 string, arg1 *opsmngr.HostListOptions) (*opsmngr.Hosts, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Hosts", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.Hosts) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Hosts indicates an expected call of Hosts. -func (mr *MockHostListerMockRecorder) Hosts(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Hosts", reflect.TypeOf((*MockHostLister)(nil).Hosts), arg0, arg1) -} - -// MockHostDescriber is a mock of HostDescriber interface. -type MockHostDescriber struct { - ctrl *gomock.Controller - recorder *MockHostDescriberMockRecorder -} - -// MockHostDescriberMockRecorder is the mock recorder for MockHostDescriber. -type MockHostDescriberMockRecorder struct { - mock *MockHostDescriber -} - -// NewMockHostDescriber creates a new mock instance. -func NewMockHostDescriber(ctrl *gomock.Controller) *MockHostDescriber { - mock := &MockHostDescriber{ctrl: ctrl} - mock.recorder = &MockHostDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHostDescriber) EXPECT() *MockHostDescriberMockRecorder { - return m.recorder -} - -// Host mocks base method. -func (m *MockHostDescriber) Host(arg0, arg1 string) (*opsmngr.Host, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Host", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.Host) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Host indicates an expected call of Host. -func (mr *MockHostDescriberMockRecorder) Host(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Host", reflect.TypeOf((*MockHostDescriber)(nil).Host), arg0, arg1) -} - -// MockHostDatabaseLister is a mock of HostDatabaseLister interface. -type MockHostDatabaseLister struct { - ctrl *gomock.Controller - recorder *MockHostDatabaseListerMockRecorder -} - -// MockHostDatabaseListerMockRecorder is the mock recorder for MockHostDatabaseLister. -type MockHostDatabaseListerMockRecorder struct { - mock *MockHostDatabaseLister -} - -// NewMockHostDatabaseLister creates a new mock instance. -func NewMockHostDatabaseLister(ctrl *gomock.Controller) *MockHostDatabaseLister { - mock := &MockHostDatabaseLister{ctrl: ctrl} - mock.recorder = &MockHostDatabaseListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHostDatabaseLister) EXPECT() *MockHostDatabaseListerMockRecorder { - return m.recorder -} - -// HostDatabases mocks base method. -func (m *MockHostDatabaseLister) HostDatabases(arg0, arg1 string, arg2 *mongodbatlas.ListOptions) (*mongodbatlas.ProcessDatabasesResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HostDatabases", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.ProcessDatabasesResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HostDatabases indicates an expected call of HostDatabases. -func (mr *MockHostDatabaseListerMockRecorder) HostDatabases(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostDatabases", reflect.TypeOf((*MockHostDatabaseLister)(nil).HostDatabases), arg0, arg1, arg2) -} - -// MockHostDisksLister is a mock of HostDisksLister interface. -type MockHostDisksLister struct { - ctrl *gomock.Controller - recorder *MockHostDisksListerMockRecorder -} - -// MockHostDisksListerMockRecorder is the mock recorder for MockHostDisksLister. -type MockHostDisksListerMockRecorder struct { - mock *MockHostDisksLister -} - -// NewMockHostDisksLister creates a new mock instance. -func NewMockHostDisksLister(ctrl *gomock.Controller) *MockHostDisksLister { - mock := &MockHostDisksLister{ctrl: ctrl} - mock.recorder = &MockHostDisksListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHostDisksLister) EXPECT() *MockHostDisksListerMockRecorder { - return m.recorder -} - -// HostDisks mocks base method. -func (m *MockHostDisksLister) HostDisks(arg0, arg1 string, arg2 *mongodbatlas.ListOptions) (*mongodbatlas.ProcessDisksResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HostDisks", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.ProcessDisksResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HostDisks indicates an expected call of HostDisks. -func (mr *MockHostDisksListerMockRecorder) HostDisks(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostDisks", reflect.TypeOf((*MockHostDisksLister)(nil).HostDisks), arg0, arg1, arg2) -} - -// MockHostByHostnameDescriber is a mock of HostByHostnameDescriber interface. -type MockHostByHostnameDescriber struct { - ctrl *gomock.Controller - recorder *MockHostByHostnameDescriberMockRecorder -} - -// MockHostByHostnameDescriberMockRecorder is the mock recorder for MockHostByHostnameDescriber. -type MockHostByHostnameDescriberMockRecorder struct { - mock *MockHostByHostnameDescriber -} - -// NewMockHostByHostnameDescriber creates a new mock instance. -func NewMockHostByHostnameDescriber(ctrl *gomock.Controller) *MockHostByHostnameDescriber { - mock := &MockHostByHostnameDescriber{ctrl: ctrl} - mock.recorder = &MockHostByHostnameDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHostByHostnameDescriber) EXPECT() *MockHostByHostnameDescriberMockRecorder { - return m.recorder -} - -// HostByHostname mocks base method. -func (m *MockHostByHostnameDescriber) HostByHostname(arg0, arg1 string, arg2 int) (*opsmngr.Host, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HostByHostname", arg0, arg1, arg2) - ret0, _ := ret[0].(*opsmngr.Host) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HostByHostname indicates an expected call of HostByHostname. -func (mr *MockHostByHostnameDescriberMockRecorder) HostByHostname(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostByHostname", reflect.TypeOf((*MockHostByHostnameDescriber)(nil).HostByHostname), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_diagnose_archive.go b/internal/mocks/mock_diagnose_archive.go deleted file mode 100644 index d90d45bbce..0000000000 --- a/internal/mocks/mock_diagnose_archive.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: ArchivesDownloader) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - io "io" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockArchivesDownloader is a mock of ArchivesDownloader interface. -type MockArchivesDownloader struct { - ctrl *gomock.Controller - recorder *MockArchivesDownloaderMockRecorder -} - -// MockArchivesDownloaderMockRecorder is the mock recorder for MockArchivesDownloader. -type MockArchivesDownloaderMockRecorder struct { - mock *MockArchivesDownloader -} - -// NewMockArchivesDownloader creates a new mock instance. -func NewMockArchivesDownloader(ctrl *gomock.Controller) *MockArchivesDownloader { - mock := &MockArchivesDownloader{ctrl: ctrl} - mock.recorder = &MockArchivesDownloaderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockArchivesDownloader) EXPECT() *MockArchivesDownloaderMockRecorder { - return m.recorder -} - -// DownloadArchive mocks base method. -func (m *MockArchivesDownloader) DownloadArchive(arg0 string, arg1 *opsmngr.DiagnosticsListOpts, arg2 io.Writer) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DownloadArchive", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// DownloadArchive indicates an expected call of DownloadArchive. -func (mr *MockArchivesDownloaderMockRecorder) DownloadArchive(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DownloadArchive", reflect.TypeOf((*MockArchivesDownloader)(nil).DownloadArchive), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_events.go b/internal/mocks/mock_events.go deleted file mode 100644 index 0034019101..0000000000 --- a/internal/mocks/mock_events.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: OrganizationEventLister,ProjectEventLister,EventLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockOrganizationEventLister is a mock of OrganizationEventLister interface. -type MockOrganizationEventLister struct { - ctrl *gomock.Controller - recorder *MockOrganizationEventListerMockRecorder -} - -// MockOrganizationEventListerMockRecorder is the mock recorder for MockOrganizationEventLister. -type MockOrganizationEventListerMockRecorder struct { - mock *MockOrganizationEventLister -} - -// NewMockOrganizationEventLister creates a new mock instance. -func NewMockOrganizationEventLister(ctrl *gomock.Controller) *MockOrganizationEventLister { - mock := &MockOrganizationEventLister{ctrl: ctrl} - mock.recorder = &MockOrganizationEventListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationEventLister) EXPECT() *MockOrganizationEventListerMockRecorder { - return m.recorder -} - -// OrganizationEvents mocks base method. -func (m *MockOrganizationEventLister) OrganizationEvents(arg0 string, arg1 *mongodbatlas.EventListOptions) (*mongodbatlas.EventResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationEvents", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.EventResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationEvents indicates an expected call of OrganizationEvents. -func (mr *MockOrganizationEventListerMockRecorder) OrganizationEvents(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationEvents", reflect.TypeOf((*MockOrganizationEventLister)(nil).OrganizationEvents), arg0, arg1) -} - -// MockProjectEventLister is a mock of ProjectEventLister interface. -type MockProjectEventLister struct { - ctrl *gomock.Controller - recorder *MockProjectEventListerMockRecorder -} - -// MockProjectEventListerMockRecorder is the mock recorder for MockProjectEventLister. -type MockProjectEventListerMockRecorder struct { - mock *MockProjectEventLister -} - -// NewMockProjectEventLister creates a new mock instance. -func NewMockProjectEventLister(ctrl *gomock.Controller) *MockProjectEventLister { - mock := &MockProjectEventLister{ctrl: ctrl} - mock.recorder = &MockProjectEventListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectEventLister) EXPECT() *MockProjectEventListerMockRecorder { - return m.recorder -} - -// ProjectEvents mocks base method. -func (m *MockProjectEventLister) ProjectEvents(arg0 string, arg1 *mongodbatlas.EventListOptions) (*mongodbatlas.EventResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectEvents", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.EventResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectEvents indicates an expected call of ProjectEvents. -func (mr *MockProjectEventListerMockRecorder) ProjectEvents(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectEvents", reflect.TypeOf((*MockProjectEventLister)(nil).ProjectEvents), arg0, arg1) -} - -// MockEventLister is a mock of EventLister interface. -type MockEventLister struct { - ctrl *gomock.Controller - recorder *MockEventListerMockRecorder -} - -// MockEventListerMockRecorder is the mock recorder for MockEventLister. -type MockEventListerMockRecorder struct { - mock *MockEventLister -} - -// NewMockEventLister creates a new mock instance. -func NewMockEventLister(ctrl *gomock.Controller) *MockEventLister { - mock := &MockEventLister{ctrl: ctrl} - mock.recorder = &MockEventListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockEventLister) EXPECT() *MockEventListerMockRecorder { - return m.recorder -} - -// OrganizationEvents mocks base method. -func (m *MockEventLister) OrganizationEvents(arg0 string, arg1 *mongodbatlas.EventListOptions) (*mongodbatlas.EventResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationEvents", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.EventResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationEvents indicates an expected call of OrganizationEvents. -func (mr *MockEventListerMockRecorder) OrganizationEvents(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationEvents", reflect.TypeOf((*MockEventLister)(nil).OrganizationEvents), arg0, arg1) -} - -// ProjectEvents mocks base method. -func (m *MockEventLister) ProjectEvents(arg0 string, arg1 *mongodbatlas.EventListOptions) (*mongodbatlas.EventResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectEvents", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.EventResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectEvents indicates an expected call of ProjectEvents. -func (mr *MockEventListerMockRecorder) ProjectEvents(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectEvents", reflect.TypeOf((*MockEventLister)(nil).ProjectEvents), arg0, arg1) -} diff --git a/internal/mocks/mock_feature_control_policy.go b/internal/mocks/mock_feature_control_policy.go deleted file mode 100644 index f57ef3086b..0000000000 --- a/internal/mocks/mock_feature_control_policy.go +++ /dev/null @@ -1,89 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: FeatureControlPoliciesLister,FeatureControlPoliciesUpdater) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockFeatureControlPoliciesLister is a mock of FeatureControlPoliciesLister interface. -type MockFeatureControlPoliciesLister struct { - ctrl *gomock.Controller - recorder *MockFeatureControlPoliciesListerMockRecorder -} - -// MockFeatureControlPoliciesListerMockRecorder is the mock recorder for MockFeatureControlPoliciesLister. -type MockFeatureControlPoliciesListerMockRecorder struct { - mock *MockFeatureControlPoliciesLister -} - -// NewMockFeatureControlPoliciesLister creates a new mock instance. -func NewMockFeatureControlPoliciesLister(ctrl *gomock.Controller) *MockFeatureControlPoliciesLister { - mock := &MockFeatureControlPoliciesLister{ctrl: ctrl} - mock.recorder = &MockFeatureControlPoliciesListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFeatureControlPoliciesLister) EXPECT() *MockFeatureControlPoliciesListerMockRecorder { - return m.recorder -} - -// FeatureControlPolicies mocks base method. -func (m *MockFeatureControlPoliciesLister) FeatureControlPolicies(arg0 string, arg1 *mongodbatlas.ListOptions) (*opsmngr.FeaturePolicy, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FeatureControlPolicies", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.FeaturePolicy) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// FeatureControlPolicies indicates an expected call of FeatureControlPolicies. -func (mr *MockFeatureControlPoliciesListerMockRecorder) FeatureControlPolicies(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FeatureControlPolicies", reflect.TypeOf((*MockFeatureControlPoliciesLister)(nil).FeatureControlPolicies), arg0, arg1) -} - -// MockFeatureControlPoliciesUpdater is a mock of FeatureControlPoliciesUpdater interface. -type MockFeatureControlPoliciesUpdater struct { - ctrl *gomock.Controller - recorder *MockFeatureControlPoliciesUpdaterMockRecorder -} - -// MockFeatureControlPoliciesUpdaterMockRecorder is the mock recorder for MockFeatureControlPoliciesUpdater. -type MockFeatureControlPoliciesUpdaterMockRecorder struct { - mock *MockFeatureControlPoliciesUpdater -} - -// NewMockFeatureControlPoliciesUpdater creates a new mock instance. -func NewMockFeatureControlPoliciesUpdater(ctrl *gomock.Controller) *MockFeatureControlPoliciesUpdater { - mock := &MockFeatureControlPoliciesUpdater{ctrl: ctrl} - mock.recorder = &MockFeatureControlPoliciesUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFeatureControlPoliciesUpdater) EXPECT() *MockFeatureControlPoliciesUpdaterMockRecorder { - return m.recorder -} - -// UpdateFeatureControlPolicy mocks base method. -func (m *MockFeatureControlPoliciesUpdater) UpdateFeatureControlPolicy(arg0 string, arg1 *opsmngr.FeaturePolicy) (*opsmngr.FeaturePolicy, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateFeatureControlPolicy", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.FeaturePolicy) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateFeatureControlPolicy indicates an expected call of UpdateFeatureControlPolicy. -func (mr *MockFeatureControlPoliciesUpdaterMockRecorder) UpdateFeatureControlPolicy(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateFeatureControlPolicy", reflect.TypeOf((*MockFeatureControlPoliciesUpdater)(nil).UpdateFeatureControlPolicy), arg0, arg1) -} diff --git a/internal/mocks/mock_global_alerts.go b/internal/mocks/mock_global_alerts.go deleted file mode 100644 index 799db8f1cc..0000000000 --- a/internal/mocks/mock_global_alerts.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: GlobalAlertLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockGlobalAlertLister is a mock of GlobalAlertLister interface. -type MockGlobalAlertLister struct { - ctrl *gomock.Controller - recorder *MockGlobalAlertListerMockRecorder -} - -// MockGlobalAlertListerMockRecorder is the mock recorder for MockGlobalAlertLister. -type MockGlobalAlertListerMockRecorder struct { - mock *MockGlobalAlertLister -} - -// NewMockGlobalAlertLister creates a new mock instance. -func NewMockGlobalAlertLister(ctrl *gomock.Controller) *MockGlobalAlertLister { - mock := &MockGlobalAlertLister{ctrl: ctrl} - mock.recorder = &MockGlobalAlertListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAlertLister) EXPECT() *MockGlobalAlertListerMockRecorder { - return m.recorder -} - -// GlobalAlerts mocks base method. -func (m *MockGlobalAlertLister) GlobalAlerts(arg0 *mongodbatlas.AlertsListOptions) (*opsmngr.GlobalAlerts, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GlobalAlerts", arg0) - ret0, _ := ret[0].(*opsmngr.GlobalAlerts) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GlobalAlerts indicates an expected call of GlobalAlerts. -func (mr *MockGlobalAlertListerMockRecorder) GlobalAlerts(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GlobalAlerts", reflect.TypeOf((*MockGlobalAlertLister)(nil).GlobalAlerts), arg0) -} diff --git a/internal/mocks/mock_global_api_keys.go b/internal/mocks/mock_global_api_keys.go deleted file mode 100644 index d86069d1ee..0000000000 --- a/internal/mocks/mock_global_api_keys.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: GlobalAPIKeyLister,GlobalAPIKeyDescriber,GlobalAPIKeyUpdater,GlobalAPIKeyCreator,GlobalAPIKeyDeleter) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockGlobalAPIKeyLister is a mock of GlobalAPIKeyLister interface. -type MockGlobalAPIKeyLister struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyListerMockRecorder -} - -// MockGlobalAPIKeyListerMockRecorder is the mock recorder for MockGlobalAPIKeyLister. -type MockGlobalAPIKeyListerMockRecorder struct { - mock *MockGlobalAPIKeyLister -} - -// NewMockGlobalAPIKeyLister creates a new mock instance. -func NewMockGlobalAPIKeyLister(ctrl *gomock.Controller) *MockGlobalAPIKeyLister { - mock := &MockGlobalAPIKeyLister{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyLister) EXPECT() *MockGlobalAPIKeyListerMockRecorder { - return m.recorder -} - -// GlobalAPIKeys mocks base method. -func (m *MockGlobalAPIKeyLister) GlobalAPIKeys(arg0 *mongodbatlas.ListOptions) ([]mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GlobalAPIKeys", arg0) - ret0, _ := ret[0].([]mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GlobalAPIKeys indicates an expected call of GlobalAPIKeys. -func (mr *MockGlobalAPIKeyListerMockRecorder) GlobalAPIKeys(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GlobalAPIKeys", reflect.TypeOf((*MockGlobalAPIKeyLister)(nil).GlobalAPIKeys), arg0) -} - -// MockGlobalAPIKeyDescriber is a mock of GlobalAPIKeyDescriber interface. -type MockGlobalAPIKeyDescriber struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyDescriberMockRecorder -} - -// MockGlobalAPIKeyDescriberMockRecorder is the mock recorder for MockGlobalAPIKeyDescriber. -type MockGlobalAPIKeyDescriberMockRecorder struct { - mock *MockGlobalAPIKeyDescriber -} - -// NewMockGlobalAPIKeyDescriber creates a new mock instance. -func NewMockGlobalAPIKeyDescriber(ctrl *gomock.Controller) *MockGlobalAPIKeyDescriber { - mock := &MockGlobalAPIKeyDescriber{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyDescriber) EXPECT() *MockGlobalAPIKeyDescriberMockRecorder { - return m.recorder -} - -// GlobalAPIKey mocks base method. -func (m *MockGlobalAPIKeyDescriber) GlobalAPIKey(arg0 string) (*mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GlobalAPIKey", arg0) - ret0, _ := ret[0].(*mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GlobalAPIKey indicates an expected call of GlobalAPIKey. -func (mr *MockGlobalAPIKeyDescriberMockRecorder) GlobalAPIKey(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GlobalAPIKey", reflect.TypeOf((*MockGlobalAPIKeyDescriber)(nil).GlobalAPIKey), arg0) -} - -// MockGlobalAPIKeyUpdater is a mock of GlobalAPIKeyUpdater interface. -type MockGlobalAPIKeyUpdater struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyUpdaterMockRecorder -} - -// MockGlobalAPIKeyUpdaterMockRecorder is the mock recorder for MockGlobalAPIKeyUpdater. -type MockGlobalAPIKeyUpdaterMockRecorder struct { - mock *MockGlobalAPIKeyUpdater -} - -// NewMockGlobalAPIKeyUpdater creates a new mock instance. -func NewMockGlobalAPIKeyUpdater(ctrl *gomock.Controller) *MockGlobalAPIKeyUpdater { - mock := &MockGlobalAPIKeyUpdater{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyUpdater) EXPECT() *MockGlobalAPIKeyUpdaterMockRecorder { - return m.recorder -} - -// UpdateGlobalAPIKey mocks base method. -func (m *MockGlobalAPIKeyUpdater) UpdateGlobalAPIKey(arg0 string, arg1 *mongodbatlas.APIKeyInput) (*mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateGlobalAPIKey", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateGlobalAPIKey indicates an expected call of UpdateGlobalAPIKey. -func (mr *MockGlobalAPIKeyUpdaterMockRecorder) UpdateGlobalAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateGlobalAPIKey", reflect.TypeOf((*MockGlobalAPIKeyUpdater)(nil).UpdateGlobalAPIKey), arg0, arg1) -} - -// MockGlobalAPIKeyCreator is a mock of GlobalAPIKeyCreator interface. -type MockGlobalAPIKeyCreator struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyCreatorMockRecorder -} - -// MockGlobalAPIKeyCreatorMockRecorder is the mock recorder for MockGlobalAPIKeyCreator. -type MockGlobalAPIKeyCreatorMockRecorder struct { - mock *MockGlobalAPIKeyCreator -} - -// NewMockGlobalAPIKeyCreator creates a new mock instance. -func NewMockGlobalAPIKeyCreator(ctrl *gomock.Controller) *MockGlobalAPIKeyCreator { - mock := &MockGlobalAPIKeyCreator{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyCreator) EXPECT() *MockGlobalAPIKeyCreatorMockRecorder { - return m.recorder -} - -// CreateGlobalAPIKey mocks base method. -func (m *MockGlobalAPIKeyCreator) CreateGlobalAPIKey(arg0 *mongodbatlas.APIKeyInput) (*mongodbatlas.APIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateGlobalAPIKey", arg0) - ret0, _ := ret[0].(*mongodbatlas.APIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateGlobalAPIKey indicates an expected call of CreateGlobalAPIKey. -func (mr *MockGlobalAPIKeyCreatorMockRecorder) CreateGlobalAPIKey(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateGlobalAPIKey", reflect.TypeOf((*MockGlobalAPIKeyCreator)(nil).CreateGlobalAPIKey), arg0) -} - -// MockGlobalAPIKeyDeleter is a mock of GlobalAPIKeyDeleter interface. -type MockGlobalAPIKeyDeleter struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyDeleterMockRecorder -} - -// MockGlobalAPIKeyDeleterMockRecorder is the mock recorder for MockGlobalAPIKeyDeleter. -type MockGlobalAPIKeyDeleterMockRecorder struct { - mock *MockGlobalAPIKeyDeleter -} - -// NewMockGlobalAPIKeyDeleter creates a new mock instance. -func NewMockGlobalAPIKeyDeleter(ctrl *gomock.Controller) *MockGlobalAPIKeyDeleter { - mock := &MockGlobalAPIKeyDeleter{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyDeleter) EXPECT() *MockGlobalAPIKeyDeleterMockRecorder { - return m.recorder -} - -// DeleteGlobalAPIKey mocks base method. -func (m *MockGlobalAPIKeyDeleter) DeleteGlobalAPIKey(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteGlobalAPIKey", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteGlobalAPIKey indicates an expected call of DeleteGlobalAPIKey. -func (mr *MockGlobalAPIKeyDeleterMockRecorder) DeleteGlobalAPIKey(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteGlobalAPIKey", reflect.TypeOf((*MockGlobalAPIKeyDeleter)(nil).DeleteGlobalAPIKey), arg0) -} diff --git a/internal/mocks/mock_global_api_keys_access_list.go b/internal/mocks/mock_global_api_keys_access_list.go deleted file mode 100644 index 38741a5d78..0000000000 --- a/internal/mocks/mock_global_api_keys_access_list.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: GlobalAPIKeyWhitelistLister,GlobalAPIKeyWhitelistDescriber,GlobalAPIKeyWhitelistCreator,GlobalAPIKeyWhitelistDeleter) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockGlobalAPIKeyWhitelistLister is a mock of GlobalAPIKeyWhitelistLister interface. -type MockGlobalAPIKeyWhitelistLister struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyWhitelistListerMockRecorder -} - -// MockGlobalAPIKeyWhitelistListerMockRecorder is the mock recorder for MockGlobalAPIKeyWhitelistLister. -type MockGlobalAPIKeyWhitelistListerMockRecorder struct { - mock *MockGlobalAPIKeyWhitelistLister -} - -// NewMockGlobalAPIKeyWhitelistLister creates a new mock instance. -func NewMockGlobalAPIKeyWhitelistLister(ctrl *gomock.Controller) *MockGlobalAPIKeyWhitelistLister { - mock := &MockGlobalAPIKeyWhitelistLister{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyWhitelistListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyWhitelistLister) EXPECT() *MockGlobalAPIKeyWhitelistListerMockRecorder { - return m.recorder -} - -// GlobalAPIKeyWhitelists mocks base method. -func (m *MockGlobalAPIKeyWhitelistLister) GlobalAPIKeyWhitelists(arg0 *mongodbatlas.ListOptions) (*opsmngr.GlobalWhitelistAPIKeys, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GlobalAPIKeyWhitelists", arg0) - ret0, _ := ret[0].(*opsmngr.GlobalWhitelistAPIKeys) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GlobalAPIKeyWhitelists indicates an expected call of GlobalAPIKeyWhitelists. -func (mr *MockGlobalAPIKeyWhitelistListerMockRecorder) GlobalAPIKeyWhitelists(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GlobalAPIKeyWhitelists", reflect.TypeOf((*MockGlobalAPIKeyWhitelistLister)(nil).GlobalAPIKeyWhitelists), arg0) -} - -// MockGlobalAPIKeyWhitelistDescriber is a mock of GlobalAPIKeyWhitelistDescriber interface. -type MockGlobalAPIKeyWhitelistDescriber struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyWhitelistDescriberMockRecorder -} - -// MockGlobalAPIKeyWhitelistDescriberMockRecorder is the mock recorder for MockGlobalAPIKeyWhitelistDescriber. -type MockGlobalAPIKeyWhitelistDescriberMockRecorder struct { - mock *MockGlobalAPIKeyWhitelistDescriber -} - -// NewMockGlobalAPIKeyWhitelistDescriber creates a new mock instance. -func NewMockGlobalAPIKeyWhitelistDescriber(ctrl *gomock.Controller) *MockGlobalAPIKeyWhitelistDescriber { - mock := &MockGlobalAPIKeyWhitelistDescriber{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyWhitelistDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyWhitelistDescriber) EXPECT() *MockGlobalAPIKeyWhitelistDescriberMockRecorder { - return m.recorder -} - -// GlobalAPIKeyWhitelist mocks base method. -func (m *MockGlobalAPIKeyWhitelistDescriber) GlobalAPIKeyWhitelist(arg0 string) (*opsmngr.GlobalWhitelistAPIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GlobalAPIKeyWhitelist", arg0) - ret0, _ := ret[0].(*opsmngr.GlobalWhitelistAPIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GlobalAPIKeyWhitelist indicates an expected call of GlobalAPIKeyWhitelist. -func (mr *MockGlobalAPIKeyWhitelistDescriberMockRecorder) GlobalAPIKeyWhitelist(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GlobalAPIKeyWhitelist", reflect.TypeOf((*MockGlobalAPIKeyWhitelistDescriber)(nil).GlobalAPIKeyWhitelist), arg0) -} - -// MockGlobalAPIKeyWhitelistCreator is a mock of GlobalAPIKeyWhitelistCreator interface. -type MockGlobalAPIKeyWhitelistCreator struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyWhitelistCreatorMockRecorder -} - -// MockGlobalAPIKeyWhitelistCreatorMockRecorder is the mock recorder for MockGlobalAPIKeyWhitelistCreator. -type MockGlobalAPIKeyWhitelistCreatorMockRecorder struct { - mock *MockGlobalAPIKeyWhitelistCreator -} - -// NewMockGlobalAPIKeyWhitelistCreator creates a new mock instance. -func NewMockGlobalAPIKeyWhitelistCreator(ctrl *gomock.Controller) *MockGlobalAPIKeyWhitelistCreator { - mock := &MockGlobalAPIKeyWhitelistCreator{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyWhitelistCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyWhitelistCreator) EXPECT() *MockGlobalAPIKeyWhitelistCreatorMockRecorder { - return m.recorder -} - -// CreateGlobalAPIKeyWhitelist mocks base method. -func (m *MockGlobalAPIKeyWhitelistCreator) CreateGlobalAPIKeyWhitelist(arg0 *opsmngr.WhitelistAPIKeysReq) (*opsmngr.GlobalWhitelistAPIKey, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateGlobalAPIKeyWhitelist", arg0) - ret0, _ := ret[0].(*opsmngr.GlobalWhitelistAPIKey) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateGlobalAPIKeyWhitelist indicates an expected call of CreateGlobalAPIKeyWhitelist. -func (mr *MockGlobalAPIKeyWhitelistCreatorMockRecorder) CreateGlobalAPIKeyWhitelist(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateGlobalAPIKeyWhitelist", reflect.TypeOf((*MockGlobalAPIKeyWhitelistCreator)(nil).CreateGlobalAPIKeyWhitelist), arg0) -} - -// MockGlobalAPIKeyWhitelistDeleter is a mock of GlobalAPIKeyWhitelistDeleter interface. -type MockGlobalAPIKeyWhitelistDeleter struct { - ctrl *gomock.Controller - recorder *MockGlobalAPIKeyWhitelistDeleterMockRecorder -} - -// MockGlobalAPIKeyWhitelistDeleterMockRecorder is the mock recorder for MockGlobalAPIKeyWhitelistDeleter. -type MockGlobalAPIKeyWhitelistDeleterMockRecorder struct { - mock *MockGlobalAPIKeyWhitelistDeleter -} - -// NewMockGlobalAPIKeyWhitelistDeleter creates a new mock instance. -func NewMockGlobalAPIKeyWhitelistDeleter(ctrl *gomock.Controller) *MockGlobalAPIKeyWhitelistDeleter { - mock := &MockGlobalAPIKeyWhitelistDeleter{ctrl: ctrl} - mock.recorder = &MockGlobalAPIKeyWhitelistDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalAPIKeyWhitelistDeleter) EXPECT() *MockGlobalAPIKeyWhitelistDeleterMockRecorder { - return m.recorder -} - -// DeleteGlobalAPIKeyWhitelist mocks base method. -func (m *MockGlobalAPIKeyWhitelistDeleter) DeleteGlobalAPIKeyWhitelist(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteGlobalAPIKeyWhitelist", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteGlobalAPIKeyWhitelist indicates an expected call of DeleteGlobalAPIKeyWhitelist. -func (mr *MockGlobalAPIKeyWhitelistDeleterMockRecorder) DeleteGlobalAPIKeyWhitelist(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteGlobalAPIKeyWhitelist", reflect.TypeOf((*MockGlobalAPIKeyWhitelistDeleter)(nil).DeleteGlobalAPIKeyWhitelist), arg0) -} diff --git a/internal/mocks/mock_live_migration_orgs_connection.go b/internal/mocks/mock_live_migration_orgs_connection.go deleted file mode 100644 index 77ab5594a4..0000000000 --- a/internal/mocks/mock_live_migration_orgs_connection.go +++ /dev/null @@ -1,89 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: OrganizationsConnector,OrganizationsDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockOrganizationsConnector is a mock of OrganizationsConnector interface. -type MockOrganizationsConnector struct { - ctrl *gomock.Controller - recorder *MockOrganizationsConnectorMockRecorder -} - -// MockOrganizationsConnectorMockRecorder is the mock recorder for MockOrganizationsConnector. -type MockOrganizationsConnectorMockRecorder struct { - mock *MockOrganizationsConnector -} - -// NewMockOrganizationsConnector creates a new mock instance. -func NewMockOrganizationsConnector(ctrl *gomock.Controller) *MockOrganizationsConnector { - mock := &MockOrganizationsConnector{ctrl: ctrl} - mock.recorder = &MockOrganizationsConnectorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationsConnector) EXPECT() *MockOrganizationsConnectorMockRecorder { - return m.recorder -} - -// ConnectOrganizations mocks base method. -func (m *MockOrganizationsConnector) ConnectOrganizations(arg0 string, arg1 *mongodbatlas.LinkToken) (*opsmngr.ConnectionStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConnectOrganizations", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.ConnectionStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ConnectOrganizations indicates an expected call of ConnectOrganizations. -func (mr *MockOrganizationsConnectorMockRecorder) ConnectOrganizations(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConnectOrganizations", reflect.TypeOf((*MockOrganizationsConnector)(nil).ConnectOrganizations), arg0, arg1) -} - -// MockOrganizationsDescriber is a mock of OrganizationsDescriber interface. -type MockOrganizationsDescriber struct { - ctrl *gomock.Controller - recorder *MockOrganizationsDescriberMockRecorder -} - -// MockOrganizationsDescriberMockRecorder is the mock recorder for MockOrganizationsDescriber. -type MockOrganizationsDescriberMockRecorder struct { - mock *MockOrganizationsDescriber -} - -// NewMockOrganizationsDescriber creates a new mock instance. -func NewMockOrganizationsDescriber(ctrl *gomock.Controller) *MockOrganizationsDescriber { - mock := &MockOrganizationsDescriber{ctrl: ctrl} - mock.recorder = &MockOrganizationsDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationsDescriber) EXPECT() *MockOrganizationsDescriberMockRecorder { - return m.recorder -} - -// OrganizationConnectionStatus mocks base method. -func (m *MockOrganizationsDescriber) OrganizationConnectionStatus(arg0 string) (*opsmngr.ConnectionStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationConnectionStatus", arg0) - ret0, _ := ret[0].(*opsmngr.ConnectionStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationConnectionStatus indicates an expected call of OrganizationConnectionStatus. -func (mr *MockOrganizationsDescriberMockRecorder) OrganizationConnectionStatus(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationConnectionStatus", reflect.TypeOf((*MockOrganizationsDescriber)(nil).OrganizationConnectionStatus), arg0) -} diff --git a/internal/mocks/mock_measurements.go b/internal/mocks/mock_measurements.go deleted file mode 100644 index 480b7ca50c..0000000000 --- a/internal/mocks/mock_measurements.go +++ /dev/null @@ -1,126 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: HostMeasurementLister,HostDiskMeasurementsLister,HostDatabaseMeasurementsLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockHostMeasurementLister is a mock of HostMeasurementLister interface. -type MockHostMeasurementLister struct { - ctrl *gomock.Controller - recorder *MockHostMeasurementListerMockRecorder -} - -// MockHostMeasurementListerMockRecorder is the mock recorder for MockHostMeasurementLister. -type MockHostMeasurementListerMockRecorder struct { - mock *MockHostMeasurementLister -} - -// NewMockHostMeasurementLister creates a new mock instance. -func NewMockHostMeasurementLister(ctrl *gomock.Controller) *MockHostMeasurementLister { - mock := &MockHostMeasurementLister{ctrl: ctrl} - mock.recorder = &MockHostMeasurementListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHostMeasurementLister) EXPECT() *MockHostMeasurementListerMockRecorder { - return m.recorder -} - -// HostMeasurements mocks base method. -func (m *MockHostMeasurementLister) HostMeasurements(arg0, arg1 string, arg2 *mongodbatlas.ProcessMeasurementListOptions) (*mongodbatlas.ProcessMeasurements, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HostMeasurements", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.ProcessMeasurements) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HostMeasurements indicates an expected call of HostMeasurements. -func (mr *MockHostMeasurementListerMockRecorder) HostMeasurements(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostMeasurements", reflect.TypeOf((*MockHostMeasurementLister)(nil).HostMeasurements), arg0, arg1, arg2) -} - -// MockHostDiskMeasurementsLister is a mock of HostDiskMeasurementsLister interface. -type MockHostDiskMeasurementsLister struct { - ctrl *gomock.Controller - recorder *MockHostDiskMeasurementsListerMockRecorder -} - -// MockHostDiskMeasurementsListerMockRecorder is the mock recorder for MockHostDiskMeasurementsLister. -type MockHostDiskMeasurementsListerMockRecorder struct { - mock *MockHostDiskMeasurementsLister -} - -// NewMockHostDiskMeasurementsLister creates a new mock instance. -func NewMockHostDiskMeasurementsLister(ctrl *gomock.Controller) *MockHostDiskMeasurementsLister { - mock := &MockHostDiskMeasurementsLister{ctrl: ctrl} - mock.recorder = &MockHostDiskMeasurementsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHostDiskMeasurementsLister) EXPECT() *MockHostDiskMeasurementsListerMockRecorder { - return m.recorder -} - -// HostDiskMeasurements mocks base method. -func (m *MockHostDiskMeasurementsLister) HostDiskMeasurements(arg0, arg1, arg2 string, arg3 *mongodbatlas.ProcessMeasurementListOptions) (*mongodbatlas.ProcessDiskMeasurements, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HostDiskMeasurements", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(*mongodbatlas.ProcessDiskMeasurements) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HostDiskMeasurements indicates an expected call of HostDiskMeasurements. -func (mr *MockHostDiskMeasurementsListerMockRecorder) HostDiskMeasurements(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostDiskMeasurements", reflect.TypeOf((*MockHostDiskMeasurementsLister)(nil).HostDiskMeasurements), arg0, arg1, arg2, arg3) -} - -// MockHostDatabaseMeasurementsLister is a mock of HostDatabaseMeasurementsLister interface. -type MockHostDatabaseMeasurementsLister struct { - ctrl *gomock.Controller - recorder *MockHostDatabaseMeasurementsListerMockRecorder -} - -// MockHostDatabaseMeasurementsListerMockRecorder is the mock recorder for MockHostDatabaseMeasurementsLister. -type MockHostDatabaseMeasurementsListerMockRecorder struct { - mock *MockHostDatabaseMeasurementsLister -} - -// NewMockHostDatabaseMeasurementsLister creates a new mock instance. -func NewMockHostDatabaseMeasurementsLister(ctrl *gomock.Controller) *MockHostDatabaseMeasurementsLister { - mock := &MockHostDatabaseMeasurementsLister{ctrl: ctrl} - mock.recorder = &MockHostDatabaseMeasurementsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHostDatabaseMeasurementsLister) EXPECT() *MockHostDatabaseMeasurementsListerMockRecorder { - return m.recorder -} - -// HostDatabaseMeasurements mocks base method. -func (m *MockHostDatabaseMeasurementsLister) HostDatabaseMeasurements(arg0, arg1, arg2 string, arg3 *mongodbatlas.ProcessMeasurementListOptions) (*mongodbatlas.ProcessDatabaseMeasurements, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HostDatabaseMeasurements", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(*mongodbatlas.ProcessDatabaseMeasurements) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HostDatabaseMeasurements indicates an expected call of HostDatabaseMeasurements. -func (mr *MockHostDatabaseMeasurementsListerMockRecorder) HostDatabaseMeasurements(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HostDatabaseMeasurements", reflect.TypeOf((*MockHostDatabaseMeasurementsLister)(nil).HostDatabaseMeasurements), arg0, arg1, arg2, arg3) -} diff --git a/internal/mocks/mock_monitoring.go b/internal/mocks/mock_monitoring.go deleted file mode 100644 index 1f15f42b52..0000000000 --- a/internal/mocks/mock_monitoring.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: MonitoringStarter,MonitoringStopper) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockMonitoringStarter is a mock of MonitoringStarter interface. -type MockMonitoringStarter struct { - ctrl *gomock.Controller - recorder *MockMonitoringStarterMockRecorder -} - -// MockMonitoringStarterMockRecorder is the mock recorder for MockMonitoringStarter. -type MockMonitoringStarterMockRecorder struct { - mock *MockMonitoringStarter -} - -// NewMockMonitoringStarter creates a new mock instance. -func NewMockMonitoringStarter(ctrl *gomock.Controller) *MockMonitoringStarter { - mock := &MockMonitoringStarter{ctrl: ctrl} - mock.recorder = &MockMonitoringStarterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockMonitoringStarter) EXPECT() *MockMonitoringStarterMockRecorder { - return m.recorder -} - -// StartMonitoring mocks base method. -func (m *MockMonitoringStarter) StartMonitoring(arg0 string, arg1 *opsmngr.Host) (*opsmngr.Host, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "StartMonitoring", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.Host) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// StartMonitoring indicates an expected call of StartMonitoring. -func (mr *MockMonitoringStarterMockRecorder) StartMonitoring(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartMonitoring", reflect.TypeOf((*MockMonitoringStarter)(nil).StartMonitoring), arg0, arg1) -} - -// MockMonitoringStopper is a mock of MonitoringStopper interface. -type MockMonitoringStopper struct { - ctrl *gomock.Controller - recorder *MockMonitoringStopperMockRecorder -} - -// MockMonitoringStopperMockRecorder is the mock recorder for MockMonitoringStopper. -type MockMonitoringStopperMockRecorder struct { - mock *MockMonitoringStopper -} - -// NewMockMonitoringStopper creates a new mock instance. -func NewMockMonitoringStopper(ctrl *gomock.Controller) *MockMonitoringStopper { - mock := &MockMonitoringStopper{ctrl: ctrl} - mock.recorder = &MockMonitoringStopperMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockMonitoringStopper) EXPECT() *MockMonitoringStopperMockRecorder { - return m.recorder -} - -// StopMonitoring mocks base method. -func (m *MockMonitoringStopper) StopMonitoring(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "StopMonitoring", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// StopMonitoring indicates an expected call of StopMonitoring. -func (mr *MockMonitoringStopperMockRecorder) StopMonitoring(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StopMonitoring", reflect.TypeOf((*MockMonitoringStopper)(nil).StopMonitoring), arg0, arg1) -} diff --git a/internal/mocks/mock_organization_invitations.go b/internal/mocks/mock_organization_invitations.go deleted file mode 100644 index 6fb23073cb..0000000000 --- a/internal/mocks/mock_organization_invitations.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: OrganizationInvitationLister,OrganizationInvitationDeleter,OrganizationInvitationDescriber,OrganizationInvitationUpdater,OrganizationInviter) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockOrganizationInvitationLister is a mock of OrganizationInvitationLister interface. -type MockOrganizationInvitationLister struct { - ctrl *gomock.Controller - recorder *MockOrganizationInvitationListerMockRecorder -} - -// MockOrganizationInvitationListerMockRecorder is the mock recorder for MockOrganizationInvitationLister. -type MockOrganizationInvitationListerMockRecorder struct { - mock *MockOrganizationInvitationLister -} - -// NewMockOrganizationInvitationLister creates a new mock instance. -func NewMockOrganizationInvitationLister(ctrl *gomock.Controller) *MockOrganizationInvitationLister { - mock := &MockOrganizationInvitationLister{ctrl: ctrl} - mock.recorder = &MockOrganizationInvitationListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationInvitationLister) EXPECT() *MockOrganizationInvitationListerMockRecorder { - return m.recorder -} - -// OrganizationInvitations mocks base method. -func (m *MockOrganizationInvitationLister) OrganizationInvitations(arg0 string, arg1 *mongodbatlas.InvitationOptions) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationInvitations", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationInvitations indicates an expected call of OrganizationInvitations. -func (mr *MockOrganizationInvitationListerMockRecorder) OrganizationInvitations(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationInvitations", reflect.TypeOf((*MockOrganizationInvitationLister)(nil).OrganizationInvitations), arg0, arg1) -} - -// MockOrganizationInvitationDeleter is a mock of OrganizationInvitationDeleter interface. -type MockOrganizationInvitationDeleter struct { - ctrl *gomock.Controller - recorder *MockOrganizationInvitationDeleterMockRecorder -} - -// MockOrganizationInvitationDeleterMockRecorder is the mock recorder for MockOrganizationInvitationDeleter. -type MockOrganizationInvitationDeleterMockRecorder struct { - mock *MockOrganizationInvitationDeleter -} - -// NewMockOrganizationInvitationDeleter creates a new mock instance. -func NewMockOrganizationInvitationDeleter(ctrl *gomock.Controller) *MockOrganizationInvitationDeleter { - mock := &MockOrganizationInvitationDeleter{ctrl: ctrl} - mock.recorder = &MockOrganizationInvitationDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationInvitationDeleter) EXPECT() *MockOrganizationInvitationDeleterMockRecorder { - return m.recorder -} - -// DeleteInvitation mocks base method. -func (m *MockOrganizationInvitationDeleter) DeleteInvitation(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteInvitation", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteInvitation indicates an expected call of DeleteInvitation. -func (mr *MockOrganizationInvitationDeleterMockRecorder) DeleteInvitation(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteInvitation", reflect.TypeOf((*MockOrganizationInvitationDeleter)(nil).DeleteInvitation), arg0, arg1) -} - -// MockOrganizationInvitationDescriber is a mock of OrganizationInvitationDescriber interface. -type MockOrganizationInvitationDescriber struct { - ctrl *gomock.Controller - recorder *MockOrganizationInvitationDescriberMockRecorder -} - -// MockOrganizationInvitationDescriberMockRecorder is the mock recorder for MockOrganizationInvitationDescriber. -type MockOrganizationInvitationDescriberMockRecorder struct { - mock *MockOrganizationInvitationDescriber -} - -// NewMockOrganizationInvitationDescriber creates a new mock instance. -func NewMockOrganizationInvitationDescriber(ctrl *gomock.Controller) *MockOrganizationInvitationDescriber { - mock := &MockOrganizationInvitationDescriber{ctrl: ctrl} - mock.recorder = &MockOrganizationInvitationDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationInvitationDescriber) EXPECT() *MockOrganizationInvitationDescriberMockRecorder { - return m.recorder -} - -// OrganizationInvitation mocks base method. -func (m *MockOrganizationInvitationDescriber) OrganizationInvitation(arg0, arg1 string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationInvitation", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationInvitation indicates an expected call of OrganizationInvitation. -func (mr *MockOrganizationInvitationDescriberMockRecorder) OrganizationInvitation(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationInvitation", reflect.TypeOf((*MockOrganizationInvitationDescriber)(nil).OrganizationInvitation), arg0, arg1) -} - -// MockOrganizationInvitationUpdater is a mock of OrganizationInvitationUpdater interface. -type MockOrganizationInvitationUpdater struct { - ctrl *gomock.Controller - recorder *MockOrganizationInvitationUpdaterMockRecorder -} - -// MockOrganizationInvitationUpdaterMockRecorder is the mock recorder for MockOrganizationInvitationUpdater. -type MockOrganizationInvitationUpdaterMockRecorder struct { - mock *MockOrganizationInvitationUpdater -} - -// NewMockOrganizationInvitationUpdater creates a new mock instance. -func NewMockOrganizationInvitationUpdater(ctrl *gomock.Controller) *MockOrganizationInvitationUpdater { - mock := &MockOrganizationInvitationUpdater{ctrl: ctrl} - mock.recorder = &MockOrganizationInvitationUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationInvitationUpdater) EXPECT() *MockOrganizationInvitationUpdaterMockRecorder { - return m.recorder -} - -// UpdateOrganizationInvitation mocks base method. -func (m *MockOrganizationInvitationUpdater) UpdateOrganizationInvitation(arg0, arg1 string, arg2 *mongodbatlas.Invitation) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateOrganizationInvitation", arg0, arg1, arg2) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateOrganizationInvitation indicates an expected call of UpdateOrganizationInvitation. -func (mr *MockOrganizationInvitationUpdaterMockRecorder) UpdateOrganizationInvitation(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateOrganizationInvitation", reflect.TypeOf((*MockOrganizationInvitationUpdater)(nil).UpdateOrganizationInvitation), arg0, arg1, arg2) -} - -// MockOrganizationInviter is a mock of OrganizationInviter interface. -type MockOrganizationInviter struct { - ctrl *gomock.Controller - recorder *MockOrganizationInviterMockRecorder -} - -// MockOrganizationInviterMockRecorder is the mock recorder for MockOrganizationInviter. -type MockOrganizationInviterMockRecorder struct { - mock *MockOrganizationInviter -} - -// NewMockOrganizationInviter creates a new mock instance. -func NewMockOrganizationInviter(ctrl *gomock.Controller) *MockOrganizationInviter { - mock := &MockOrganizationInviter{ctrl: ctrl} - mock.recorder = &MockOrganizationInviterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationInviter) EXPECT() *MockOrganizationInviterMockRecorder { - return m.recorder -} - -// InviteUser mocks base method. -func (m *MockOrganizationInviter) InviteUser(arg0 string, arg1 *mongodbatlas.Invitation) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InviteUser", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// InviteUser indicates an expected call of InviteUser. -func (mr *MockOrganizationInviterMockRecorder) InviteUser(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InviteUser", reflect.TypeOf((*MockOrganizationInviter)(nil).InviteUser), arg0, arg1) -} diff --git a/internal/mocks/mock_owners.go b/internal/mocks/mock_owners.go deleted file mode 100644 index 42dd14b006..0000000000 --- a/internal/mocks/mock_owners.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: OwnerCreator) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockOwnerCreator is a mock of OwnerCreator interface. -type MockOwnerCreator struct { - ctrl *gomock.Controller - recorder *MockOwnerCreatorMockRecorder -} - -// MockOwnerCreatorMockRecorder is the mock recorder for MockOwnerCreator. -type MockOwnerCreatorMockRecorder struct { - mock *MockOwnerCreator -} - -// NewMockOwnerCreator creates a new mock instance. -func NewMockOwnerCreator(ctrl *gomock.Controller) *MockOwnerCreator { - mock := &MockOwnerCreator{ctrl: ctrl} - mock.recorder = &MockOwnerCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOwnerCreator) EXPECT() *MockOwnerCreatorMockRecorder { - return m.recorder -} - -// CreateOwner mocks base method. -func (m *MockOwnerCreator) CreateOwner(arg0 *opsmngr.User, arg1 []string) (*opsmngr.CreateUserResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOwner", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.CreateUserResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateOwner indicates an expected call of CreateOwner. -func (mr *MockOwnerCreatorMockRecorder) CreateOwner(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOwner", reflect.TypeOf((*MockOwnerCreator)(nil).CreateOwner), arg0, arg1) -} diff --git a/internal/mocks/mock_performance_advisor.go b/internal/mocks/mock_performance_advisor.go deleted file mode 100644 index d16fb144e6..0000000000 --- a/internal/mocks/mock_performance_advisor.go +++ /dev/null @@ -1,200 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: PerformanceAdvisorNamespacesLister,PerformanceAdvisorSlowQueriesLister,PerformanceAdvisorIndexesLister,PerformanceAdvisorSlowOperationThresholdEnabler,PerformanceAdvisorSlowOperationThresholdDisabler) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockPerformanceAdvisorNamespacesLister is a mock of PerformanceAdvisorNamespacesLister interface. -type MockPerformanceAdvisorNamespacesLister struct { - ctrl *gomock.Controller - recorder *MockPerformanceAdvisorNamespacesListerMockRecorder -} - -// MockPerformanceAdvisorNamespacesListerMockRecorder is the mock recorder for MockPerformanceAdvisorNamespacesLister. -type MockPerformanceAdvisorNamespacesListerMockRecorder struct { - mock *MockPerformanceAdvisorNamespacesLister -} - -// NewMockPerformanceAdvisorNamespacesLister creates a new mock instance. -func NewMockPerformanceAdvisorNamespacesLister(ctrl *gomock.Controller) *MockPerformanceAdvisorNamespacesLister { - mock := &MockPerformanceAdvisorNamespacesLister{ctrl: ctrl} - mock.recorder = &MockPerformanceAdvisorNamespacesListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockPerformanceAdvisorNamespacesLister) EXPECT() *MockPerformanceAdvisorNamespacesListerMockRecorder { - return m.recorder -} - -// PerformanceAdvisorNamespaces mocks base method. -func (m *MockPerformanceAdvisorNamespacesLister) PerformanceAdvisorNamespaces(arg0, arg1 string, arg2 *mongodbatlas.NamespaceOptions) (*mongodbatlas.Namespaces, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PerformanceAdvisorNamespaces", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.Namespaces) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PerformanceAdvisorNamespaces indicates an expected call of PerformanceAdvisorNamespaces. -func (mr *MockPerformanceAdvisorNamespacesListerMockRecorder) PerformanceAdvisorNamespaces(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PerformanceAdvisorNamespaces", reflect.TypeOf((*MockPerformanceAdvisorNamespacesLister)(nil).PerformanceAdvisorNamespaces), arg0, arg1, arg2) -} - -// MockPerformanceAdvisorSlowQueriesLister is a mock of PerformanceAdvisorSlowQueriesLister interface. -type MockPerformanceAdvisorSlowQueriesLister struct { - ctrl *gomock.Controller - recorder *MockPerformanceAdvisorSlowQueriesListerMockRecorder -} - -// MockPerformanceAdvisorSlowQueriesListerMockRecorder is the mock recorder for MockPerformanceAdvisorSlowQueriesLister. -type MockPerformanceAdvisorSlowQueriesListerMockRecorder struct { - mock *MockPerformanceAdvisorSlowQueriesLister -} - -// NewMockPerformanceAdvisorSlowQueriesLister creates a new mock instance. -func NewMockPerformanceAdvisorSlowQueriesLister(ctrl *gomock.Controller) *MockPerformanceAdvisorSlowQueriesLister { - mock := &MockPerformanceAdvisorSlowQueriesLister{ctrl: ctrl} - mock.recorder = &MockPerformanceAdvisorSlowQueriesListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockPerformanceAdvisorSlowQueriesLister) EXPECT() *MockPerformanceAdvisorSlowQueriesListerMockRecorder { - return m.recorder -} - -// PerformanceAdvisorSlowQueries mocks base method. -func (m *MockPerformanceAdvisorSlowQueriesLister) PerformanceAdvisorSlowQueries(arg0, arg1 string, arg2 *mongodbatlas.SlowQueryOptions) (*mongodbatlas.SlowQueries, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PerformanceAdvisorSlowQueries", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.SlowQueries) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PerformanceAdvisorSlowQueries indicates an expected call of PerformanceAdvisorSlowQueries. -func (mr *MockPerformanceAdvisorSlowQueriesListerMockRecorder) PerformanceAdvisorSlowQueries(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PerformanceAdvisorSlowQueries", reflect.TypeOf((*MockPerformanceAdvisorSlowQueriesLister)(nil).PerformanceAdvisorSlowQueries), arg0, arg1, arg2) -} - -// MockPerformanceAdvisorIndexesLister is a mock of PerformanceAdvisorIndexesLister interface. -type MockPerformanceAdvisorIndexesLister struct { - ctrl *gomock.Controller - recorder *MockPerformanceAdvisorIndexesListerMockRecorder -} - -// MockPerformanceAdvisorIndexesListerMockRecorder is the mock recorder for MockPerformanceAdvisorIndexesLister. -type MockPerformanceAdvisorIndexesListerMockRecorder struct { - mock *MockPerformanceAdvisorIndexesLister -} - -// NewMockPerformanceAdvisorIndexesLister creates a new mock instance. -func NewMockPerformanceAdvisorIndexesLister(ctrl *gomock.Controller) *MockPerformanceAdvisorIndexesLister { - mock := &MockPerformanceAdvisorIndexesLister{ctrl: ctrl} - mock.recorder = &MockPerformanceAdvisorIndexesListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockPerformanceAdvisorIndexesLister) EXPECT() *MockPerformanceAdvisorIndexesListerMockRecorder { - return m.recorder -} - -// PerformanceAdvisorIndexes mocks base method. -func (m *MockPerformanceAdvisorIndexesLister) PerformanceAdvisorIndexes(arg0, arg1 string, arg2 *mongodbatlas.SuggestedIndexOptions) (*mongodbatlas.SuggestedIndexes, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PerformanceAdvisorIndexes", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.SuggestedIndexes) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PerformanceAdvisorIndexes indicates an expected call of PerformanceAdvisorIndexes. -func (mr *MockPerformanceAdvisorIndexesListerMockRecorder) PerformanceAdvisorIndexes(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PerformanceAdvisorIndexes", reflect.TypeOf((*MockPerformanceAdvisorIndexesLister)(nil).PerformanceAdvisorIndexes), arg0, arg1, arg2) -} - -// MockPerformanceAdvisorSlowOperationThresholdEnabler is a mock of PerformanceAdvisorSlowOperationThresholdEnabler interface. -type MockPerformanceAdvisorSlowOperationThresholdEnabler struct { - ctrl *gomock.Controller - recorder *MockPerformanceAdvisorSlowOperationThresholdEnablerMockRecorder -} - -// MockPerformanceAdvisorSlowOperationThresholdEnablerMockRecorder is the mock recorder for MockPerformanceAdvisorSlowOperationThresholdEnabler. -type MockPerformanceAdvisorSlowOperationThresholdEnablerMockRecorder struct { - mock *MockPerformanceAdvisorSlowOperationThresholdEnabler -} - -// NewMockPerformanceAdvisorSlowOperationThresholdEnabler creates a new mock instance. -func NewMockPerformanceAdvisorSlowOperationThresholdEnabler(ctrl *gomock.Controller) *MockPerformanceAdvisorSlowOperationThresholdEnabler { - mock := &MockPerformanceAdvisorSlowOperationThresholdEnabler{ctrl: ctrl} - mock.recorder = &MockPerformanceAdvisorSlowOperationThresholdEnablerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockPerformanceAdvisorSlowOperationThresholdEnabler) EXPECT() *MockPerformanceAdvisorSlowOperationThresholdEnablerMockRecorder { - return m.recorder -} - -// EnablePerformanceAdvisorSlowOperationThreshold mocks base method. -func (m *MockPerformanceAdvisorSlowOperationThresholdEnabler) EnablePerformanceAdvisorSlowOperationThreshold(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "EnablePerformanceAdvisorSlowOperationThreshold", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// EnablePerformanceAdvisorSlowOperationThreshold indicates an expected call of EnablePerformanceAdvisorSlowOperationThreshold. -func (mr *MockPerformanceAdvisorSlowOperationThresholdEnablerMockRecorder) EnablePerformanceAdvisorSlowOperationThreshold(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnablePerformanceAdvisorSlowOperationThreshold", reflect.TypeOf((*MockPerformanceAdvisorSlowOperationThresholdEnabler)(nil).EnablePerformanceAdvisorSlowOperationThreshold), arg0) -} - -// MockPerformanceAdvisorSlowOperationThresholdDisabler is a mock of PerformanceAdvisorSlowOperationThresholdDisabler interface. -type MockPerformanceAdvisorSlowOperationThresholdDisabler struct { - ctrl *gomock.Controller - recorder *MockPerformanceAdvisorSlowOperationThresholdDisablerMockRecorder -} - -// MockPerformanceAdvisorSlowOperationThresholdDisablerMockRecorder is the mock recorder for MockPerformanceAdvisorSlowOperationThresholdDisabler. -type MockPerformanceAdvisorSlowOperationThresholdDisablerMockRecorder struct { - mock *MockPerformanceAdvisorSlowOperationThresholdDisabler -} - -// NewMockPerformanceAdvisorSlowOperationThresholdDisabler creates a new mock instance. -func NewMockPerformanceAdvisorSlowOperationThresholdDisabler(ctrl *gomock.Controller) *MockPerformanceAdvisorSlowOperationThresholdDisabler { - mock := &MockPerformanceAdvisorSlowOperationThresholdDisabler{ctrl: ctrl} - mock.recorder = &MockPerformanceAdvisorSlowOperationThresholdDisablerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockPerformanceAdvisorSlowOperationThresholdDisabler) EXPECT() *MockPerformanceAdvisorSlowOperationThresholdDisablerMockRecorder { - return m.recorder -} - -// DisablePerformanceAdvisorSlowOperationThreshold mocks base method. -func (m *MockPerformanceAdvisorSlowOperationThresholdDisabler) DisablePerformanceAdvisorSlowOperationThreshold(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DisablePerformanceAdvisorSlowOperationThreshold", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DisablePerformanceAdvisorSlowOperationThreshold indicates an expected call of DisablePerformanceAdvisorSlowOperationThreshold. -func (mr *MockPerformanceAdvisorSlowOperationThresholdDisablerMockRecorder) DisablePerformanceAdvisorSlowOperationThreshold(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DisablePerformanceAdvisorSlowOperationThreshold", reflect.TypeOf((*MockPerformanceAdvisorSlowOperationThresholdDisabler)(nil).DisablePerformanceAdvisorSlowOperationThreshold), arg0) -} diff --git a/internal/mocks/mock_project_invitations.go b/internal/mocks/mock_project_invitations.go deleted file mode 100644 index e98430527d..0000000000 --- a/internal/mocks/mock_project_invitations.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: ProjectInvitationLister,ProjectInvitationDescriber,ProjectInvitationDeleter,ProjectInviter,ProjectInvitationUpdater) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockProjectInvitationLister is a mock of ProjectInvitationLister interface. -type MockProjectInvitationLister struct { - ctrl *gomock.Controller - recorder *MockProjectInvitationListerMockRecorder -} - -// MockProjectInvitationListerMockRecorder is the mock recorder for MockProjectInvitationLister. -type MockProjectInvitationListerMockRecorder struct { - mock *MockProjectInvitationLister -} - -// NewMockProjectInvitationLister creates a new mock instance. -func NewMockProjectInvitationLister(ctrl *gomock.Controller) *MockProjectInvitationLister { - mock := &MockProjectInvitationLister{ctrl: ctrl} - mock.recorder = &MockProjectInvitationListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectInvitationLister) EXPECT() *MockProjectInvitationListerMockRecorder { - return m.recorder -} - -// ProjectInvitations mocks base method. -func (m *MockProjectInvitationLister) ProjectInvitations(arg0 string, arg1 *mongodbatlas.InvitationOptions) ([]*mongodbatlas.Invitation, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectInvitations", arg0, arg1) - ret0, _ := ret[0].([]*mongodbatlas.Invitation) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectInvitations indicates an expected call of ProjectInvitations. -func (mr *MockProjectInvitationListerMockRecorder) ProjectInvitations(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectInvitations", reflect.TypeOf((*MockProjectInvitationLister)(nil).ProjectInvitations), arg0, arg1) -} - -// MockProjectInvitationDescriber is a mock of ProjectInvitationDescriber interface. -type MockProjectInvitationDescriber struct { - ctrl *gomock.Controller - recorder *MockProjectInvitationDescriberMockRecorder -} - -// MockProjectInvitationDescriberMockRecorder is the mock recorder for MockProjectInvitationDescriber. -type MockProjectInvitationDescriberMockRecorder struct { - mock *MockProjectInvitationDescriber -} - -// NewMockProjectInvitationDescriber creates a new mock instance. -func NewMockProjectInvitationDescriber(ctrl *gomock.Controller) *MockProjectInvitationDescriber { - mock := &MockProjectInvitationDescriber{ctrl: ctrl} - mock.recorder = &MockProjectInvitationDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectInvitationDescriber) EXPECT() *MockProjectInvitationDescriberMockRecorder { - return m.recorder -} - -// ProjectInvitation mocks base method. -func (m *MockProjectInvitationDescriber) ProjectInvitation(arg0, arg1 string) (*mongodbatlas.Invitation, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectInvitation", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.Invitation) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectInvitation indicates an expected call of ProjectInvitation. -func (mr *MockProjectInvitationDescriberMockRecorder) ProjectInvitation(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectInvitation", reflect.TypeOf((*MockProjectInvitationDescriber)(nil).ProjectInvitation), arg0, arg1) -} - -// MockProjectInvitationDeleter is a mock of ProjectInvitationDeleter interface. -type MockProjectInvitationDeleter struct { - ctrl *gomock.Controller - recorder *MockProjectInvitationDeleterMockRecorder -} - -// MockProjectInvitationDeleterMockRecorder is the mock recorder for MockProjectInvitationDeleter. -type MockProjectInvitationDeleterMockRecorder struct { - mock *MockProjectInvitationDeleter -} - -// NewMockProjectInvitationDeleter creates a new mock instance. -func NewMockProjectInvitationDeleter(ctrl *gomock.Controller) *MockProjectInvitationDeleter { - mock := &MockProjectInvitationDeleter{ctrl: ctrl} - mock.recorder = &MockProjectInvitationDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectInvitationDeleter) EXPECT() *MockProjectInvitationDeleterMockRecorder { - return m.recorder -} - -// DeleteProjectInvitation mocks base method. -func (m *MockProjectInvitationDeleter) DeleteProjectInvitation(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteProjectInvitation", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteProjectInvitation indicates an expected call of DeleteProjectInvitation. -func (mr *MockProjectInvitationDeleterMockRecorder) DeleteProjectInvitation(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteProjectInvitation", reflect.TypeOf((*MockProjectInvitationDeleter)(nil).DeleteProjectInvitation), arg0, arg1) -} - -// MockProjectInviter is a mock of ProjectInviter interface. -type MockProjectInviter struct { - ctrl *gomock.Controller - recorder *MockProjectInviterMockRecorder -} - -// MockProjectInviterMockRecorder is the mock recorder for MockProjectInviter. -type MockProjectInviterMockRecorder struct { - mock *MockProjectInviter -} - -// NewMockProjectInviter creates a new mock instance. -func NewMockProjectInviter(ctrl *gomock.Controller) *MockProjectInviter { - mock := &MockProjectInviter{ctrl: ctrl} - mock.recorder = &MockProjectInviterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectInviter) EXPECT() *MockProjectInviterMockRecorder { - return m.recorder -} - -// InviteUserToProject mocks base method. -func (m *MockProjectInviter) InviteUserToProject(arg0 string, arg1 *mongodbatlas.Invitation) (*mongodbatlas.Invitation, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InviteUserToProject", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.Invitation) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// InviteUserToProject indicates an expected call of InviteUserToProject. -func (mr *MockProjectInviterMockRecorder) InviteUserToProject(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InviteUserToProject", reflect.TypeOf((*MockProjectInviter)(nil).InviteUserToProject), arg0, arg1) -} - -// MockProjectInvitationUpdater is a mock of ProjectInvitationUpdater interface. -type MockProjectInvitationUpdater struct { - ctrl *gomock.Controller - recorder *MockProjectInvitationUpdaterMockRecorder -} - -// MockProjectInvitationUpdaterMockRecorder is the mock recorder for MockProjectInvitationUpdater. -type MockProjectInvitationUpdaterMockRecorder struct { - mock *MockProjectInvitationUpdater -} - -// NewMockProjectInvitationUpdater creates a new mock instance. -func NewMockProjectInvitationUpdater(ctrl *gomock.Controller) *MockProjectInvitationUpdater { - mock := &MockProjectInvitationUpdater{ctrl: ctrl} - mock.recorder = &MockProjectInvitationUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectInvitationUpdater) EXPECT() *MockProjectInvitationUpdaterMockRecorder { - return m.recorder -} - -// UpdateProjectInvitation mocks base method. -func (m *MockProjectInvitationUpdater) UpdateProjectInvitation(arg0, arg1 string, arg2 *mongodbatlas.Invitation) (*mongodbatlas.Invitation, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateProjectInvitation", arg0, arg1, arg2) - ret0, _ := ret[0].(*mongodbatlas.Invitation) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateProjectInvitation indicates an expected call of UpdateProjectInvitation. -func (mr *MockProjectInvitationUpdaterMockRecorder) UpdateProjectInvitation(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateProjectInvitation", reflect.TypeOf((*MockProjectInvitationUpdater)(nil).UpdateProjectInvitation), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_server_usage.go b/internal/mocks/mock_server_usage.go deleted file mode 100644 index 64712d9298..0000000000 --- a/internal/mocks/mock_server_usage.go +++ /dev/null @@ -1,313 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: ProjectServerTypeGetter,ProjectServerTypeUpdater,OrganizationServerTypeGetter,OrganizationServerTypeUpdater,ProjectHostAssignmentLister,OrganizationHostAssignmentLister,SnapshotGenerator,ServerUsageReportDownloader) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - io "io" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockProjectServerTypeGetter is a mock of ProjectServerTypeGetter interface. -type MockProjectServerTypeGetter struct { - ctrl *gomock.Controller - recorder *MockProjectServerTypeGetterMockRecorder -} - -// MockProjectServerTypeGetterMockRecorder is the mock recorder for MockProjectServerTypeGetter. -type MockProjectServerTypeGetterMockRecorder struct { - mock *MockProjectServerTypeGetter -} - -// NewMockProjectServerTypeGetter creates a new mock instance. -func NewMockProjectServerTypeGetter(ctrl *gomock.Controller) *MockProjectServerTypeGetter { - mock := &MockProjectServerTypeGetter{ctrl: ctrl} - mock.recorder = &MockProjectServerTypeGetterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectServerTypeGetter) EXPECT() *MockProjectServerTypeGetterMockRecorder { - return m.recorder -} - -// ProjectServerType mocks base method. -func (m *MockProjectServerTypeGetter) ProjectServerType(arg0 string) (*opsmngr.ServerType, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectServerType", arg0) - ret0, _ := ret[0].(*opsmngr.ServerType) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectServerType indicates an expected call of ProjectServerType. -func (mr *MockProjectServerTypeGetterMockRecorder) ProjectServerType(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectServerType", reflect.TypeOf((*MockProjectServerTypeGetter)(nil).ProjectServerType), arg0) -} - -// MockProjectServerTypeUpdater is a mock of ProjectServerTypeUpdater interface. -type MockProjectServerTypeUpdater struct { - ctrl *gomock.Controller - recorder *MockProjectServerTypeUpdaterMockRecorder -} - -// MockProjectServerTypeUpdaterMockRecorder is the mock recorder for MockProjectServerTypeUpdater. -type MockProjectServerTypeUpdaterMockRecorder struct { - mock *MockProjectServerTypeUpdater -} - -// NewMockProjectServerTypeUpdater creates a new mock instance. -func NewMockProjectServerTypeUpdater(ctrl *gomock.Controller) *MockProjectServerTypeUpdater { - mock := &MockProjectServerTypeUpdater{ctrl: ctrl} - mock.recorder = &MockProjectServerTypeUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectServerTypeUpdater) EXPECT() *MockProjectServerTypeUpdaterMockRecorder { - return m.recorder -} - -// UpdateProjectServerType mocks base method. -func (m *MockProjectServerTypeUpdater) UpdateProjectServerType(arg0 string, arg1 *opsmngr.ServerTypeRequest) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateProjectServerType", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateProjectServerType indicates an expected call of UpdateProjectServerType. -func (mr *MockProjectServerTypeUpdaterMockRecorder) UpdateProjectServerType(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateProjectServerType", reflect.TypeOf((*MockProjectServerTypeUpdater)(nil).UpdateProjectServerType), arg0, arg1) -} - -// MockOrganizationServerTypeGetter is a mock of OrganizationServerTypeGetter interface. -type MockOrganizationServerTypeGetter struct { - ctrl *gomock.Controller - recorder *MockOrganizationServerTypeGetterMockRecorder -} - -// MockOrganizationServerTypeGetterMockRecorder is the mock recorder for MockOrganizationServerTypeGetter. -type MockOrganizationServerTypeGetterMockRecorder struct { - mock *MockOrganizationServerTypeGetter -} - -// NewMockOrganizationServerTypeGetter creates a new mock instance. -func NewMockOrganizationServerTypeGetter(ctrl *gomock.Controller) *MockOrganizationServerTypeGetter { - mock := &MockOrganizationServerTypeGetter{ctrl: ctrl} - mock.recorder = &MockOrganizationServerTypeGetterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationServerTypeGetter) EXPECT() *MockOrganizationServerTypeGetterMockRecorder { - return m.recorder -} - -// OrganizationServerType mocks base method. -func (m *MockOrganizationServerTypeGetter) OrganizationServerType(arg0 string) (*opsmngr.ServerType, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationServerType", arg0) - ret0, _ := ret[0].(*opsmngr.ServerType) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationServerType indicates an expected call of OrganizationServerType. -func (mr *MockOrganizationServerTypeGetterMockRecorder) OrganizationServerType(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationServerType", reflect.TypeOf((*MockOrganizationServerTypeGetter)(nil).OrganizationServerType), arg0) -} - -// MockOrganizationServerTypeUpdater is a mock of OrganizationServerTypeUpdater interface. -type MockOrganizationServerTypeUpdater struct { - ctrl *gomock.Controller - recorder *MockOrganizationServerTypeUpdaterMockRecorder -} - -// MockOrganizationServerTypeUpdaterMockRecorder is the mock recorder for MockOrganizationServerTypeUpdater. -type MockOrganizationServerTypeUpdaterMockRecorder struct { - mock *MockOrganizationServerTypeUpdater -} - -// NewMockOrganizationServerTypeUpdater creates a new mock instance. -func NewMockOrganizationServerTypeUpdater(ctrl *gomock.Controller) *MockOrganizationServerTypeUpdater { - mock := &MockOrganizationServerTypeUpdater{ctrl: ctrl} - mock.recorder = &MockOrganizationServerTypeUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationServerTypeUpdater) EXPECT() *MockOrganizationServerTypeUpdaterMockRecorder { - return m.recorder -} - -// UpdateOrganizationServerType mocks base method. -func (m *MockOrganizationServerTypeUpdater) UpdateOrganizationServerType(arg0 string, arg1 *opsmngr.ServerTypeRequest) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateOrganizationServerType", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateOrganizationServerType indicates an expected call of UpdateOrganizationServerType. -func (mr *MockOrganizationServerTypeUpdaterMockRecorder) UpdateOrganizationServerType(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateOrganizationServerType", reflect.TypeOf((*MockOrganizationServerTypeUpdater)(nil).UpdateOrganizationServerType), arg0, arg1) -} - -// MockProjectHostAssignmentLister is a mock of ProjectHostAssignmentLister interface. -type MockProjectHostAssignmentLister struct { - ctrl *gomock.Controller - recorder *MockProjectHostAssignmentListerMockRecorder -} - -// MockProjectHostAssignmentListerMockRecorder is the mock recorder for MockProjectHostAssignmentLister. -type MockProjectHostAssignmentListerMockRecorder struct { - mock *MockProjectHostAssignmentLister -} - -// NewMockProjectHostAssignmentLister creates a new mock instance. -func NewMockProjectHostAssignmentLister(ctrl *gomock.Controller) *MockProjectHostAssignmentLister { - mock := &MockProjectHostAssignmentLister{ctrl: ctrl} - mock.recorder = &MockProjectHostAssignmentListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectHostAssignmentLister) EXPECT() *MockProjectHostAssignmentListerMockRecorder { - return m.recorder -} - -// ProjectHostAssignments mocks base method. -func (m *MockProjectHostAssignmentLister) ProjectHostAssignments(arg0 string, arg1 *opsmngr.ServerTypeOptions) (*opsmngr.HostAssignments, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectHostAssignments", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.HostAssignments) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectHostAssignments indicates an expected call of ProjectHostAssignments. -func (mr *MockProjectHostAssignmentListerMockRecorder) ProjectHostAssignments(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectHostAssignments", reflect.TypeOf((*MockProjectHostAssignmentLister)(nil).ProjectHostAssignments), arg0, arg1) -} - -// MockOrganizationHostAssignmentLister is a mock of OrganizationHostAssignmentLister interface. -type MockOrganizationHostAssignmentLister struct { - ctrl *gomock.Controller - recorder *MockOrganizationHostAssignmentListerMockRecorder -} - -// MockOrganizationHostAssignmentListerMockRecorder is the mock recorder for MockOrganizationHostAssignmentLister. -type MockOrganizationHostAssignmentListerMockRecorder struct { - mock *MockOrganizationHostAssignmentLister -} - -// NewMockOrganizationHostAssignmentLister creates a new mock instance. -func NewMockOrganizationHostAssignmentLister(ctrl *gomock.Controller) *MockOrganizationHostAssignmentLister { - mock := &MockOrganizationHostAssignmentLister{ctrl: ctrl} - mock.recorder = &MockOrganizationHostAssignmentListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOrganizationHostAssignmentLister) EXPECT() *MockOrganizationHostAssignmentListerMockRecorder { - return m.recorder -} - -// OrganizationHostAssignments mocks base method. -func (m *MockOrganizationHostAssignmentLister) OrganizationHostAssignments(arg0 string, arg1 *opsmngr.ServerTypeOptions) (*opsmngr.HostAssignments, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationHostAssignments", arg0, arg1) - ret0, _ := ret[0].(*opsmngr.HostAssignments) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationHostAssignments indicates an expected call of OrganizationHostAssignments. -func (mr *MockOrganizationHostAssignmentListerMockRecorder) OrganizationHostAssignments(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationHostAssignments", reflect.TypeOf((*MockOrganizationHostAssignmentLister)(nil).OrganizationHostAssignments), arg0, arg1) -} - -// MockSnapshotGenerator is a mock of SnapshotGenerator interface. -type MockSnapshotGenerator struct { - ctrl *gomock.Controller - recorder *MockSnapshotGeneratorMockRecorder -} - -// MockSnapshotGeneratorMockRecorder is the mock recorder for MockSnapshotGenerator. -type MockSnapshotGeneratorMockRecorder struct { - mock *MockSnapshotGenerator -} - -// NewMockSnapshotGenerator creates a new mock instance. -func NewMockSnapshotGenerator(ctrl *gomock.Controller) *MockSnapshotGenerator { - mock := &MockSnapshotGenerator{ctrl: ctrl} - mock.recorder = &MockSnapshotGeneratorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSnapshotGenerator) EXPECT() *MockSnapshotGeneratorMockRecorder { - return m.recorder -} - -// GenerateSnapshot mocks base method. -func (m *MockSnapshotGenerator) GenerateSnapshot() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GenerateSnapshot") - ret0, _ := ret[0].(error) - return ret0 -} - -// GenerateSnapshot indicates an expected call of GenerateSnapshot. -func (mr *MockSnapshotGeneratorMockRecorder) GenerateSnapshot() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateSnapshot", reflect.TypeOf((*MockSnapshotGenerator)(nil).GenerateSnapshot)) -} - -// MockServerUsageReportDownloader is a mock of ServerUsageReportDownloader interface. -type MockServerUsageReportDownloader struct { - ctrl *gomock.Controller - recorder *MockServerUsageReportDownloaderMockRecorder -} - -// MockServerUsageReportDownloaderMockRecorder is the mock recorder for MockServerUsageReportDownloader. -type MockServerUsageReportDownloaderMockRecorder struct { - mock *MockServerUsageReportDownloader -} - -// NewMockServerUsageReportDownloader creates a new mock instance. -func NewMockServerUsageReportDownloader(ctrl *gomock.Controller) *MockServerUsageReportDownloader { - mock := &MockServerUsageReportDownloader{ctrl: ctrl} - mock.recorder = &MockServerUsageReportDownloaderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockServerUsageReportDownloader) EXPECT() *MockServerUsageReportDownloaderMockRecorder { - return m.recorder -} - -// DownloadServerUsageReport mocks base method. -func (m *MockServerUsageReportDownloader) DownloadServerUsageReport(arg0 *opsmngr.ServerTypeOptions, arg1 io.Writer) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DownloadServerUsageReport", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// DownloadServerUsageReport indicates an expected call of DownloadServerUsageReport. -func (mr *MockServerUsageReportDownloaderMockRecorder) DownloadServerUsageReport(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DownloadServerUsageReport", reflect.TypeOf((*MockServerUsageReportDownloader)(nil).DownloadServerUsageReport), arg0, arg1) -} diff --git a/internal/mocks/mock_teams.go b/internal/mocks/mock_teams.go deleted file mode 100644 index 44b15c6f99..0000000000 --- a/internal/mocks/mock_teams.go +++ /dev/null @@ -1,291 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: TeamLister,TeamDescriber,TeamCreator,TeamDeleter,TeamAdder,TeamUserRemover,TeamRolesUpdater) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockTeamLister is a mock of TeamLister interface. -type MockTeamLister struct { - ctrl *gomock.Controller - recorder *MockTeamListerMockRecorder -} - -// MockTeamListerMockRecorder is the mock recorder for MockTeamLister. -type MockTeamListerMockRecorder struct { - mock *MockTeamLister -} - -// NewMockTeamLister creates a new mock instance. -func NewMockTeamLister(ctrl *gomock.Controller) *MockTeamLister { - mock := &MockTeamLister{ctrl: ctrl} - mock.recorder = &MockTeamListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTeamLister) EXPECT() *MockTeamListerMockRecorder { - return m.recorder -} - -// Teams mocks base method. -func (m *MockTeamLister) Teams(arg0 string, arg1 *mongodbatlas.ListOptions) ([]mongodbatlas.Team, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Teams", arg0, arg1) - ret0, _ := ret[0].([]mongodbatlas.Team) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Teams indicates an expected call of Teams. -func (mr *MockTeamListerMockRecorder) Teams(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Teams", reflect.TypeOf((*MockTeamLister)(nil).Teams), arg0, arg1) -} - -// MockTeamDescriber is a mock of TeamDescriber interface. -type MockTeamDescriber struct { - ctrl *gomock.Controller - recorder *MockTeamDescriberMockRecorder -} - -// MockTeamDescriberMockRecorder is the mock recorder for MockTeamDescriber. -type MockTeamDescriberMockRecorder struct { - mock *MockTeamDescriber -} - -// NewMockTeamDescriber creates a new mock instance. -func NewMockTeamDescriber(ctrl *gomock.Controller) *MockTeamDescriber { - mock := &MockTeamDescriber{ctrl: ctrl} - mock.recorder = &MockTeamDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTeamDescriber) EXPECT() *MockTeamDescriberMockRecorder { - return m.recorder -} - -// TeamByID mocks base method. -func (m *MockTeamDescriber) TeamByID(arg0, arg1 string) (*mongodbatlas.Team, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamByID", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.Team) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamByID indicates an expected call of TeamByID. -func (mr *MockTeamDescriberMockRecorder) TeamByID(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamByID", reflect.TypeOf((*MockTeamDescriber)(nil).TeamByID), arg0, arg1) -} - -// TeamByName mocks base method. -func (m *MockTeamDescriber) TeamByName(arg0, arg1 string) (*mongodbatlas.Team, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamByName", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.Team) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamByName indicates an expected call of TeamByName. -func (mr *MockTeamDescriberMockRecorder) TeamByName(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamByName", reflect.TypeOf((*MockTeamDescriber)(nil).TeamByName), arg0, arg1) -} - -// MockTeamCreator is a mock of TeamCreator interface. -type MockTeamCreator struct { - ctrl *gomock.Controller - recorder *MockTeamCreatorMockRecorder -} - -// MockTeamCreatorMockRecorder is the mock recorder for MockTeamCreator. -type MockTeamCreatorMockRecorder struct { - mock *MockTeamCreator -} - -// NewMockTeamCreator creates a new mock instance. -func NewMockTeamCreator(ctrl *gomock.Controller) *MockTeamCreator { - mock := &MockTeamCreator{ctrl: ctrl} - mock.recorder = &MockTeamCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTeamCreator) EXPECT() *MockTeamCreatorMockRecorder { - return m.recorder -} - -// CreateTeam mocks base method. -func (m *MockTeamCreator) CreateTeam(arg0 string, arg1 *mongodbatlas.Team) (*mongodbatlas.Team, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateTeam", arg0, arg1) - ret0, _ := ret[0].(*mongodbatlas.Team) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateTeam indicates an expected call of CreateTeam. -func (mr *MockTeamCreatorMockRecorder) CreateTeam(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateTeam", reflect.TypeOf((*MockTeamCreator)(nil).CreateTeam), arg0, arg1) -} - -// MockTeamDeleter is a mock of TeamDeleter interface. -type MockTeamDeleter struct { - ctrl *gomock.Controller - recorder *MockTeamDeleterMockRecorder -} - -// MockTeamDeleterMockRecorder is the mock recorder for MockTeamDeleter. -type MockTeamDeleterMockRecorder struct { - mock *MockTeamDeleter -} - -// NewMockTeamDeleter creates a new mock instance. -func NewMockTeamDeleter(ctrl *gomock.Controller) *MockTeamDeleter { - mock := &MockTeamDeleter{ctrl: ctrl} - mock.recorder = &MockTeamDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTeamDeleter) EXPECT() *MockTeamDeleterMockRecorder { - return m.recorder -} - -// DeleteTeam mocks base method. -func (m *MockTeamDeleter) DeleteTeam(arg0, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteTeam", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteTeam indicates an expected call of DeleteTeam. -func (mr *MockTeamDeleterMockRecorder) DeleteTeam(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteTeam", reflect.TypeOf((*MockTeamDeleter)(nil).DeleteTeam), arg0, arg1) -} - -// MockTeamAdder is a mock of TeamAdder interface. -type MockTeamAdder struct { - ctrl *gomock.Controller - recorder *MockTeamAdderMockRecorder -} - -// MockTeamAdderMockRecorder is the mock recorder for MockTeamAdder. -type MockTeamAdderMockRecorder struct { - mock *MockTeamAdder -} - -// NewMockTeamAdder creates a new mock instance. -func NewMockTeamAdder(ctrl *gomock.Controller) *MockTeamAdder { - mock := &MockTeamAdder{ctrl: ctrl} - mock.recorder = &MockTeamAdderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTeamAdder) EXPECT() *MockTeamAdderMockRecorder { - return m.recorder -} - -// AddUsersToTeam mocks base method. -func (m *MockTeamAdder) AddUsersToTeam(arg0, arg1 string, arg2 []string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddUsersToTeam", arg0, arg1, arg2) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AddUsersToTeam indicates an expected call of AddUsersToTeam. -func (mr *MockTeamAdderMockRecorder) AddUsersToTeam(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUsersToTeam", reflect.TypeOf((*MockTeamAdder)(nil).AddUsersToTeam), arg0, arg1, arg2) -} - -// MockTeamUserRemover is a mock of TeamUserRemover interface. -type MockTeamUserRemover struct { - ctrl *gomock.Controller - recorder *MockTeamUserRemoverMockRecorder -} - -// MockTeamUserRemoverMockRecorder is the mock recorder for MockTeamUserRemover. -type MockTeamUserRemoverMockRecorder struct { - mock *MockTeamUserRemover -} - -// NewMockTeamUserRemover creates a new mock instance. -func NewMockTeamUserRemover(ctrl *gomock.Controller) *MockTeamUserRemover { - mock := &MockTeamUserRemover{ctrl: ctrl} - mock.recorder = &MockTeamUserRemoverMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTeamUserRemover) EXPECT() *MockTeamUserRemoverMockRecorder { - return m.recorder -} - -// RemoveUserFromTeam mocks base method. -func (m *MockTeamUserRemover) RemoveUserFromTeam(arg0, arg1, arg2 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RemoveUserFromTeam", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// RemoveUserFromTeam indicates an expected call of RemoveUserFromTeam. -func (mr *MockTeamUserRemoverMockRecorder) RemoveUserFromTeam(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveUserFromTeam", reflect.TypeOf((*MockTeamUserRemover)(nil).RemoveUserFromTeam), arg0, arg1, arg2) -} - -// MockTeamRolesUpdater is a mock of TeamRolesUpdater interface. -type MockTeamRolesUpdater struct { - ctrl *gomock.Controller - recorder *MockTeamRolesUpdaterMockRecorder -} - -// MockTeamRolesUpdaterMockRecorder is the mock recorder for MockTeamRolesUpdater. -type MockTeamRolesUpdaterMockRecorder struct { - mock *MockTeamRolesUpdater -} - -// NewMockTeamRolesUpdater creates a new mock instance. -func NewMockTeamRolesUpdater(ctrl *gomock.Controller) *MockTeamRolesUpdater { - mock := &MockTeamRolesUpdater{ctrl: ctrl} - mock.recorder = &MockTeamRolesUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTeamRolesUpdater) EXPECT() *MockTeamRolesUpdaterMockRecorder { - return m.recorder -} - -// UpdateProjectTeamRoles mocks base method. -func (m *MockTeamRolesUpdater) UpdateProjectTeamRoles(arg0, arg1 string, arg2 *mongodbatlas.TeamUpdateRoles) ([]mongodbatlas.TeamRoles, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateProjectTeamRoles", arg0, arg1, arg2) - ret0, _ := ret[0].([]mongodbatlas.TeamRoles) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateProjectTeamRoles indicates an expected call of UpdateProjectTeamRoles. -func (mr *MockTeamRolesUpdaterMockRecorder) UpdateProjectTeamRoles(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateProjectTeamRoles", reflect.TypeOf((*MockTeamRolesUpdater)(nil).UpdateProjectTeamRoles), arg0, arg1, arg2) -} diff --git a/internal/mocks/mock_users.go b/internal/mocks/mock_users.go deleted file mode 100644 index 4a09f882ab..0000000000 --- a/internal/mocks/mock_users.go +++ /dev/null @@ -1,217 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: UserCreator,UserDescriber,UserDeleter,UserLister,TeamUserLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - store "github.com/mongodb/mongodb-atlas-cli/internal/store" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockUserCreator is a mock of UserCreator interface. -type MockUserCreator struct { - ctrl *gomock.Controller - recorder *MockUserCreatorMockRecorder -} - -// MockUserCreatorMockRecorder is the mock recorder for MockUserCreator. -type MockUserCreatorMockRecorder struct { - mock *MockUserCreator -} - -// NewMockUserCreator creates a new mock instance. -func NewMockUserCreator(ctrl *gomock.Controller) *MockUserCreator { - mock := &MockUserCreator{ctrl: ctrl} - mock.recorder = &MockUserCreatorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockUserCreator) EXPECT() *MockUserCreatorMockRecorder { - return m.recorder -} - -// CreateUser mocks base method. -func (m *MockUserCreator) CreateUser(arg0 *store.UserRequest) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateUser", arg0) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateUser indicates an expected call of CreateUser. -func (mr *MockUserCreatorMockRecorder) CreateUser(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateUser", reflect.TypeOf((*MockUserCreator)(nil).CreateUser), arg0) -} - -// MockUserDescriber is a mock of UserDescriber interface. -type MockUserDescriber struct { - ctrl *gomock.Controller - recorder *MockUserDescriberMockRecorder -} - -// MockUserDescriberMockRecorder is the mock recorder for MockUserDescriber. -type MockUserDescriberMockRecorder struct { - mock *MockUserDescriber -} - -// NewMockUserDescriber creates a new mock instance. -func NewMockUserDescriber(ctrl *gomock.Controller) *MockUserDescriber { - mock := &MockUserDescriber{ctrl: ctrl} - mock.recorder = &MockUserDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockUserDescriber) EXPECT() *MockUserDescriberMockRecorder { - return m.recorder -} - -// UserByID mocks base method. -func (m *MockUserDescriber) UserByID(arg0 string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UserByID", arg0) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UserByID indicates an expected call of UserByID. -func (mr *MockUserDescriberMockRecorder) UserByID(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UserByID", reflect.TypeOf((*MockUserDescriber)(nil).UserByID), arg0) -} - -// UserByName mocks base method. -func (m *MockUserDescriber) UserByName(arg0 string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UserByName", arg0) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UserByName indicates an expected call of UserByName. -func (mr *MockUserDescriberMockRecorder) UserByName(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UserByName", reflect.TypeOf((*MockUserDescriber)(nil).UserByName), arg0) -} - -// MockUserDeleter is a mock of UserDeleter interface. -type MockUserDeleter struct { - ctrl *gomock.Controller - recorder *MockUserDeleterMockRecorder -} - -// MockUserDeleterMockRecorder is the mock recorder for MockUserDeleter. -type MockUserDeleterMockRecorder struct { - mock *MockUserDeleter -} - -// NewMockUserDeleter creates a new mock instance. -func NewMockUserDeleter(ctrl *gomock.Controller) *MockUserDeleter { - mock := &MockUserDeleter{ctrl: ctrl} - mock.recorder = &MockUserDeleterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockUserDeleter) EXPECT() *MockUserDeleterMockRecorder { - return m.recorder -} - -// DeleteUser mocks base method. -func (m *MockUserDeleter) DeleteUser(arg0 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteUser", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteUser indicates an expected call of DeleteUser. -func (mr *MockUserDeleterMockRecorder) DeleteUser(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUser", reflect.TypeOf((*MockUserDeleter)(nil).DeleteUser), arg0) -} - -// MockUserLister is a mock of UserLister interface. -type MockUserLister struct { - ctrl *gomock.Controller - recorder *MockUserListerMockRecorder -} - -// MockUserListerMockRecorder is the mock recorder for MockUserLister. -type MockUserListerMockRecorder struct { - mock *MockUserLister -} - -// NewMockUserLister creates a new mock instance. -func NewMockUserLister(ctrl *gomock.Controller) *MockUserLister { - mock := &MockUserLister{ctrl: ctrl} - mock.recorder = &MockUserListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockUserLister) EXPECT() *MockUserListerMockRecorder { - return m.recorder -} - -// OrganizationUsers mocks base method. -func (m *MockUserLister) OrganizationUsers(arg0 string, arg1 *mongodbatlas.ListOptions) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "OrganizationUsers", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OrganizationUsers indicates an expected call of OrganizationUsers. -func (mr *MockUserListerMockRecorder) OrganizationUsers(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OrganizationUsers", reflect.TypeOf((*MockUserLister)(nil).OrganizationUsers), arg0, arg1) -} - -// MockTeamUserLister is a mock of TeamUserLister interface. -type MockTeamUserLister struct { - ctrl *gomock.Controller - recorder *MockTeamUserListerMockRecorder -} - -// MockTeamUserListerMockRecorder is the mock recorder for MockTeamUserLister. -type MockTeamUserListerMockRecorder struct { - mock *MockTeamUserLister -} - -// NewMockTeamUserLister creates a new mock instance. -func NewMockTeamUserLister(ctrl *gomock.Controller) *MockTeamUserLister { - mock := &MockTeamUserLister{ctrl: ctrl} - mock.recorder = &MockTeamUserListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTeamUserLister) EXPECT() *MockTeamUserListerMockRecorder { - return m.recorder -} - -// TeamUsers mocks base method. -func (m *MockTeamUserLister) TeamUsers(arg0, arg1 string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamUsers", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamUsers indicates an expected call of TeamUsers. -func (mr *MockTeamUserListerMockRecorder) TeamUsers(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamUsers", reflect.TypeOf((*MockTeamUserLister)(nil).TeamUsers), arg0, arg1) -} diff --git a/internal/mocks/mock_version_manifest.go b/internal/mocks/mock_version_manifest.go deleted file mode 100644 index 1ff4fb04f6..0000000000 --- a/internal/mocks/mock_version_manifest.go +++ /dev/null @@ -1,142 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store (interfaces: VersionManifestUpdater,VersionManifestGetter,VersionManifestUpdaterServiceVersionDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" - opsmngr "go.mongodb.org/ops-manager/opsmngr" -) - -// MockVersionManifestUpdater is a mock of VersionManifestUpdater interface. -type MockVersionManifestUpdater struct { - ctrl *gomock.Controller - recorder *MockVersionManifestUpdaterMockRecorder -} - -// MockVersionManifestUpdaterMockRecorder is the mock recorder for MockVersionManifestUpdater. -type MockVersionManifestUpdaterMockRecorder struct { - mock *MockVersionManifestUpdater -} - -// NewMockVersionManifestUpdater creates a new mock instance. -func NewMockVersionManifestUpdater(ctrl *gomock.Controller) *MockVersionManifestUpdater { - mock := &MockVersionManifestUpdater{ctrl: ctrl} - mock.recorder = &MockVersionManifestUpdaterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVersionManifestUpdater) EXPECT() *MockVersionManifestUpdaterMockRecorder { - return m.recorder -} - -// UpdateVersionManifest mocks base method. -func (m *MockVersionManifestUpdater) UpdateVersionManifest(arg0 *opsmngr.VersionManifest) (*opsmngr.VersionManifest, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateVersionManifest", arg0) - ret0, _ := ret[0].(*opsmngr.VersionManifest) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateVersionManifest indicates an expected call of UpdateVersionManifest. -func (mr *MockVersionManifestUpdaterMockRecorder) UpdateVersionManifest(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateVersionManifest", reflect.TypeOf((*MockVersionManifestUpdater)(nil).UpdateVersionManifest), arg0) -} - -// MockVersionManifestGetter is a mock of VersionManifestGetter interface. -type MockVersionManifestGetter struct { - ctrl *gomock.Controller - recorder *MockVersionManifestGetterMockRecorder -} - -// MockVersionManifestGetterMockRecorder is the mock recorder for MockVersionManifestGetter. -type MockVersionManifestGetterMockRecorder struct { - mock *MockVersionManifestGetter -} - -// NewMockVersionManifestGetter creates a new mock instance. -func NewMockVersionManifestGetter(ctrl *gomock.Controller) *MockVersionManifestGetter { - mock := &MockVersionManifestGetter{ctrl: ctrl} - mock.recorder = &MockVersionManifestGetterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVersionManifestGetter) EXPECT() *MockVersionManifestGetterMockRecorder { - return m.recorder -} - -// GetVersionManifest mocks base method. -func (m *MockVersionManifestGetter) GetVersionManifest(arg0 string) (*opsmngr.VersionManifest, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetVersionManifest", arg0) - ret0, _ := ret[0].(*opsmngr.VersionManifest) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetVersionManifest indicates an expected call of GetVersionManifest. -func (mr *MockVersionManifestGetterMockRecorder) GetVersionManifest(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVersionManifest", reflect.TypeOf((*MockVersionManifestGetter)(nil).GetVersionManifest), arg0) -} - -// MockVersionManifestUpdaterServiceVersionDescriber is a mock of VersionManifestUpdaterServiceVersionDescriber interface. -type MockVersionManifestUpdaterServiceVersionDescriber struct { - ctrl *gomock.Controller - recorder *MockVersionManifestUpdaterServiceVersionDescriberMockRecorder -} - -// MockVersionManifestUpdaterServiceVersionDescriberMockRecorder is the mock recorder for MockVersionManifestUpdaterServiceVersionDescriber. -type MockVersionManifestUpdaterServiceVersionDescriberMockRecorder struct { - mock *MockVersionManifestUpdaterServiceVersionDescriber -} - -// NewMockVersionManifestUpdaterServiceVersionDescriber creates a new mock instance. -func NewMockVersionManifestUpdaterServiceVersionDescriber(ctrl *gomock.Controller) *MockVersionManifestUpdaterServiceVersionDescriber { - mock := &MockVersionManifestUpdaterServiceVersionDescriber{ctrl: ctrl} - mock.recorder = &MockVersionManifestUpdaterServiceVersionDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVersionManifestUpdaterServiceVersionDescriber) EXPECT() *MockVersionManifestUpdaterServiceVersionDescriberMockRecorder { - return m.recorder -} - -// ServiceVersion mocks base method. -func (m *MockVersionManifestUpdaterServiceVersionDescriber) ServiceVersion() (*mongodbatlas.ServiceVersion, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServiceVersion") - ret0, _ := ret[0].(*mongodbatlas.ServiceVersion) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ServiceVersion indicates an expected call of ServiceVersion. -func (mr *MockVersionManifestUpdaterServiceVersionDescriberMockRecorder) ServiceVersion() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceVersion", reflect.TypeOf((*MockVersionManifestUpdaterServiceVersionDescriber)(nil).ServiceVersion)) -} - -// UpdateVersionManifest mocks base method. -func (m *MockVersionManifestUpdaterServiceVersionDescriber) UpdateVersionManifest(arg0 *opsmngr.VersionManifest) (*opsmngr.VersionManifest, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateVersionManifest", arg0) - ret0, _ := ret[0].(*opsmngr.VersionManifest) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateVersionManifest indicates an expected call of UpdateVersionManifest. -func (mr *MockVersionManifestUpdaterServiceVersionDescriberMockRecorder) UpdateVersionManifest(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateVersionManifest", reflect.TypeOf((*MockVersionManifestUpdaterServiceVersionDescriber)(nil).UpdateVersionManifest), arg0) -} diff --git a/internal/store/agents.go b/internal/store/agents.go deleted file mode 100644 index a293f78003..0000000000 --- a/internal/store/agents.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_agents.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store AgentLister,AgentUpgrader,AgentAPIKeyLister,AgentAPIKeyCreator,AgentAPIKeyDeleter,AgentGlobalVersionsLister,AgentProjectVersionsLister - -type AgentLister interface { - Agents(string, string, *opsmngr.ListOptions) (*opsmngr.Agents, error) -} - -type AgentGlobalVersionsLister interface { - AgentGlobalVersions() (*opsmngr.SoftwareVersions, error) -} - -type AgentProjectVersionsLister interface { - AgentProjectVersions(string) (*opsmngr.AgentVersions, error) -} - -type AgentUpgrader interface { - UpgradeAgent(string) (*opsmngr.AutomationConfigAgent, error) -} - -type AgentAPIKeyLister interface { - AgentAPIKeys(string) ([]*opsmngr.AgentAPIKey, error) -} - -type AgentAPIKeyCreator interface { - CreateAgentAPIKey(string, *opsmngr.AgentAPIKeysRequest) (*opsmngr.AgentAPIKey, error) -} - -type AgentAPIKeyDeleter interface { - DeleteAgentAPIKey(string, string) error -} - -// Agents encapsulates the logic to manage different cloud providers. -func (s *Store) Agents(projectID, agentType string, opts *opsmngr.ListOptions) (*opsmngr.Agents, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Agents.ListAgentsByType(s.ctx, projectID, agentType, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpgradeAgent encapsulates the logic to manage different cloud providers. -func (s *Store) UpgradeAgent(projectID string) (*opsmngr.AutomationConfigAgent, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Automation.UpdateAgentVersion(s.ctx, projectID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// AgentAPIKeys encapsulates the logic to manage different cloud providers. -func (s *Store) AgentAPIKeys(projectID string) ([]*opsmngr.AgentAPIKey, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Agents.ListAgentAPIKeys(s.ctx, projectID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateAgentAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) CreateAgentAPIKey(projectID string, r *opsmngr.AgentAPIKeysRequest) (*opsmngr.AgentAPIKey, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Agents.CreateAgentAPIKey(s.ctx, projectID, r) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteAgentAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteAgentAPIKey(projectID, keyID string) error { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - _, err := s.client.(*opsmngr.Client).Agents.DeleteAgentAPIKey(s.ctx, projectID, keyID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// AgentGlobalVersions encapsulates the logic to manage different cloud providers. -func (s *Store) AgentGlobalVersions() (*opsmngr.SoftwareVersions, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Agents.GlobalVersions(s.ctx) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// AgentProjectVersions encapsulates the logic to manage different cloud providers. -func (s *Store) AgentProjectVersions(projectID string) (*opsmngr.AgentVersions, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Agents.ProjectVersions(s.ctx, projectID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/alert_configuration.go b/internal/store/alert_configuration.go deleted file mode 100644 index c1282d5168..0000000000 --- a/internal/store/alert_configuration.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "github.com/mongodb/mongodb-atlas-cli/internal/pointer" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_alert_configuration.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store AlertConfigurationLister,AlertConfigurationCreator,AlertConfigurationDeleter,AlertConfigurationUpdater,MatcherFieldsLister,AlertConfigurationEnabler,AlertConfigurationDisabler - -type AlertConfigurationLister interface { - AlertConfigurations(string, *opsmngr.ListOptions) ([]atlas.AlertConfiguration, error) -} - -type AlertConfigurationCreator interface { - CreateAlertConfiguration(*atlas.AlertConfiguration) (*atlas.AlertConfiguration, error) -} - -type AlertConfigurationDeleter interface { - DeleteAlertConfiguration(string, string) error -} - -type AlertConfigurationUpdater interface { - UpdateAlertConfiguration(*atlas.AlertConfiguration) (*atlas.AlertConfiguration, error) -} - -type MatcherFieldsLister interface { - MatcherFields() ([]string, error) -} - -type AlertConfigurationEnabler interface { - EnableAlertConfiguration(string, string) (*atlas.AlertConfiguration, error) -} - -type AlertConfigurationDisabler interface { - DisableAlertConfiguration(string, string) (*atlas.AlertConfiguration, error) -} - -// AlertConfigurations encapsulate the logic to manage different cloud providers. -func (s *Store) AlertConfigurations(projectID string, opts *atlas.ListOptions) ([]atlas.AlertConfiguration, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AlertConfigurations.List(s.ctx, projectID, opts) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).AlertConfigurations.List(s.ctx, projectID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateAlertConfiguration encapsulate the logic to manage different cloud providers. -func (s *Store) CreateAlertConfiguration(alertConfig *atlas.AlertConfiguration) (*atlas.AlertConfiguration, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AlertConfigurations.Create(s.ctx, alertConfig.GroupID, alertConfig) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).AlertConfigurations.Create(s.ctx, alertConfig.GroupID, alertConfig) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteAlertConfiguration encapsulate the logic to manage different cloud providers. -func (s *Store) DeleteAlertConfiguration(projectID, id string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).AlertConfigurations.Delete(s.ctx, projectID, id) - return err - case config.OpsManagerService, config.CloudManagerService: - _, err := s.client.(*opsmngr.Client).AlertConfigurations.Delete(s.ctx, projectID, id) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// MatcherFields encapsulate the logic to manage different cloud providers. -func (s *Store) MatcherFields() ([]string, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AlertConfigurations.ListMatcherFields(s.ctx) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).AlertConfigurations.ListMatcherFields(s.ctx) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -func (s *Store) UpdateAlertConfiguration(alertConfig *atlas.AlertConfiguration) (*atlas.AlertConfiguration, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AlertConfigurations.Update(s.ctx, alertConfig.GroupID, alertConfig.ID, alertConfig) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).AlertConfigurations.Update(s.ctx, alertConfig.GroupID, alertConfig.ID, alertConfig) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// EnableAlertConfiguration encapsulate the logic to manage different cloud providers. -func (s *Store) EnableAlertConfiguration(projectID, id string) (*atlas.AlertConfiguration, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AlertConfigurations.EnableAnAlertConfig(s.ctx, projectID, id, pointer.Get(true)) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).AlertConfigurations.EnableAnAlertConfig(s.ctx, projectID, id, pointer.Get(true)) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DisableAlertConfiguration encapsulate the logic to manage different cloud providers. -func (s *Store) DisableAlertConfiguration(projectID, id string) (*atlas.AlertConfiguration, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AlertConfigurations.EnableAnAlertConfig(s.ctx, projectID, id, pointer.Get(false)) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).AlertConfigurations.EnableAnAlertConfig(s.ctx, projectID, id, pointer.Get(false)) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/alerts.go b/internal/store/alerts.go deleted file mode 100644 index 4c81072e0b..0000000000 --- a/internal/store/alerts.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_alerts.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store AlertDescriber,AlertLister,AlertAcknowledger - -type AlertDescriber interface { - Alert(string, string) (*opsmngr.Alert, error) -} - -type AlertLister interface { - Alerts(string, *opsmngr.AlertsListOptions) (*atlas.AlertsResponse, error) -} - -type AlertAcknowledger interface { - AcknowledgeAlert(string, string, *opsmngr.AcknowledgeRequest) (*atlas.Alert, error) -} - -// Alert encapsulate the logic to manage different cloud providers. -func (s *Store) Alert(projectID, alertID string) (*atlas.Alert, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Alerts.Get(s.ctx, projectID, alertID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// Alerts encapsulate the logic to manage different cloud providers. -func (s *Store) Alerts(projectID string, opts *opsmngr.AlertsListOptions) (*opsmngr.AlertsResponse, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Alerts.List(s.ctx, projectID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// Acknowledge encapsulate the logic to manage different cloud providers. -func (s *Store) AcknowledgeAlert(projectID, alertID string, body *opsmngr.AcknowledgeRequest) (*atlas.Alert, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Alerts.Acknowledge(s.ctx, projectID, alertID, body) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/api_keys.go b/internal/store/api_keys.go deleted file mode 100644 index b97a8dd0eb..0000000000 --- a/internal/store/api_keys.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_api_keys.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store ProjectAPIKeyLister,ProjectAPIKeyCreator,OrganizationAPIKeyLister,OrganizationAPIKeyDescriber,OrganizationAPIKeyUpdater,OrganizationAPIKeyCreator,OrganizationAPIKeyDeleter,ProjectAPIKeyDeleter,ProjectAPIKeyAssigner - -type ProjectAPIKeyLister interface { - ProjectAPIKeys(string, *atlas.ListOptions) ([]atlas.APIKey, error) -} - -type ProjectAPIKeyCreator interface { - CreateProjectAPIKey(string, *atlas.APIKeyInput) (*atlas.APIKey, error) -} - -type ProjectAPIKeyDeleter interface { - DeleteProjectAPIKey(string, string) error -} - -type ProjectAPIKeyAssigner interface { - AssignProjectAPIKey(string, string, *atlas.AssignAPIKey) error -} - -type OrganizationAPIKeyLister interface { - OrganizationAPIKeys(string, *atlas.ListOptions) ([]atlas.APIKey, error) -} - -type OrganizationAPIKeyDescriber interface { - OrganizationAPIKey(string, string) (*atlas.APIKey, error) -} - -type OrganizationAPIKeyUpdater interface { - UpdateOrganizationAPIKey(string, string, *atlas.APIKeyInput) (*atlas.APIKey, error) -} - -type OrganizationAPIKeyCreator interface { - CreateOrganizationAPIKey(string, *atlas.APIKeyInput) (*atlas.APIKey, error) -} - -type OrganizationAPIKeyDeleter interface { - DeleteOrganizationAPIKey(string, string) error -} - -// OrganizationAPIKeys encapsulates the logic to manage different cloud providers. -func (s *Store) OrganizationAPIKeys(orgID string, opts *atlas.ListOptions) ([]atlas.APIKey, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).APIKeys.List(s.ctx, orgID, opts) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).OrganizationAPIKeys.List(s.ctx, orgID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// OrganizationAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) OrganizationAPIKey(orgID, apiKeyID string) (*atlas.APIKey, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).APIKeys.Get(s.ctx, orgID, apiKeyID) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).OrganizationAPIKeys.Get(s.ctx, orgID, apiKeyID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateOrganizationAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateOrganizationAPIKey(orgID, apiKeyID string, input *atlas.APIKeyInput) (*atlas.APIKey, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).APIKeys.Update(s.ctx, orgID, apiKeyID, input) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).OrganizationAPIKeys.Update(s.ctx, orgID, apiKeyID, input) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateOrganizationAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) CreateOrganizationAPIKey(orgID string, input *atlas.APIKeyInput) (*atlas.APIKey, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).APIKeys.Create(s.ctx, orgID, input) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).OrganizationAPIKeys.Create(s.ctx, orgID, input) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteOrganizationAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteOrganizationAPIKey(orgID, id string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).APIKeys.Delete(s.ctx, orgID, id) - return err - case config.CloudManagerService, config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).OrganizationAPIKeys.Delete(s.ctx, orgID, id) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// ProjectAPIKeys returns the API Keys for a specific project. -func (s *Store) ProjectAPIKeys(projectID string, opts *atlas.ListOptions) ([]atlas.APIKey, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).ProjectAPIKeys.List(s.ctx, projectID, opts) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).ProjectAPIKeys.List(s.ctx, projectID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateProjectAPIKey creates an API Keys for a project. -func (s *Store) CreateProjectAPIKey(projectID string, apiKeyInput *atlas.APIKeyInput) (*atlas.APIKey, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).ProjectAPIKeys.Create(s.ctx, projectID, apiKeyInput) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).ProjectAPIKeys.Create(s.ctx, projectID, apiKeyInput) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// AssignProjectAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) AssignProjectAPIKey(projectID, apiKeyID string, input *atlas.AssignAPIKey) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).ProjectAPIKeys.Assign(s.ctx, projectID, apiKeyID, input) - return err - case config.OpsManagerService, config.CloudManagerService: - _, err := s.client.(*opsmngr.Client).ProjectAPIKeys.Assign(s.ctx, projectID, apiKeyID, input) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteProjectAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteProjectAPIKey(projectID, id string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).ProjectAPIKeys.Unassign(s.ctx, projectID, id) - return err - case config.CloudManagerService, config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).ProjectAPIKeys.Unassign(s.ctx, projectID, id) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/api_keys_access_list.go b/internal/store/api_keys_access_list.go deleted file mode 100644 index d9da5dd09c..0000000000 --- a/internal/store/api_keys_access_list.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_api_keys_access_list.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store OrganizationAPIKeyAccessListCreator,OrganizationAPIKeyAccessListDeleter,OrganizationAPIKeyAccessListLister - -type OrganizationAPIKeyAccessListLister interface { - OrganizationAPIKeyAccessLists(string, string, *opsmngr.ListOptions) (*atlas.AccessListAPIKeys, error) -} - -type OrganizationAPIKeyAccessListDeleter interface { - DeleteOrganizationAPIKeyAccessList(string, string, string) error -} - -type OrganizationAPIKeyAccessListCreator interface { - CreateOrganizationAPIKeyAccessList(string, string, []*atlas.AccessListAPIKeysReq) (*atlas.AccessListAPIKeys, error) -} - -// CreateOrganizationAPIKeyAccessList encapsulates the logic to manage different cloud providers. -func (s *Store) CreateOrganizationAPIKeyAccessList(orgID, apiKeyID string, opts []*atlas.AccessListAPIKeysReq) (*atlas.AccessListAPIKeys, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AccessListAPIKeys.Create(s.ctx, orgID, apiKeyID, opts) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).AccessListAPIKeys.Create(s.ctx, orgID, apiKeyID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteOrganizationAPIKeyAccessList encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteOrganizationAPIKeyAccessList(orgID, apiKeyID, ipAddress string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).AccessListAPIKeys.Delete(s.ctx, orgID, apiKeyID, ipAddress) - return err - case config.CloudManagerService, config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).AccessListAPIKeys.Delete(s.ctx, orgID, apiKeyID, ipAddress) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// OrganizationAPIKeyAccessLists encapsulates the logic to manage different cloud providers. -func (s *Store) OrganizationAPIKeyAccessLists(orgID, apiKeyID string, opts *atlas.ListOptions) (*atlas.AccessListAPIKeys, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AccessListAPIKeys.List(s.ctx, orgID, apiKeyID, opts) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).AccessListAPIKeys.List(s.ctx, orgID, apiKeyID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/atlas/service_version.go b/internal/store/atlas/service_version.go deleted file mode 100644 index 6661dd9039..0000000000 --- a/internal/store/atlas/service_version.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package atlas - -import ( - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../../mocks/atlas/mock_service_version.go -package=atlas github.com/mongodb/mongodb-atlas-cli/internal/store/atlas ServiceVersionDescriber - -type ServiceVersionDescriber interface { - ServiceVersion() (*opsmngr.ServiceVersion, error) -} - -// ServiceVersion encapsulates the logic to manage different cloud providers. -func (s *Store) ServiceVersion() (*atlas.ServiceVersion, error) { - result, _, err := s.client.ServiceVersion.Get(s.ctx) - return result, err -} diff --git a/internal/store/automation.go b/internal/store/automation.go deleted file mode 100644 index 5118a29ff2..0000000000 --- a/internal/store/automation.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_automation.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store AutomationGetter,AutomationUpdater,AutomationStatusGetter,AutomationPatcher,CloudManagerClustersLister,CloudManagerClustersDescriber,CloudManagerClustersDeleter - -type AutomationGetter interface { - GetAutomationConfig(string) (*opsmngr.AutomationConfig, error) -} - -type AutomationUpdater interface { - UpdateAutomationConfig(string, *opsmngr.AutomationConfig) error -} - -type AutomationStatusGetter interface { - GetAutomationStatus(string) (*opsmngr.AutomationStatus, error) -} - -type AutomationPatcher interface { - AutomationGetter - AutomationUpdater -} - -type AllClusterLister interface { - ListAllProjectClusters() (*opsmngr.AllClustersProjects, error) -} - -type CloudManagerClustersLister interface { - AutomationGetter - ClusterLister - AllClusterLister -} - -type CloudManagerClustersDescriber interface { - AutomationGetter - OpsManagerClusterDescriber -} - -type CloudManagerClustersDeleter interface { - AutomationStatusGetter - MonitoringStopper - HostByHostnameDescriber - AutomationPatcher -} - -func (s *Store) GetAutomationStatus(projectID string) (*opsmngr.AutomationStatus, error) { - switch s.service { - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Automation.GetStatus(s.ctx, projectID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// GetAutomationConfig encapsulate the logic to manage different cloud providers. -func (s *Store) GetAutomationConfig(projectID string) (*opsmngr.AutomationConfig, error) { - switch s.service { - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Automation.GetConfig(s.ctx, projectID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateAutomationConfig encapsulate the logic to manage different cloud providers. -func (s *Store) UpdateAutomationConfig(projectID string, automationConfig *opsmngr.AutomationConfig) error { - switch s.service { - case config.CloudManagerService, config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).Automation.UpdateConfig(s.ctx, projectID, automationConfig) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/backup_configs.go b/internal/store/backup_configs.go deleted file mode 100644 index cee3613aa6..0000000000 --- a/internal/store/backup_configs.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_backup_config.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store BackupConfigGetter,BackupConfigLister,BackupConfigUpdater - -type BackupConfigGetter interface { - GetBackupConfig(string, string) (*opsmngr.BackupConfig, error) -} - -type BackupConfigLister interface { - ListBackupConfigs(string, *opsmngr.ListOptions) (*opsmngr.BackupConfigs, error) -} - -type BackupConfigUpdater interface { - UpdateBackupConfig(*opsmngr.BackupConfig) (*opsmngr.BackupConfig, error) -} - -// GetBackupConfig encapsulates the logic to manage different cloud providers. -func (s *Store) GetBackupConfig(projectID, clusterID string) (*opsmngr.BackupConfig, error) { - switch s.service { - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).BackupConfigs.Get(s.ctx, projectID, clusterID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// ListBackupConfigs encapsulates the logic to manage different cloud providers. -func (s *Store) ListBackupConfigs(projectID string, options *opsmngr.ListOptions) (*opsmngr.BackupConfigs, error) { - switch s.service { - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).BackupConfigs.List(s.ctx, projectID, options) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateBackupConfig encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateBackupConfig(backupConfig *opsmngr.BackupConfig) (*opsmngr.BackupConfig, error) { - switch s.service { - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).BackupConfigs.Update(s.ctx, backupConfig.GroupID, backupConfig.ClusterID, backupConfig) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/blockstores.go b/internal/store/blockstores.go deleted file mode 100644 index 4da8d53ecb..0000000000 --- a/internal/store/blockstores.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_backup_blockstores.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store BlockstoresLister,BlockstoresDescriber,BlockstoresCreator,BlockstoresUpdater,BlockstoresDeleter - -type BlockstoresLister interface { - ListBlockstores(*opsmngr.ListOptions) (*opsmngr.BackupStores, error) -} - -type BlockstoresDescriber interface { - DescribeBlockstore(string) (*opsmngr.BackupStore, error) -} - -type BlockstoresCreator interface { - CreateBlockstore(*opsmngr.BackupStore) (*opsmngr.BackupStore, error) -} - -type BlockstoresUpdater interface { - UpdateBlockstore(*opsmngr.BackupStore) (*opsmngr.BackupStore, error) -} - -type BlockstoresDeleter interface { - DeleteBlockstore(string) error -} - -// ListBlockstore encapsulates the logic to manage different cloud providers. -func (s *Store) ListBlockstores(options *opsmngr.ListOptions) (*opsmngr.BackupStores, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).BlockstoreConfig.List(s.ctx, options) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DescribeBlockstore encapsulates the logic to manage different cloud providers. -func (s *Store) DescribeBlockstore(blockstoreID string) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).BlockstoreConfig.Get(s.ctx, blockstoreID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateBlockstore encapsulates the logic to manage different cloud providers. -func (s *Store) CreateBlockstore(blockstore *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).BlockstoreConfig.Create(s.ctx, blockstore) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateBlockstore encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateBlockstore(blockstore *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).BlockstoreConfig.Update(s.ctx, blockstore.ID, blockstore) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteBlockstore encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteBlockstore(blockstoreID string) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).BlockstoreConfig.Delete(s.ctx, blockstoreID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/continuous_backup.go b/internal/store/continuous_backup.go deleted file mode 100644 index dbf9b05795..0000000000 --- a/internal/store/continuous_backup.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_continuous_backup.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store CheckpointsLister,ContinuousJobLister,ContinuousJobCreator,ContinuousSnapshotsLister - -type CheckpointsLister interface { - Checkpoints(string, string, *atlas.ListOptions) (*atlas.Checkpoints, error) -} - -type ContinuousJobLister interface { - ContinuousRestoreJobs(string, string, *atlas.ListOptions) (*atlas.ContinuousJobs, error) -} - -type ContinuousJobCreator interface { - CreateContinuousRestoreJob(string, string, *atlas.ContinuousJobRequest) (*atlas.ContinuousJobs, error) -} - -type ContinuousSnapshotsLister interface { - ContinuousSnapshots(string, string, *atlas.ListOptions) (*atlas.ContinuousSnapshots, error) -} - -// Checkpoints encapsulate the logic to manage different cloud providers. -func (s *Store) Checkpoints(projectID, clusterID string, opts *atlas.ListOptions) (*atlas.Checkpoints, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Checkpoints.List(s.ctx, projectID, clusterID, opts) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Checkpoints.List(s.ctx, projectID, clusterID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// ContinuousRestoreJobs encapsulate the logic to manage different cloud providers. -func (s *Store) ContinuousRestoreJobs(projectID, clusterID string, opts *atlas.ListOptions) (*atlas.ContinuousJobs, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).ContinuousRestoreJobs.List(s.ctx, projectID, clusterID, opts) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).ContinuousRestoreJobs.List(s.ctx, projectID, clusterID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateContinuousRestoreJob encapsulate the logic to manage different cloud providers. -func (s *Store) CreateContinuousRestoreJob(projectID, clusterID string, request *atlas.ContinuousJobRequest) (*atlas.ContinuousJobs, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).ContinuousRestoreJobs.Create(s.ctx, projectID, clusterID, request) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).ContinuousRestoreJobs.Create(s.ctx, projectID, clusterID, request) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// ContinuousSnapshots encapsulate the logic to manage different cloud providers. -func (s *Store) ContinuousSnapshots(projectID, clusterID string, opts *atlas.ListOptions) (*atlas.ContinuousSnapshots, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).ContinuousSnapshots.List(s.ctx, projectID, clusterID, opts) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).ContinuousSnapshots.List(s.ctx, projectID, clusterID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/data_federation.go b/internal/store/data_federation.go deleted file mode 100644 index 907518195b..0000000000 --- a/internal/store/data_federation.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2023 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -//go:generate mockgen -destination=../mocks/mock_data_federation.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store DataFederationLister,DataFederationStore - -type DataFederationStore interface { - DataFederationLister - atlas.DataFederationDescriber -} - -type DataFederationLister interface { - DataFederationList(string) ([]admin.DataLakeTenant, error) -} - -// DataFederationList encapsulates the logic to manage different cloud providers. -func (s *Store) DataFederationList(projectID string) ([]admin.DataLakeTenant, error) { - req := s.clientv2.DataFederationApi.ListFederatedDatabases(s.ctx, projectID) - result, _, err := req.Execute() - return result, err -} - -// DataFederation encapsulates the logic to manage different cloud providers. -func (s *Store) DataFederation(projectID, id string) (*admin.DataLakeTenant, error) { - result, _, err := s.clientv2.DataFederationApi.GetFederatedDatabase(s.ctx, projectID, id).Execute() - return result, err -} diff --git a/internal/store/deployments.go b/internal/store/deployments.go deleted file mode 100644 index f38f000aeb..0000000000 --- a/internal/store/deployments.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_deployments.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store HostLister,HostDescriber,HostDatabaseLister,HostDisksLister,HostByHostnameDescriber - -type HostLister interface { - Hosts(string, *opsmngr.HostListOptions) (*opsmngr.Hosts, error) -} - -type HostDescriber interface { - Host(string, string) (*opsmngr.Host, error) -} -type HostByHostnameDescriber interface { - HostByHostname(string, string, int) (*opsmngr.Host, error) -} - -type HostDatabaseLister interface { - HostDatabases(string, string, *atlas.ListOptions) (*atlas.ProcessDatabasesResponse, error) -} - -type HostDisksLister interface { - HostDisks(string, string, *atlas.ListOptions) (*atlas.ProcessDisksResponse, error) -} - -// HostDatabases encapsulate the logic to manage different cloud providers. -func (s *Store) HostDatabases(groupID, hostID string, opts *atlas.ListOptions) (*atlas.ProcessDatabasesResponse, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Deployments.ListDatabases(s.ctx, groupID, hostID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// HostDisks encapsulate the logic to manage different cloud providers. -func (s *Store) HostDisks(groupID, hostID string, opts *atlas.ListOptions) (*atlas.ProcessDisksResponse, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Deployments.ListPartitions(s.ctx, groupID, hostID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// Hosts encapsulate the logic to manage different cloud providers. -func (s *Store) Hosts(groupID string, opts *opsmngr.HostListOptions) (*opsmngr.Hosts, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Deployments.ListHosts(s.ctx, groupID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// Host encapsulate the logic to manage different cloud providers. -func (s *Store) Host(groupID, hostID string) (*opsmngr.Host, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Deployments.GetHost(s.ctx, groupID, hostID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// HostByHostname encapsulate the logic to manage different cloud providers. -func (s *Store) HostByHostname(groupID, hostname string, port int) (*opsmngr.Host, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Deployments.GetHostByHostname(s.ctx, groupID, hostname, port) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/diagnose_archive.go b/internal/store/diagnose_archive.go deleted file mode 100644 index a084139c1c..0000000000 --- a/internal/store/diagnose_archive.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - "io" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_diagnose_archive.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store ArchivesDownloader - -type ArchivesDownloader interface { - DownloadArchive(string, *opsmngr.DiagnosticsListOpts, io.Writer) error -} - -// DownloadArchive encapsulate the logic to manage different cloud providers. -func (s *Store) DownloadArchive(groupID string, opts *opsmngr.DiagnosticsListOpts, out io.Writer) error { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - _, err := s.client.(*opsmngr.Client).Diagnostics.Get(s.ctx, groupID, opts, out) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/events.go b/internal/store/events.go deleted file mode 100644 index e58103943e..0000000000 --- a/internal/store/events.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_events.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store OrganizationEventLister,ProjectEventLister,EventLister - -type OrganizationEventLister interface { - OrganizationEvents(string, *atlas.EventListOptions) (*atlas.EventResponse, error) -} - -type ProjectEventLister interface { - ProjectEvents(string, *atlas.EventListOptions) (*atlas.EventResponse, error) -} - -type EventLister interface { - OrganizationEventLister - ProjectEventLister -} - -// ProjectEvents encapsulate the logic to manage different cloud providers. -func (s *Store) ProjectEvents(projectID string, opts *atlas.EventListOptions) (*atlas.EventResponse, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Events.ListProjectEvents(s.ctx, projectID, opts) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Events.ListProjectEvents(s.ctx, projectID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// OrganizationEvents encapsulate the logic to manage different cloud providers. -func (s *Store) OrganizationEvents(orgID string, opts *atlas.EventListOptions) (*atlas.EventResponse, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Events.ListOrganizationEvents(s.ctx, orgID, opts) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Events.ListOrganizationEvents(s.ctx, orgID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/feature_control_policies.go b/internal/store/feature_control_policies.go deleted file mode 100644 index b29cf014ca..0000000000 --- a/internal/store/feature_control_policies.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_feature_control_policy.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store FeatureControlPoliciesLister,FeatureControlPoliciesUpdater - -type FeatureControlPoliciesLister interface { - FeatureControlPolicies(string, *opsmngr.ListOptions) (*opsmngr.FeaturePolicy, error) -} - -type FeatureControlPoliciesUpdater interface { - UpdateFeatureControlPolicy(string, *opsmngr.FeaturePolicy) (*opsmngr.FeaturePolicy, error) -} - -// FeatureControlPolicies encapsulate the logic to manage different cloud providers. -func (s *Store) FeatureControlPolicies(projectID string, opts *opsmngr.ListOptions) (*opsmngr.FeaturePolicy, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).FeatureControlPolicies.List(s.ctx, projectID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateFeatureControlPolicy encapsulate the logic to manage different cloud providers. -func (s *Store) UpdateFeatureControlPolicy(projectID string, policy *opsmngr.FeaturePolicy) (*opsmngr.FeaturePolicy, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).FeatureControlPolicies.Update(s.ctx, projectID, policy) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/file_systems.go b/internal/store/file_systems.go deleted file mode 100644 index ee7e8865d8..0000000000 --- a/internal/store/file_systems.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_backup_file_systems.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store FileSystemsLister,FileSystemsDescriber,FileSystemsDeleter,FileSystemsCreator,FileSystemsUpdater - -type FileSystemsLister interface { - ListFileSystems(*opsmngr.ListOptions) (*opsmngr.FileSystemStoreConfigurations, error) -} - -type FileSystemsDescriber interface { - DescribeFileSystem(string) (*opsmngr.FileSystemStoreConfiguration, error) -} - -type FileSystemsDeleter interface { - DeleteFileSystem(string) error -} - -type FileSystemsCreator interface { - CreateFileSystems(*opsmngr.FileSystemStoreConfiguration) (*opsmngr.FileSystemStoreConfiguration, error) -} - -type FileSystemsUpdater interface { - UpdateFileSystems(*opsmngr.FileSystemStoreConfiguration) (*opsmngr.FileSystemStoreConfiguration, error) -} - -// ListFileSystems encapsulates the logic to manage different cloud providers. -func (s *Store) ListFileSystems(options *opsmngr.ListOptions) (*opsmngr.FileSystemStoreConfigurations, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).FileSystemStoreConfig.List(s.ctx, options) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DescribeFileSystem encapsulates the logic to manage different cloud providers. -func (s *Store) DescribeFileSystem(fileSystemID string) (*opsmngr.FileSystemStoreConfiguration, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).FileSystemStoreConfig.Get(s.ctx, fileSystemID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteFileSystem encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteFileSystem(fileSystemID string) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).FileSystemStoreConfig.Delete(s.ctx, fileSystemID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateFileSystems encapsulates the logic to manage different cloud providers. -func (s *Store) CreateFileSystems(fileSystem *opsmngr.FileSystemStoreConfiguration) (*opsmngr.FileSystemStoreConfiguration, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).FileSystemStoreConfig.Create(s.ctx, fileSystem) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateFileSystems encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateFileSystems(fileSystem *opsmngr.FileSystemStoreConfiguration) (*opsmngr.FileSystemStoreConfiguration, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).FileSystemStoreConfig.Update(s.ctx, fileSystem.ID, fileSystem) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/global_alerts.go b/internal/store/global_alerts.go deleted file mode 100644 index 050a5c5185..0000000000 --- a/internal/store/global_alerts.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_global_alerts.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store GlobalAlertLister - -type GlobalAlertLister interface { - GlobalAlerts(*atlas.AlertsListOptions) (*opsmngr.GlobalAlerts, error) -} - -// GlobalAlerts encapsulate the logic to manage different cloud providers. -func (s *Store) GlobalAlerts(opts *atlas.AlertsListOptions) (*opsmngr.GlobalAlerts, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).GlobalAlerts.List(s.ctx, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/global_api_keys.go b/internal/store/global_api_keys.go deleted file mode 100644 index a27107e443..0000000000 --- a/internal/store/global_api_keys.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_global_api_keys.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store GlobalAPIKeyLister,GlobalAPIKeyDescriber,GlobalAPIKeyUpdater,GlobalAPIKeyCreator,GlobalAPIKeyDeleter - -type GlobalAPIKeyLister interface { - GlobalAPIKeys(*opsmngr.ListOptions) ([]opsmngr.APIKey, error) -} - -type GlobalAPIKeyDescriber interface { - GlobalAPIKey(string) (*opsmngr.APIKey, error) -} - -type GlobalAPIKeyUpdater interface { - UpdateGlobalAPIKey(string, *opsmngr.APIKeyInput) (*opsmngr.APIKey, error) -} - -type GlobalAPIKeyCreator interface { - CreateGlobalAPIKey(*opsmngr.APIKeyInput) (*opsmngr.APIKey, error) -} - -type GlobalAPIKeyDeleter interface { - DeleteGlobalAPIKey(string) error -} - -// GlobalAPIKeys encapsulates the logic to manage different cloud providers. -func (s *Store) GlobalAPIKeys(opts *opsmngr.ListOptions) ([]opsmngr.APIKey, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).GlobalAPIKeys.List(s.ctx, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// GlobalAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) GlobalAPIKey(apiKeyID string) (*opsmngr.APIKey, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).GlobalAPIKeys.Get(s.ctx, apiKeyID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateGlobalAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateGlobalAPIKey(apiKeyID string, input *atlas.APIKeyInput) (*opsmngr.APIKey, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).GlobalAPIKeys.Update(s.ctx, apiKeyID, input) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateGlobalAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) CreateGlobalAPIKey(input *opsmngr.APIKeyInput) (*opsmngr.APIKey, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).GlobalAPIKeys.Create(s.ctx, input) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteGlobalAPIKey encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteGlobalAPIKey(id string) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).GlobalAPIKeys.Delete(s.ctx, id) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/global_api_keys_whitelist.go b/internal/store/global_api_keys_whitelist.go deleted file mode 100644 index 498a514f66..0000000000 --- a/internal/store/global_api_keys_whitelist.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_global_api_keys_access_list.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store GlobalAPIKeyWhitelistLister,GlobalAPIKeyWhitelistDescriber,GlobalAPIKeyWhitelistCreator,GlobalAPIKeyWhitelistDeleter - -type GlobalAPIKeyWhitelistLister interface { - GlobalAPIKeyWhitelists(*atlas.ListOptions) (*opsmngr.GlobalWhitelistAPIKeys, error) -} - -type GlobalAPIKeyWhitelistDescriber interface { - GlobalAPIKeyWhitelist(string) (*opsmngr.GlobalWhitelistAPIKey, error) -} - -type GlobalAPIKeyWhitelistCreator interface { - CreateGlobalAPIKeyWhitelist(*opsmngr.WhitelistAPIKeysReq) (*opsmngr.GlobalWhitelistAPIKey, error) -} - -type GlobalAPIKeyWhitelistDeleter interface { - DeleteGlobalAPIKeyWhitelist(string) error -} - -// GlobalAPIKeyWhitelists encapsulates the logic to manage different cloud providers. -func (s *Store) GlobalAPIKeyWhitelists(opts *atlas.ListOptions) (*opsmngr.GlobalWhitelistAPIKeys, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).GlobalAPIKeysWhitelist.List(s.ctx, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// GlobalAPIKeyWhitelist encapsulates the logic to manage different cloud providers. -func (s *Store) GlobalAPIKeyWhitelist(id string) (*opsmngr.GlobalWhitelistAPIKey, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).GlobalAPIKeysWhitelist.Get(s.ctx, id) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateGlobalAPIKeyWhitelist encapsulates the logic to manage different cloud providers. -func (s *Store) CreateGlobalAPIKeyWhitelist(opts *opsmngr.WhitelistAPIKeysReq) (*opsmngr.GlobalWhitelistAPIKey, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).GlobalAPIKeysWhitelist.Create(s.ctx, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteGlobalAPIKeyWhitelist encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteGlobalAPIKeyWhitelist(id string) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).GlobalAPIKeysWhitelist.Delete(s.ctx, id) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/live_migration_orgs_connection.go b/internal/store/live_migration_orgs_connection.go deleted file mode 100644 index c4e9152b3d..0000000000 --- a/internal/store/live_migration_orgs_connection.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_live_migration_orgs_connection.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store OrganizationsConnector,OrganizationsDescriber - -type OrganizationsConnector interface { - ConnectOrganizations(string, *atlas.LinkToken) (*opsmngr.ConnectionStatus, error) -} - -type OrganizationsDescriber interface { - OrganizationConnectionStatus(string) (*opsmngr.ConnectionStatus, error) -} - -// CreateLinkConnection encapsulate the logic to manage different cloud providers. -func (s *Store) ConnectOrganizations(orgID string, linkToken *atlas.LinkToken) (*opsmngr.ConnectionStatus, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).LiveMigration.ConnectOrganizations(s.ctx, orgID, linkToken) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// OrganizationsLinkStatus encapsulate the logic to manage different cloud providers. -func (s *Store) OrganizationConnectionStatus(orgID string) (*opsmngr.ConnectionStatus, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).LiveMigration.ConnectionStatus(s.ctx, orgID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/measurements.go b/internal/store/measurements.go deleted file mode 100644 index 4dbfb0b898..0000000000 --- a/internal/store/measurements.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_measurements.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store HostMeasurementLister,HostDiskMeasurementsLister,HostDatabaseMeasurementsLister - -type HostMeasurementLister interface { - HostMeasurements(string, string, *atlas.ProcessMeasurementListOptions) (*atlas.ProcessMeasurements, error) -} - -type HostDiskMeasurementsLister interface { - HostDiskMeasurements(string, string, string, *atlas.ProcessMeasurementListOptions) (*atlas.ProcessDiskMeasurements, error) -} - -type HostDatabaseMeasurementsLister interface { - HostDatabaseMeasurements(string, string, string, *atlas.ProcessMeasurementListOptions) (*atlas.ProcessDatabaseMeasurements, error) -} - -// HostMeasurements encapsulate the logic to manage different cloud providers. -func (s *Store) HostMeasurements(groupID, host string, opts *atlas.ProcessMeasurementListOptions) (*atlas.ProcessMeasurements, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Measurements.Host(s.ctx, groupID, host, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// HostDiskMeasurements encapsulates the logic to manage different cloud providers. -func (s *Store) HostDiskMeasurements(groupID, hostID, partitionName string, opts *atlas.ProcessMeasurementListOptions) (*atlas.ProcessDiskMeasurements, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Measurements.Disk(s.ctx, groupID, hostID, partitionName, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// HostDatabaseMeasurements encapsulate the logic to manage different cloud providers. -func (s *Store) HostDatabaseMeasurements(groupID, hostID, databaseName string, opts *atlas.ProcessMeasurementListOptions) (*atlas.ProcessDatabaseMeasurements, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Measurements.Database(s.ctx, groupID, hostID, databaseName, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/mocks/mock_access_role.go b/internal/store/mocks/mock_access_role.go deleted file mode 100644 index 0453931376..0000000000 --- a/internal/store/mocks/mock_access_role.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: CloudProviderAccessRoleLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockCloudProviderAccessRoleLister is a mock of CloudProviderAccessRoleLister interface. -type MockCloudProviderAccessRoleLister struct { - ctrl *gomock.Controller - recorder *MockCloudProviderAccessRoleListerMockRecorder -} - -// MockCloudProviderAccessRoleListerMockRecorder is the mock recorder for MockCloudProviderAccessRoleLister. -type MockCloudProviderAccessRoleListerMockRecorder struct { - mock *MockCloudProviderAccessRoleLister -} - -// NewMockCloudProviderAccessRoleLister creates a new mock instance. -func NewMockCloudProviderAccessRoleLister(ctrl *gomock.Controller) *MockCloudProviderAccessRoleLister { - mock := &MockCloudProviderAccessRoleLister{ctrl: ctrl} - mock.recorder = &MockCloudProviderAccessRoleListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockCloudProviderAccessRoleLister) EXPECT() *MockCloudProviderAccessRoleListerMockRecorder { - return m.recorder -} - -// CloudProviderAccessRoles mocks base method. -func (m *MockCloudProviderAccessRoleLister) CloudProviderAccessRoles(arg0 string) (*admin.CloudProviderAccessRoles, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CloudProviderAccessRoles", arg0) - ret0, _ := ret[0].(*admin.CloudProviderAccessRoles) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CloudProviderAccessRoles indicates an expected call of CloudProviderAccessRoles. -func (mr *MockCloudProviderAccessRoleListerMockRecorder) CloudProviderAccessRoles(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloudProviderAccessRoles", reflect.TypeOf((*MockCloudProviderAccessRoleLister)(nil).CloudProviderAccessRoles), arg0) -} diff --git a/internal/store/mocks/mock_atlas_generic_store.go b/internal/store/mocks/mock_atlas_generic_store.go deleted file mode 100644 index 412382db5a..0000000000 --- a/internal/store/mocks/mock_atlas_generic_store.go +++ /dev/null @@ -1,531 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: OperatorGenericStore) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockOperatorGenericStore is a mock of OperatorGenericStore interface. -type MockOperatorGenericStore struct { - ctrl *gomock.Controller - recorder *MockOperatorGenericStoreMockRecorder -} - -// MockOperatorGenericStoreMockRecorder is the mock recorder for MockOperatorGenericStore. -type MockOperatorGenericStoreMockRecorder struct { - mock *MockOperatorGenericStore -} - -// NewMockOperatorGenericStore creates a new mock instance. -func NewMockOperatorGenericStore(ctrl *gomock.Controller) *MockOperatorGenericStore { - mock := &MockOperatorGenericStore{ctrl: ctrl} - mock.recorder = &MockOperatorGenericStoreMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOperatorGenericStore) EXPECT() *MockOperatorGenericStoreMockRecorder { - return m.recorder -} - -// AlertConfigurations mocks base method. -func (m *MockOperatorGenericStore) AlertConfigurations(arg0 *admin.ListAlertConfigurationsApiParams) (*admin.PaginatedAlertConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AlertConfigurations", arg0) - ret0, _ := ret[0].(*admin.PaginatedAlertConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AlertConfigurations indicates an expected call of AlertConfigurations. -func (mr *MockOperatorGenericStoreMockRecorder) AlertConfigurations(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AlertConfigurations", reflect.TypeOf((*MockOperatorGenericStore)(nil).AlertConfigurations), arg0) -} - -// AssignProjectAPIKey mocks base method. -func (m *MockOperatorGenericStore) AssignProjectAPIKey(arg0, arg1 string, arg2 *admin.UpdateAtlasProjectApiKey) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AssignProjectAPIKey", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// AssignProjectAPIKey indicates an expected call of AssignProjectAPIKey. -func (mr *MockOperatorGenericStoreMockRecorder) AssignProjectAPIKey(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AssignProjectAPIKey", reflect.TypeOf((*MockOperatorGenericStore)(nil).AssignProjectAPIKey), arg0, arg1, arg2) -} - -// AtlasCluster mocks base method. -func (m *MockOperatorGenericStore) AtlasCluster(arg0, arg1 string) (*admin.AdvancedClusterDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AtlasCluster", arg0, arg1) - ret0, _ := ret[0].(*admin.AdvancedClusterDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AtlasCluster indicates an expected call of AtlasCluster. -func (mr *MockOperatorGenericStoreMockRecorder) AtlasCluster(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AtlasCluster", reflect.TypeOf((*MockOperatorGenericStore)(nil).AtlasCluster), arg0, arg1) -} - -// AtlasClusterConfigurationOptions mocks base method. -func (m *MockOperatorGenericStore) AtlasClusterConfigurationOptions(arg0, arg1 string) (*admin.ClusterDescriptionProcessArgs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AtlasClusterConfigurationOptions", arg0, arg1) - ret0, _ := ret[0].(*admin.ClusterDescriptionProcessArgs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AtlasClusterConfigurationOptions indicates an expected call of AtlasClusterConfigurationOptions. -func (mr *MockOperatorGenericStoreMockRecorder) AtlasClusterConfigurationOptions(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AtlasClusterConfigurationOptions", reflect.TypeOf((*MockOperatorGenericStore)(nil).AtlasClusterConfigurationOptions), arg0, arg1) -} - -// Auditing mocks base method. -func (m *MockOperatorGenericStore) Auditing(arg0 string) (*admin.AuditLog, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Auditing", arg0) - ret0, _ := ret[0].(*admin.AuditLog) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Auditing indicates an expected call of Auditing. -func (mr *MockOperatorGenericStoreMockRecorder) Auditing(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Auditing", reflect.TypeOf((*MockOperatorGenericStore)(nil).Auditing), arg0) -} - -// CloudProviderAccessRoles mocks base method. -func (m *MockOperatorGenericStore) CloudProviderAccessRoles(arg0 string) (*admin.CloudProviderAccessRoles, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CloudProviderAccessRoles", arg0) - ret0, _ := ret[0].(*admin.CloudProviderAccessRoles) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CloudProviderAccessRoles indicates an expected call of CloudProviderAccessRoles. -func (mr *MockOperatorGenericStoreMockRecorder) CloudProviderAccessRoles(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloudProviderAccessRoles", reflect.TypeOf((*MockOperatorGenericStore)(nil).CloudProviderAccessRoles), arg0) -} - -// CreateOrganizationAPIKey mocks base method. -func (m *MockOperatorGenericStore) CreateOrganizationAPIKey(arg0 string, arg1 *admin.CreateAtlasOrganizationApiKey) (*admin.ApiKeyUserDetails, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrganizationAPIKey", arg0, arg1) - ret0, _ := ret[0].(*admin.ApiKeyUserDetails) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateOrganizationAPIKey indicates an expected call of CreateOrganizationAPIKey. -func (mr *MockOperatorGenericStoreMockRecorder) CreateOrganizationAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrganizationAPIKey", reflect.TypeOf((*MockOperatorGenericStore)(nil).CreateOrganizationAPIKey), arg0, arg1) -} - -// CreateProject mocks base method. -func (m *MockOperatorGenericStore) CreateProject(arg0 *admin.CreateProjectApiParams) (*admin.Group, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateProject", arg0) - ret0, _ := ret[0].(*admin.Group) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateProject indicates an expected call of CreateProject. -func (mr *MockOperatorGenericStoreMockRecorder) CreateProject(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateProject", reflect.TypeOf((*MockOperatorGenericStore)(nil).CreateProject), arg0) -} - -// CreateProjectAPIKey mocks base method. -func (m *MockOperatorGenericStore) CreateProjectAPIKey(arg0 string, arg1 *admin.CreateAtlasProjectApiKey) (*admin.ApiKeyUserDetails, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateProjectAPIKey", arg0, arg1) - ret0, _ := ret[0].(*admin.ApiKeyUserDetails) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateProjectAPIKey indicates an expected call of CreateProjectAPIKey. -func (mr *MockOperatorGenericStoreMockRecorder) CreateProjectAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateProjectAPIKey", reflect.TypeOf((*MockOperatorGenericStore)(nil).CreateProjectAPIKey), arg0, arg1) -} - -// DataFederation mocks base method. -func (m *MockOperatorGenericStore) DataFederation(arg0, arg1 string) (*admin.DataLakeTenant, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DataFederation", arg0, arg1) - ret0, _ := ret[0].(*admin.DataLakeTenant) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DataFederation indicates an expected call of DataFederation. -func (mr *MockOperatorGenericStoreMockRecorder) DataFederation(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DataFederation", reflect.TypeOf((*MockOperatorGenericStore)(nil).DataFederation), arg0, arg1) -} - -// DataFederationList mocks base method. -func (m *MockOperatorGenericStore) DataFederationList(arg0, arg1 string) ([]admin.DataLakeTenant, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DataFederationList", arg0, arg1) - ret0, _ := ret[0].([]admin.DataLakeTenant) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DataFederationList indicates an expected call of DataFederationList. -func (mr *MockOperatorGenericStoreMockRecorder) DataFederationList(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DataFederationList", reflect.TypeOf((*MockOperatorGenericStore)(nil).DataFederationList), arg0, arg1) -} - -// DatabaseRoles mocks base method. -func (m *MockOperatorGenericStore) DatabaseRoles(arg0 string) ([]admin.UserCustomDBRole, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DatabaseRoles", arg0) - ret0, _ := ret[0].([]admin.UserCustomDBRole) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DatabaseRoles indicates an expected call of DatabaseRoles. -func (mr *MockOperatorGenericStoreMockRecorder) DatabaseRoles(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DatabaseRoles", reflect.TypeOf((*MockOperatorGenericStore)(nil).DatabaseRoles), arg0) -} - -// DatabaseUsers mocks base method. -func (m *MockOperatorGenericStore) DatabaseUsers(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedApiAtlasDatabaseUser, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DatabaseUsers", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedApiAtlasDatabaseUser) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DatabaseUsers indicates an expected call of DatabaseUsers. -func (mr *MockOperatorGenericStoreMockRecorder) DatabaseUsers(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DatabaseUsers", reflect.TypeOf((*MockOperatorGenericStore)(nil).DatabaseUsers), arg0, arg1) -} - -// DescribeSchedule mocks base method. -func (m *MockOperatorGenericStore) DescribeSchedule(arg0, arg1 string) (*admin.DiskBackupSnapshotSchedule, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DescribeSchedule", arg0, arg1) - ret0, _ := ret[0].(*admin.DiskBackupSnapshotSchedule) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DescribeSchedule indicates an expected call of DescribeSchedule. -func (mr *MockOperatorGenericStoreMockRecorder) DescribeSchedule(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeSchedule", reflect.TypeOf((*MockOperatorGenericStore)(nil).DescribeSchedule), arg0, arg1) -} - -// EncryptionAtRest mocks base method. -func (m *MockOperatorGenericStore) EncryptionAtRest(arg0 string) (*admin.EncryptionAtRest, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "EncryptionAtRest", arg0) - ret0, _ := ret[0].(*admin.EncryptionAtRest) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// EncryptionAtRest indicates an expected call of EncryptionAtRest. -func (mr *MockOperatorGenericStoreMockRecorder) EncryptionAtRest(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EncryptionAtRest", reflect.TypeOf((*MockOperatorGenericStore)(nil).EncryptionAtRest), arg0) -} - -// GetServerlessInstance mocks base method. -func (m *MockOperatorGenericStore) GetServerlessInstance(arg0, arg1 string) (*admin.ServerlessInstanceDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetServerlessInstance", arg0, arg1) - ret0, _ := ret[0].(*admin.ServerlessInstanceDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetServerlessInstance indicates an expected call of GetServerlessInstance. -func (mr *MockOperatorGenericStoreMockRecorder) GetServerlessInstance(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServerlessInstance", reflect.TypeOf((*MockOperatorGenericStore)(nil).GetServerlessInstance), arg0, arg1) -} - -// GlobalCluster mocks base method. -func (m *MockOperatorGenericStore) GlobalCluster(arg0, arg1 string) (*admin.GeoSharding, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GlobalCluster", arg0, arg1) - ret0, _ := ret[0].(*admin.GeoSharding) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GlobalCluster indicates an expected call of GlobalCluster. -func (mr *MockOperatorGenericStoreMockRecorder) GlobalCluster(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GlobalCluster", reflect.TypeOf((*MockOperatorGenericStore)(nil).GlobalCluster), arg0, arg1) -} - -// Integrations mocks base method. -func (m *MockOperatorGenericStore) Integrations(arg0 string) (*admin.PaginatedIntegration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Integrations", arg0) - ret0, _ := ret[0].(*admin.PaginatedIntegration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Integrations indicates an expected call of Integrations. -func (mr *MockOperatorGenericStoreMockRecorder) Integrations(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Integrations", reflect.TypeOf((*MockOperatorGenericStore)(nil).Integrations), arg0) -} - -// MaintenanceWindow mocks base method. -func (m *MockOperatorGenericStore) MaintenanceWindow(arg0 string) (*admin.GroupMaintenanceWindow, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MaintenanceWindow", arg0) - ret0, _ := ret[0].(*admin.GroupMaintenanceWindow) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// MaintenanceWindow indicates an expected call of MaintenanceWindow. -func (mr *MockOperatorGenericStoreMockRecorder) MaintenanceWindow(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MaintenanceWindow", reflect.TypeOf((*MockOperatorGenericStore)(nil).MaintenanceWindow), arg0) -} - -// PeeringConnections mocks base method. -func (m *MockOperatorGenericStore) PeeringConnections(arg0 string, arg1 *mongodbatlas.ContainersListOptions) ([]admin.BaseNetworkPeeringConnectionSettings, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PeeringConnections", arg0, arg1) - ret0, _ := ret[0].([]admin.BaseNetworkPeeringConnectionSettings) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PeeringConnections indicates an expected call of PeeringConnections. -func (mr *MockOperatorGenericStoreMockRecorder) PeeringConnections(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PeeringConnections", reflect.TypeOf((*MockOperatorGenericStore)(nil).PeeringConnections), arg0, arg1) -} - -// PrivateEndpoints mocks base method. -func (m *MockOperatorGenericStore) PrivateEndpoints(arg0, arg1 string) ([]admin.EndpointService, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PrivateEndpoints", arg0, arg1) - ret0, _ := ret[0].([]admin.EndpointService) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PrivateEndpoints indicates an expected call of PrivateEndpoints. -func (mr *MockOperatorGenericStoreMockRecorder) PrivateEndpoints(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrivateEndpoints", reflect.TypeOf((*MockOperatorGenericStore)(nil).PrivateEndpoints), arg0, arg1) -} - -// Project mocks base method. -func (m *MockOperatorGenericStore) Project(arg0 string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Project", arg0) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Project indicates an expected call of Project. -func (mr *MockOperatorGenericStoreMockRecorder) Project(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Project", reflect.TypeOf((*MockOperatorGenericStore)(nil).Project), arg0) -} - -// ProjectByName mocks base method. -func (m *MockOperatorGenericStore) ProjectByName(arg0 string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectByName", arg0) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectByName indicates an expected call of ProjectByName. -func (mr *MockOperatorGenericStoreMockRecorder) ProjectByName(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectByName", reflect.TypeOf((*MockOperatorGenericStore)(nil).ProjectByName), arg0) -} - -// ProjectClusters mocks base method. -func (m *MockOperatorGenericStore) ProjectClusters(arg0 string, arg1 *atlas.ListOptions) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectClusters", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectClusters indicates an expected call of ProjectClusters. -func (mr *MockOperatorGenericStoreMockRecorder) ProjectClusters(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectClusters", reflect.TypeOf((*MockOperatorGenericStore)(nil).ProjectClusters), arg0, arg1) -} - -// ProjectIPAccessLists mocks base method. -func (m *MockOperatorGenericStore) ProjectIPAccessLists(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedNetworkAccess, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectIPAccessLists", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedNetworkAccess) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectIPAccessLists indicates an expected call of ProjectIPAccessLists. -func (mr *MockOperatorGenericStoreMockRecorder) ProjectIPAccessLists(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectIPAccessLists", reflect.TypeOf((*MockOperatorGenericStore)(nil).ProjectIPAccessLists), arg0, arg1) -} - -// ProjectSettings mocks base method. -func (m *MockOperatorGenericStore) ProjectSettings(arg0 string) (*admin.GroupSettings, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectSettings", arg0) - ret0, _ := ret[0].(*admin.GroupSettings) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectSettings indicates an expected call of ProjectSettings. -func (mr *MockOperatorGenericStoreMockRecorder) ProjectSettings(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectSettings", reflect.TypeOf((*MockOperatorGenericStore)(nil).ProjectSettings), arg0) -} - -// ProjectTeams mocks base method. -func (m *MockOperatorGenericStore) ProjectTeams(arg0 string) (*admin.PaginatedTeamRole, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectTeams", arg0) - ret0, _ := ret[0].(*admin.PaginatedTeamRole) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectTeams indicates an expected call of ProjectTeams. -func (mr *MockOperatorGenericStoreMockRecorder) ProjectTeams(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectTeams", reflect.TypeOf((*MockOperatorGenericStore)(nil).ProjectTeams), arg0) -} - -// Projects mocks base method. -func (m *MockOperatorGenericStore) Projects(arg0 *mongodbatlas.ListOptions) (*admin.PaginatedAtlasGroup, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Projects", arg0) - ret0, _ := ret[0].(*admin.PaginatedAtlasGroup) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Projects indicates an expected call of Projects. -func (mr *MockOperatorGenericStoreMockRecorder) Projects(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Projects", reflect.TypeOf((*MockOperatorGenericStore)(nil).Projects), arg0) -} - -// ServerlessInstances mocks base method. -func (m *MockOperatorGenericStore) ServerlessInstances(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedServerlessInstanceDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServerlessInstances", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedServerlessInstanceDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ServerlessInstances indicates an expected call of ServerlessInstances. -func (mr *MockOperatorGenericStoreMockRecorder) ServerlessInstances(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServerlessInstances", reflect.TypeOf((*MockOperatorGenericStore)(nil).ServerlessInstances), arg0, arg1) -} - -// ServerlessPrivateEndpoints mocks base method. -func (m *MockOperatorGenericStore) ServerlessPrivateEndpoints(arg0, arg1 string) ([]admin.ServerlessTenantEndpoint, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServerlessPrivateEndpoints", arg0, arg1) - ret0, _ := ret[0].([]admin.ServerlessTenantEndpoint) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ServerlessPrivateEndpoints indicates an expected call of ServerlessPrivateEndpoints. -func (mr *MockOperatorGenericStoreMockRecorder) ServerlessPrivateEndpoints(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServerlessPrivateEndpoints", reflect.TypeOf((*MockOperatorGenericStore)(nil).ServerlessPrivateEndpoints), arg0, arg1) -} - -// TeamByID mocks base method. -func (m *MockOperatorGenericStore) TeamByID(arg0, arg1 string) (*admin.TeamResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamByID", arg0, arg1) - ret0, _ := ret[0].(*admin.TeamResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamByID indicates an expected call of TeamByID. -func (mr *MockOperatorGenericStoreMockRecorder) TeamByID(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamByID", reflect.TypeOf((*MockOperatorGenericStore)(nil).TeamByID), arg0, arg1) -} - -// TeamByName mocks base method. -func (m *MockOperatorGenericStore) TeamByName(arg0, arg1 string) (*admin.TeamResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamByName", arg0, arg1) - ret0, _ := ret[0].(*admin.TeamResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamByName indicates an expected call of TeamByName. -func (mr *MockOperatorGenericStoreMockRecorder) TeamByName(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamByName", reflect.TypeOf((*MockOperatorGenericStore)(nil).TeamByName), arg0, arg1) -} - -// TeamUsers mocks base method. -func (m *MockOperatorGenericStore) TeamUsers(arg0, arg1 string) (*admin.PaginatedApiAppUser, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamUsers", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedApiAppUser) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamUsers indicates an expected call of TeamUsers. -func (mr *MockOperatorGenericStoreMockRecorder) TeamUsers(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamUsers", reflect.TypeOf((*MockOperatorGenericStore)(nil).TeamUsers), arg0, arg1) -} diff --git a/internal/store/mocks/mock_atlas_operator_cluster_store.go b/internal/store/mocks/mock_atlas_operator_cluster_store.go deleted file mode 100644 index 3bef9b5d2d..0000000000 --- a/internal/store/mocks/mock_atlas_operator_cluster_store.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: OperatorClusterStore) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockOperatorClusterStore is a mock of OperatorClusterStore interface. -type MockOperatorClusterStore struct { - ctrl *gomock.Controller - recorder *MockOperatorClusterStoreMockRecorder -} - -// MockOperatorClusterStoreMockRecorder is the mock recorder for MockOperatorClusterStore. -type MockOperatorClusterStoreMockRecorder struct { - mock *MockOperatorClusterStore -} - -// NewMockOperatorClusterStore creates a new mock instance. -func NewMockOperatorClusterStore(ctrl *gomock.Controller) *MockOperatorClusterStore { - mock := &MockOperatorClusterStore{ctrl: ctrl} - mock.recorder = &MockOperatorClusterStoreMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOperatorClusterStore) EXPECT() *MockOperatorClusterStoreMockRecorder { - return m.recorder -} - -// AtlasCluster mocks base method. -func (m *MockOperatorClusterStore) AtlasCluster(arg0, arg1 string) (*admin.AdvancedClusterDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AtlasCluster", arg0, arg1) - ret0, _ := ret[0].(*admin.AdvancedClusterDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AtlasCluster indicates an expected call of AtlasCluster. -func (mr *MockOperatorClusterStoreMockRecorder) AtlasCluster(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AtlasCluster", reflect.TypeOf((*MockOperatorClusterStore)(nil).AtlasCluster), arg0, arg1) -} - -// AtlasClusterConfigurationOptions mocks base method. -func (m *MockOperatorClusterStore) AtlasClusterConfigurationOptions(arg0, arg1 string) (*admin.ClusterDescriptionProcessArgs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AtlasClusterConfigurationOptions", arg0, arg1) - ret0, _ := ret[0].(*admin.ClusterDescriptionProcessArgs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AtlasClusterConfigurationOptions indicates an expected call of AtlasClusterConfigurationOptions. -func (mr *MockOperatorClusterStoreMockRecorder) AtlasClusterConfigurationOptions(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AtlasClusterConfigurationOptions", reflect.TypeOf((*MockOperatorClusterStore)(nil).AtlasClusterConfigurationOptions), arg0, arg1) -} - -// DescribeSchedule mocks base method. -func (m *MockOperatorClusterStore) DescribeSchedule(arg0, arg1 string) (*admin.DiskBackupSnapshotSchedule, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DescribeSchedule", arg0, arg1) - ret0, _ := ret[0].(*admin.DiskBackupSnapshotSchedule) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DescribeSchedule indicates an expected call of DescribeSchedule. -func (mr *MockOperatorClusterStoreMockRecorder) DescribeSchedule(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeSchedule", reflect.TypeOf((*MockOperatorClusterStore)(nil).DescribeSchedule), arg0, arg1) -} - -// GetServerlessInstance mocks base method. -func (m *MockOperatorClusterStore) GetServerlessInstance(arg0, arg1 string) (*admin.ServerlessInstanceDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetServerlessInstance", arg0, arg1) - ret0, _ := ret[0].(*admin.ServerlessInstanceDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetServerlessInstance indicates an expected call of GetServerlessInstance. -func (mr *MockOperatorClusterStoreMockRecorder) GetServerlessInstance(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServerlessInstance", reflect.TypeOf((*MockOperatorClusterStore)(nil).GetServerlessInstance), arg0, arg1) -} - -// GlobalCluster mocks base method. -func (m *MockOperatorClusterStore) GlobalCluster(arg0, arg1 string) (*admin.GeoSharding, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GlobalCluster", arg0, arg1) - ret0, _ := ret[0].(*admin.GeoSharding) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GlobalCluster indicates an expected call of GlobalCluster. -func (mr *MockOperatorClusterStoreMockRecorder) GlobalCluster(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GlobalCluster", reflect.TypeOf((*MockOperatorClusterStore)(nil).GlobalCluster), arg0, arg1) -} - -// ProjectClusters mocks base method. -func (m *MockOperatorClusterStore) ProjectClusters(arg0 string, arg1 *atlas.ListOptions) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectClusters", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectClusters indicates an expected call of ProjectClusters. -func (mr *MockOperatorClusterStoreMockRecorder) ProjectClusters(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectClusters", reflect.TypeOf((*MockOperatorClusterStore)(nil).ProjectClusters), arg0, arg1) -} - -// ServerlessInstances mocks base method. -func (m *MockOperatorClusterStore) ServerlessInstances(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedServerlessInstanceDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServerlessInstances", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedServerlessInstanceDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ServerlessInstances indicates an expected call of ServerlessInstances. -func (mr *MockOperatorClusterStoreMockRecorder) ServerlessInstances(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServerlessInstances", reflect.TypeOf((*MockOperatorClusterStore)(nil).ServerlessInstances), arg0, arg1) -} - -// ServerlessPrivateEndpoints mocks base method. -func (m *MockOperatorClusterStore) ServerlessPrivateEndpoints(arg0, arg1 string) ([]admin.ServerlessTenantEndpoint, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServerlessPrivateEndpoints", arg0, arg1) - ret0, _ := ret[0].([]admin.ServerlessTenantEndpoint) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ServerlessPrivateEndpoints indicates an expected call of ServerlessPrivateEndpoints. -func (mr *MockOperatorClusterStoreMockRecorder) ServerlessPrivateEndpoints(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServerlessPrivateEndpoints", reflect.TypeOf((*MockOperatorClusterStore)(nil).ServerlessPrivateEndpoints), arg0, arg1) -} diff --git a/internal/store/mocks/mock_atlas_operator_db_users_store.go b/internal/store/mocks/mock_atlas_operator_db_users_store.go deleted file mode 100644 index 4fb326b5ac..0000000000 --- a/internal/store/mocks/mock_atlas_operator_db_users_store.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: OperatorDBUsersStore) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockOperatorDBUsersStore is a mock of OperatorDBUsersStore interface. -type MockOperatorDBUsersStore struct { - ctrl *gomock.Controller - recorder *MockOperatorDBUsersStoreMockRecorder -} - -// MockOperatorDBUsersStoreMockRecorder is the mock recorder for MockOperatorDBUsersStore. -type MockOperatorDBUsersStoreMockRecorder struct { - mock *MockOperatorDBUsersStore -} - -// NewMockOperatorDBUsersStore creates a new mock instance. -func NewMockOperatorDBUsersStore(ctrl *gomock.Controller) *MockOperatorDBUsersStore { - mock := &MockOperatorDBUsersStore{ctrl: ctrl} - mock.recorder = &MockOperatorDBUsersStoreMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOperatorDBUsersStore) EXPECT() *MockOperatorDBUsersStoreMockRecorder { - return m.recorder -} - -// DatabaseUsers mocks base method. -func (m *MockOperatorDBUsersStore) DatabaseUsers(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedApiAtlasDatabaseUser, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DatabaseUsers", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedApiAtlasDatabaseUser) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DatabaseUsers indicates an expected call of DatabaseUsers. -func (mr *MockOperatorDBUsersStoreMockRecorder) DatabaseUsers(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DatabaseUsers", reflect.TypeOf((*MockOperatorDBUsersStore)(nil).DatabaseUsers), arg0, arg1) -} diff --git a/internal/store/mocks/mock_atlas_operator_org_store.go b/internal/store/mocks/mock_atlas_operator_org_store.go deleted file mode 100644 index 48cb2799fa..0000000000 --- a/internal/store/mocks/mock_atlas_operator_org_store.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: OperatorOrgStore) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockOperatorOrgStore is a mock of OperatorOrgStore interface. -type MockOperatorOrgStore struct { - ctrl *gomock.Controller - recorder *MockOperatorOrgStoreMockRecorder -} - -// MockOperatorOrgStoreMockRecorder is the mock recorder for MockOperatorOrgStore. -type MockOperatorOrgStoreMockRecorder struct { - mock *MockOperatorOrgStore -} - -// NewMockOperatorOrgStore creates a new mock instance. -func NewMockOperatorOrgStore(ctrl *gomock.Controller) *MockOperatorOrgStore { - mock := &MockOperatorOrgStore{ctrl: ctrl} - mock.recorder = &MockOperatorOrgStoreMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOperatorOrgStore) EXPECT() *MockOperatorOrgStoreMockRecorder { - return m.recorder -} - -// AssignProjectAPIKey mocks base method. -func (m *MockOperatorOrgStore) AssignProjectAPIKey(arg0, arg1 string, arg2 *admin.UpdateAtlasProjectApiKey) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AssignProjectAPIKey", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// AssignProjectAPIKey indicates an expected call of AssignProjectAPIKey. -func (mr *MockOperatorOrgStoreMockRecorder) AssignProjectAPIKey(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AssignProjectAPIKey", reflect.TypeOf((*MockOperatorOrgStore)(nil).AssignProjectAPIKey), arg0, arg1, arg2) -} - -// CreateOrganizationAPIKey mocks base method. -func (m *MockOperatorOrgStore) CreateOrganizationAPIKey(arg0 string, arg1 *admin.CreateAtlasOrganizationApiKey) (*admin.ApiKeyUserDetails, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrganizationAPIKey", arg0, arg1) - ret0, _ := ret[0].(*admin.ApiKeyUserDetails) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateOrganizationAPIKey indicates an expected call of CreateOrganizationAPIKey. -func (mr *MockOperatorOrgStoreMockRecorder) CreateOrganizationAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrganizationAPIKey", reflect.TypeOf((*MockOperatorOrgStore)(nil).CreateOrganizationAPIKey), arg0, arg1) -} diff --git a/internal/store/mocks/mock_atlas_operator_project_store.go b/internal/store/mocks/mock_atlas_operator_project_store.go deleted file mode 100644 index 434b0a2ae6..0000000000 --- a/internal/store/mocks/mock_atlas_operator_project_store.go +++ /dev/null @@ -1,337 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: OperatorProjectStore) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockOperatorProjectStore is a mock of OperatorProjectStore interface. -type MockOperatorProjectStore struct { - ctrl *gomock.Controller - recorder *MockOperatorProjectStoreMockRecorder -} - -// MockOperatorProjectStoreMockRecorder is the mock recorder for MockOperatorProjectStore. -type MockOperatorProjectStoreMockRecorder struct { - mock *MockOperatorProjectStore -} - -// NewMockOperatorProjectStore creates a new mock instance. -func NewMockOperatorProjectStore(ctrl *gomock.Controller) *MockOperatorProjectStore { - mock := &MockOperatorProjectStore{ctrl: ctrl} - mock.recorder = &MockOperatorProjectStoreMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOperatorProjectStore) EXPECT() *MockOperatorProjectStoreMockRecorder { - return m.recorder -} - -// AlertConfigurations mocks base method. -func (m *MockOperatorProjectStore) AlertConfigurations(arg0 *admin.ListAlertConfigurationsApiParams) (*admin.PaginatedAlertConfig, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AlertConfigurations", arg0) - ret0, _ := ret[0].(*admin.PaginatedAlertConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AlertConfigurations indicates an expected call of AlertConfigurations. -func (mr *MockOperatorProjectStoreMockRecorder) AlertConfigurations(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AlertConfigurations", reflect.TypeOf((*MockOperatorProjectStore)(nil).AlertConfigurations), arg0) -} - -// Auditing mocks base method. -func (m *MockOperatorProjectStore) Auditing(arg0 string) (*admin.AuditLog, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Auditing", arg0) - ret0, _ := ret[0].(*admin.AuditLog) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Auditing indicates an expected call of Auditing. -func (mr *MockOperatorProjectStoreMockRecorder) Auditing(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Auditing", reflect.TypeOf((*MockOperatorProjectStore)(nil).Auditing), arg0) -} - -// CloudProviderAccessRoles mocks base method. -func (m *MockOperatorProjectStore) CloudProviderAccessRoles(arg0 string) (*admin.CloudProviderAccessRoles, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CloudProviderAccessRoles", arg0) - ret0, _ := ret[0].(*admin.CloudProviderAccessRoles) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CloudProviderAccessRoles indicates an expected call of CloudProviderAccessRoles. -func (mr *MockOperatorProjectStoreMockRecorder) CloudProviderAccessRoles(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloudProviderAccessRoles", reflect.TypeOf((*MockOperatorProjectStore)(nil).CloudProviderAccessRoles), arg0) -} - -// CreateProject mocks base method. -func (m *MockOperatorProjectStore) CreateProject(arg0 *admin.CreateProjectApiParams) (*admin.Group, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateProject", arg0) - ret0, _ := ret[0].(*admin.Group) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateProject indicates an expected call of CreateProject. -func (mr *MockOperatorProjectStoreMockRecorder) CreateProject(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateProject", reflect.TypeOf((*MockOperatorProjectStore)(nil).CreateProject), arg0) -} - -// CreateProjectAPIKey mocks base method. -func (m *MockOperatorProjectStore) CreateProjectAPIKey(arg0 string, arg1 *admin.CreateAtlasProjectApiKey) (*admin.ApiKeyUserDetails, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateProjectAPIKey", arg0, arg1) - ret0, _ := ret[0].(*admin.ApiKeyUserDetails) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateProjectAPIKey indicates an expected call of CreateProjectAPIKey. -func (mr *MockOperatorProjectStoreMockRecorder) CreateProjectAPIKey(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateProjectAPIKey", reflect.TypeOf((*MockOperatorProjectStore)(nil).CreateProjectAPIKey), arg0, arg1) -} - -// DatabaseRoles mocks base method. -func (m *MockOperatorProjectStore) DatabaseRoles(arg0 string) ([]admin.UserCustomDBRole, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DatabaseRoles", arg0) - ret0, _ := ret[0].([]admin.UserCustomDBRole) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DatabaseRoles indicates an expected call of DatabaseRoles. -func (mr *MockOperatorProjectStoreMockRecorder) DatabaseRoles(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DatabaseRoles", reflect.TypeOf((*MockOperatorProjectStore)(nil).DatabaseRoles), arg0) -} - -// EncryptionAtRest mocks base method. -func (m *MockOperatorProjectStore) EncryptionAtRest(arg0 string) (*admin.EncryptionAtRest, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "EncryptionAtRest", arg0) - ret0, _ := ret[0].(*admin.EncryptionAtRest) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// EncryptionAtRest indicates an expected call of EncryptionAtRest. -func (mr *MockOperatorProjectStoreMockRecorder) EncryptionAtRest(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EncryptionAtRest", reflect.TypeOf((*MockOperatorProjectStore)(nil).EncryptionAtRest), arg0) -} - -// Integrations mocks base method. -func (m *MockOperatorProjectStore) Integrations(arg0 string) (*admin.PaginatedIntegration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Integrations", arg0) - ret0, _ := ret[0].(*admin.PaginatedIntegration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Integrations indicates an expected call of Integrations. -func (mr *MockOperatorProjectStoreMockRecorder) Integrations(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Integrations", reflect.TypeOf((*MockOperatorProjectStore)(nil).Integrations), arg0) -} - -// MaintenanceWindow mocks base method. -func (m *MockOperatorProjectStore) MaintenanceWindow(arg0 string) (*admin.GroupMaintenanceWindow, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MaintenanceWindow", arg0) - ret0, _ := ret[0].(*admin.GroupMaintenanceWindow) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// MaintenanceWindow indicates an expected call of MaintenanceWindow. -func (mr *MockOperatorProjectStoreMockRecorder) MaintenanceWindow(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MaintenanceWindow", reflect.TypeOf((*MockOperatorProjectStore)(nil).MaintenanceWindow), arg0) -} - -// PeeringConnections mocks base method. -func (m *MockOperatorProjectStore) PeeringConnections(arg0 string, arg1 *mongodbatlas.ContainersListOptions) ([]admin.BaseNetworkPeeringConnectionSettings, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PeeringConnections", arg0, arg1) - ret0, _ := ret[0].([]admin.BaseNetworkPeeringConnectionSettings) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PeeringConnections indicates an expected call of PeeringConnections. -func (mr *MockOperatorProjectStoreMockRecorder) PeeringConnections(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PeeringConnections", reflect.TypeOf((*MockOperatorProjectStore)(nil).PeeringConnections), arg0, arg1) -} - -// PrivateEndpoints mocks base method. -func (m *MockOperatorProjectStore) PrivateEndpoints(arg0, arg1 string) ([]admin.EndpointService, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PrivateEndpoints", arg0, arg1) - ret0, _ := ret[0].([]admin.EndpointService) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PrivateEndpoints indicates an expected call of PrivateEndpoints. -func (mr *MockOperatorProjectStoreMockRecorder) PrivateEndpoints(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrivateEndpoints", reflect.TypeOf((*MockOperatorProjectStore)(nil).PrivateEndpoints), arg0, arg1) -} - -// Project mocks base method. -func (m *MockOperatorProjectStore) Project(arg0 string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Project", arg0) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Project indicates an expected call of Project. -func (mr *MockOperatorProjectStoreMockRecorder) Project(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Project", reflect.TypeOf((*MockOperatorProjectStore)(nil).Project), arg0) -} - -// ProjectByName mocks base method. -func (m *MockOperatorProjectStore) ProjectByName(arg0 string) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectByName", arg0) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectByName indicates an expected call of ProjectByName. -func (mr *MockOperatorProjectStoreMockRecorder) ProjectByName(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectByName", reflect.TypeOf((*MockOperatorProjectStore)(nil).ProjectByName), arg0) -} - -// ProjectIPAccessLists mocks base method. -func (m *MockOperatorProjectStore) ProjectIPAccessLists(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedNetworkAccess, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectIPAccessLists", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedNetworkAccess) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectIPAccessLists indicates an expected call of ProjectIPAccessLists. -func (mr *MockOperatorProjectStoreMockRecorder) ProjectIPAccessLists(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectIPAccessLists", reflect.TypeOf((*MockOperatorProjectStore)(nil).ProjectIPAccessLists), arg0, arg1) -} - -// ProjectSettings mocks base method. -func (m *MockOperatorProjectStore) ProjectSettings(arg0 string) (*admin.GroupSettings, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectSettings", arg0) - ret0, _ := ret[0].(*admin.GroupSettings) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectSettings indicates an expected call of ProjectSettings. -func (mr *MockOperatorProjectStoreMockRecorder) ProjectSettings(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectSettings", reflect.TypeOf((*MockOperatorProjectStore)(nil).ProjectSettings), arg0) -} - -// ProjectTeams mocks base method. -func (m *MockOperatorProjectStore) ProjectTeams(arg0 string) (*admin.PaginatedTeamRole, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectTeams", arg0) - ret0, _ := ret[0].(*admin.PaginatedTeamRole) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectTeams indicates an expected call of ProjectTeams. -func (mr *MockOperatorProjectStoreMockRecorder) ProjectTeams(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectTeams", reflect.TypeOf((*MockOperatorProjectStore)(nil).ProjectTeams), arg0) -} - -// Projects mocks base method. -func (m *MockOperatorProjectStore) Projects(arg0 *mongodbatlas.ListOptions) (*admin.PaginatedAtlasGroup, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Projects", arg0) - ret0, _ := ret[0].(*admin.PaginatedAtlasGroup) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Projects indicates an expected call of Projects. -func (mr *MockOperatorProjectStoreMockRecorder) Projects(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Projects", reflect.TypeOf((*MockOperatorProjectStore)(nil).Projects), arg0) -} - -// TeamByID mocks base method. -func (m *MockOperatorProjectStore) TeamByID(arg0, arg1 string) (*admin.TeamResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamByID", arg0, arg1) - ret0, _ := ret[0].(*admin.TeamResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamByID indicates an expected call of TeamByID. -func (mr *MockOperatorProjectStoreMockRecorder) TeamByID(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamByID", reflect.TypeOf((*MockOperatorProjectStore)(nil).TeamByID), arg0, arg1) -} - -// TeamByName mocks base method. -func (m *MockOperatorProjectStore) TeamByName(arg0, arg1 string) (*admin.TeamResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamByName", arg0, arg1) - ret0, _ := ret[0].(*admin.TeamResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamByName indicates an expected call of TeamByName. -func (mr *MockOperatorProjectStoreMockRecorder) TeamByName(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamByName", reflect.TypeOf((*MockOperatorProjectStore)(nil).TeamByName), arg0, arg1) -} - -// TeamUsers mocks base method. -func (m *MockOperatorProjectStore) TeamUsers(arg0, arg1 string) (*admin.PaginatedApiAppUser, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TeamUsers", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedApiAppUser) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TeamUsers indicates an expected call of TeamUsers. -func (mr *MockOperatorProjectStoreMockRecorder) TeamUsers(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeamUsers", reflect.TypeOf((*MockOperatorProjectStore)(nil).TeamUsers), arg0, arg1) -} diff --git a/internal/store/mocks/mock_auditing.go b/internal/store/mocks/mock_auditing.go deleted file mode 100644 index 100e9b01de..0000000000 --- a/internal/store/mocks/mock_auditing.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: AuditingDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockAuditingDescriber is a mock of AuditingDescriber interface. -type MockAuditingDescriber struct { - ctrl *gomock.Controller - recorder *MockAuditingDescriberMockRecorder -} - -// MockAuditingDescriberMockRecorder is the mock recorder for MockAuditingDescriber. -type MockAuditingDescriberMockRecorder struct { - mock *MockAuditingDescriber -} - -// NewMockAuditingDescriber creates a new mock instance. -func NewMockAuditingDescriber(ctrl *gomock.Controller) *MockAuditingDescriber { - mock := &MockAuditingDescriber{ctrl: ctrl} - mock.recorder = &MockAuditingDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAuditingDescriber) EXPECT() *MockAuditingDescriberMockRecorder { - return m.recorder -} - -// Auditing mocks base method. -func (m *MockAuditingDescriber) Auditing(arg0 string) (*admin.AuditLog, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Auditing", arg0) - ret0, _ := ret[0].(*admin.AuditLog) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Auditing indicates an expected call of Auditing. -func (mr *MockAuditingDescriberMockRecorder) Auditing(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Auditing", reflect.TypeOf((*MockAuditingDescriber)(nil).Auditing), arg0) -} diff --git a/internal/store/mocks/mock_cloud_provider_backup.go b/internal/store/mocks/mock_cloud_provider_backup.go deleted file mode 100644 index e5dc359eeb..0000000000 --- a/internal/store/mocks/mock_cloud_provider_backup.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: ScheduleDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockScheduleDescriber is a mock of ScheduleDescriber interface. -type MockScheduleDescriber struct { - ctrl *gomock.Controller - recorder *MockScheduleDescriberMockRecorder -} - -// MockScheduleDescriberMockRecorder is the mock recorder for MockScheduleDescriber. -type MockScheduleDescriberMockRecorder struct { - mock *MockScheduleDescriber -} - -// NewMockScheduleDescriber creates a new mock instance. -func NewMockScheduleDescriber(ctrl *gomock.Controller) *MockScheduleDescriber { - mock := &MockScheduleDescriber{ctrl: ctrl} - mock.recorder = &MockScheduleDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockScheduleDescriber) EXPECT() *MockScheduleDescriberMockRecorder { - return m.recorder -} - -// DescribeSchedule mocks base method. -func (m *MockScheduleDescriber) DescribeSchedule(arg0, arg1 string) (*admin.DiskBackupSnapshotSchedule, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DescribeSchedule", arg0, arg1) - ret0, _ := ret[0].(*admin.DiskBackupSnapshotSchedule) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DescribeSchedule indicates an expected call of DescribeSchedule. -func (mr *MockScheduleDescriberMockRecorder) DescribeSchedule(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeSchedule", reflect.TypeOf((*MockScheduleDescriber)(nil).DescribeSchedule), arg0, arg1) -} diff --git a/internal/store/mocks/mock_clusters.go b/internal/store/mocks/mock_clusters.go deleted file mode 100644 index ff5d4a76af..0000000000 --- a/internal/store/mocks/mock_clusters.go +++ /dev/null @@ -1,127 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: ClusterLister,ClusterDescriber,ClusterConfigurationOptionsDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockClusterLister is a mock of ClusterLister interface. -type MockClusterLister struct { - ctrl *gomock.Controller - recorder *MockClusterListerMockRecorder -} - -// MockClusterListerMockRecorder is the mock recorder for MockClusterLister. -type MockClusterListerMockRecorder struct { - mock *MockClusterLister -} - -// NewMockClusterLister creates a new mock instance. -func NewMockClusterLister(ctrl *gomock.Controller) *MockClusterLister { - mock := &MockClusterLister{ctrl: ctrl} - mock.recorder = &MockClusterListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockClusterLister) EXPECT() *MockClusterListerMockRecorder { - return m.recorder -} - -// ProjectClusters mocks base method. -func (m *MockClusterLister) ProjectClusters(arg0 string, arg1 *atlas.ListOptions) (interface{}, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectClusters", arg0, arg1) - ret0, _ := ret[0].(interface{}) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectClusters indicates an expected call of ProjectClusters. -func (mr *MockClusterListerMockRecorder) ProjectClusters(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectClusters", reflect.TypeOf((*MockClusterLister)(nil).ProjectClusters), arg0, arg1) -} - -// MockClusterDescriber is a mock of ClusterDescriber interface. -type MockClusterDescriber struct { - ctrl *gomock.Controller - recorder *MockClusterDescriberMockRecorder -} - -// MockClusterDescriberMockRecorder is the mock recorder for MockClusterDescriber. -type MockClusterDescriberMockRecorder struct { - mock *MockClusterDescriber -} - -// NewMockClusterDescriber creates a new mock instance. -func NewMockClusterDescriber(ctrl *gomock.Controller) *MockClusterDescriber { - mock := &MockClusterDescriber{ctrl: ctrl} - mock.recorder = &MockClusterDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockClusterDescriber) EXPECT() *MockClusterDescriberMockRecorder { - return m.recorder -} - -// AtlasCluster mocks base method. -func (m *MockClusterDescriber) AtlasCluster(arg0, arg1 string) (*admin.AdvancedClusterDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AtlasCluster", arg0, arg1) - ret0, _ := ret[0].(*admin.AdvancedClusterDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AtlasCluster indicates an expected call of AtlasCluster. -func (mr *MockClusterDescriberMockRecorder) AtlasCluster(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AtlasCluster", reflect.TypeOf((*MockClusterDescriber)(nil).AtlasCluster), arg0, arg1) -} - -// MockClusterConfigurationOptionsDescriber is a mock of ClusterConfigurationOptionsDescriber interface. -type MockClusterConfigurationOptionsDescriber struct { - ctrl *gomock.Controller - recorder *MockClusterConfigurationOptionsDescriberMockRecorder -} - -// MockClusterConfigurationOptionsDescriberMockRecorder is the mock recorder for MockClusterConfigurationOptionsDescriber. -type MockClusterConfigurationOptionsDescriberMockRecorder struct { - mock *MockClusterConfigurationOptionsDescriber -} - -// NewMockClusterConfigurationOptionsDescriber creates a new mock instance. -func NewMockClusterConfigurationOptionsDescriber(ctrl *gomock.Controller) *MockClusterConfigurationOptionsDescriber { - mock := &MockClusterConfigurationOptionsDescriber{ctrl: ctrl} - mock.recorder = &MockClusterConfigurationOptionsDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockClusterConfigurationOptionsDescriber) EXPECT() *MockClusterConfigurationOptionsDescriberMockRecorder { - return m.recorder -} - -// AtlasClusterConfigurationOptions mocks base method. -func (m *MockClusterConfigurationOptionsDescriber) AtlasClusterConfigurationOptions(arg0, arg1 string) (*admin.ClusterDescriptionProcessArgs, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AtlasClusterConfigurationOptions", arg0, arg1) - ret0, _ := ret[0].(*admin.ClusterDescriptionProcessArgs) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AtlasClusterConfigurationOptions indicates an expected call of AtlasClusterConfigurationOptions. -func (mr *MockClusterConfigurationOptionsDescriberMockRecorder) AtlasClusterConfigurationOptions(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AtlasClusterConfigurationOptions", reflect.TypeOf((*MockClusterConfigurationOptionsDescriber)(nil).AtlasClusterConfigurationOptions), arg0, arg1) -} diff --git a/internal/store/mocks/mock_database_roles.go b/internal/store/mocks/mock_database_roles.go deleted file mode 100644 index 9b06c23828..0000000000 --- a/internal/store/mocks/mock_database_roles.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: DatabaseRoleLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockDatabaseRoleLister is a mock of DatabaseRoleLister interface. -type MockDatabaseRoleLister struct { - ctrl *gomock.Controller - recorder *MockDatabaseRoleListerMockRecorder -} - -// MockDatabaseRoleListerMockRecorder is the mock recorder for MockDatabaseRoleLister. -type MockDatabaseRoleListerMockRecorder struct { - mock *MockDatabaseRoleLister -} - -// NewMockDatabaseRoleLister creates a new mock instance. -func NewMockDatabaseRoleLister(ctrl *gomock.Controller) *MockDatabaseRoleLister { - mock := &MockDatabaseRoleLister{ctrl: ctrl} - mock.recorder = &MockDatabaseRoleListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDatabaseRoleLister) EXPECT() *MockDatabaseRoleListerMockRecorder { - return m.recorder -} - -// DatabaseRoles mocks base method. -func (m *MockDatabaseRoleLister) DatabaseRoles(arg0 string) ([]admin.UserCustomDBRole, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DatabaseRoles", arg0) - ret0, _ := ret[0].([]admin.UserCustomDBRole) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DatabaseRoles indicates an expected call of DatabaseRoles. -func (mr *MockDatabaseRoleListerMockRecorder) DatabaseRoles(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DatabaseRoles", reflect.TypeOf((*MockDatabaseRoleLister)(nil).DatabaseRoles), arg0) -} diff --git a/internal/store/mocks/mock_database_users.go b/internal/store/mocks/mock_database_users.go deleted file mode 100644 index 9e6ed3f187..0000000000 --- a/internal/store/mocks/mock_database_users.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: DatabaseUserLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockDatabaseUserLister is a mock of DatabaseUserLister interface. -type MockDatabaseUserLister struct { - ctrl *gomock.Controller - recorder *MockDatabaseUserListerMockRecorder -} - -// MockDatabaseUserListerMockRecorder is the mock recorder for MockDatabaseUserLister. -type MockDatabaseUserListerMockRecorder struct { - mock *MockDatabaseUserLister -} - -// NewMockDatabaseUserLister creates a new mock instance. -func NewMockDatabaseUserLister(ctrl *gomock.Controller) *MockDatabaseUserLister { - mock := &MockDatabaseUserLister{ctrl: ctrl} - mock.recorder = &MockDatabaseUserListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDatabaseUserLister) EXPECT() *MockDatabaseUserListerMockRecorder { - return m.recorder -} - -// DatabaseUsers mocks base method. -func (m *MockDatabaseUserLister) DatabaseUsers(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedApiAtlasDatabaseUser, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DatabaseUsers", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedApiAtlasDatabaseUser) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DatabaseUsers indicates an expected call of DatabaseUsers. -func (mr *MockDatabaseUserListerMockRecorder) DatabaseUsers(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DatabaseUsers", reflect.TypeOf((*MockDatabaseUserLister)(nil).DatabaseUsers), arg0, arg1) -} diff --git a/internal/store/mocks/mock_encryption_at_rest.go b/internal/store/mocks/mock_encryption_at_rest.go deleted file mode 100644 index 8b7bd60bde..0000000000 --- a/internal/store/mocks/mock_encryption_at_rest.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: EncryptionAtRestDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockEncryptionAtRestDescriber is a mock of EncryptionAtRestDescriber interface. -type MockEncryptionAtRestDescriber struct { - ctrl *gomock.Controller - recorder *MockEncryptionAtRestDescriberMockRecorder -} - -// MockEncryptionAtRestDescriberMockRecorder is the mock recorder for MockEncryptionAtRestDescriber. -type MockEncryptionAtRestDescriberMockRecorder struct { - mock *MockEncryptionAtRestDescriber -} - -// NewMockEncryptionAtRestDescriber creates a new mock instance. -func NewMockEncryptionAtRestDescriber(ctrl *gomock.Controller) *MockEncryptionAtRestDescriber { - mock := &MockEncryptionAtRestDescriber{ctrl: ctrl} - mock.recorder = &MockEncryptionAtRestDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockEncryptionAtRestDescriber) EXPECT() *MockEncryptionAtRestDescriberMockRecorder { - return m.recorder -} - -// EncryptionAtRest mocks base method. -func (m *MockEncryptionAtRestDescriber) EncryptionAtRest(arg0 string) (*admin.EncryptionAtRest, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "EncryptionAtRest", arg0) - ret0, _ := ret[0].(*admin.EncryptionAtRest) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// EncryptionAtRest indicates an expected call of EncryptionAtRest. -func (mr *MockEncryptionAtRestDescriberMockRecorder) EncryptionAtRest(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EncryptionAtRest", reflect.TypeOf((*MockEncryptionAtRestDescriber)(nil).EncryptionAtRest), arg0) -} diff --git a/internal/store/mocks/mock_global_cluster.go b/internal/store/mocks/mock_global_cluster.go deleted file mode 100644 index 09323a24cb..0000000000 --- a/internal/store/mocks/mock_global_cluster.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: GlobalClusterDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockGlobalClusterDescriber is a mock of GlobalClusterDescriber interface. -type MockGlobalClusterDescriber struct { - ctrl *gomock.Controller - recorder *MockGlobalClusterDescriberMockRecorder -} - -// MockGlobalClusterDescriberMockRecorder is the mock recorder for MockGlobalClusterDescriber. -type MockGlobalClusterDescriberMockRecorder struct { - mock *MockGlobalClusterDescriber -} - -// NewMockGlobalClusterDescriber creates a new mock instance. -func NewMockGlobalClusterDescriber(ctrl *gomock.Controller) *MockGlobalClusterDescriber { - mock := &MockGlobalClusterDescriber{ctrl: ctrl} - mock.recorder = &MockGlobalClusterDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGlobalClusterDescriber) EXPECT() *MockGlobalClusterDescriberMockRecorder { - return m.recorder -} - -// GlobalCluster mocks base method. -func (m *MockGlobalClusterDescriber) GlobalCluster(arg0, arg1 string) (*admin.GeoSharding, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GlobalCluster", arg0, arg1) - ret0, _ := ret[0].(*admin.GeoSharding) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GlobalCluster indicates an expected call of GlobalCluster. -func (mr *MockGlobalClusterDescriberMockRecorder) GlobalCluster(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GlobalCluster", reflect.TypeOf((*MockGlobalClusterDescriber)(nil).GlobalCluster), arg0, arg1) -} diff --git a/internal/store/mocks/mock_integrations.go b/internal/store/mocks/mock_integrations.go deleted file mode 100644 index 598241edab..0000000000 --- a/internal/store/mocks/mock_integrations.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: IntegrationLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockIntegrationLister is a mock of IntegrationLister interface. -type MockIntegrationLister struct { - ctrl *gomock.Controller - recorder *MockIntegrationListerMockRecorder -} - -// MockIntegrationListerMockRecorder is the mock recorder for MockIntegrationLister. -type MockIntegrationListerMockRecorder struct { - mock *MockIntegrationLister -} - -// NewMockIntegrationLister creates a new mock instance. -func NewMockIntegrationLister(ctrl *gomock.Controller) *MockIntegrationLister { - mock := &MockIntegrationLister{ctrl: ctrl} - mock.recorder = &MockIntegrationListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIntegrationLister) EXPECT() *MockIntegrationListerMockRecorder { - return m.recorder -} - -// Integrations mocks base method. -func (m *MockIntegrationLister) Integrations(arg0 string) (*admin.PaginatedIntegration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Integrations", arg0) - ret0, _ := ret[0].(*admin.PaginatedIntegration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Integrations indicates an expected call of Integrations. -func (mr *MockIntegrationListerMockRecorder) Integrations(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Integrations", reflect.TypeOf((*MockIntegrationLister)(nil).Integrations), arg0) -} diff --git a/internal/store/mocks/mock_maintenance.go b/internal/store/mocks/mock_maintenance.go deleted file mode 100644 index 7ca31364cb..0000000000 --- a/internal/store/mocks/mock_maintenance.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: MaintenanceWindowDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockMaintenanceWindowDescriber is a mock of MaintenanceWindowDescriber interface. -type MockMaintenanceWindowDescriber struct { - ctrl *gomock.Controller - recorder *MockMaintenanceWindowDescriberMockRecorder -} - -// MockMaintenanceWindowDescriberMockRecorder is the mock recorder for MockMaintenanceWindowDescriber. -type MockMaintenanceWindowDescriberMockRecorder struct { - mock *MockMaintenanceWindowDescriber -} - -// NewMockMaintenanceWindowDescriber creates a new mock instance. -func NewMockMaintenanceWindowDescriber(ctrl *gomock.Controller) *MockMaintenanceWindowDescriber { - mock := &MockMaintenanceWindowDescriber{ctrl: ctrl} - mock.recorder = &MockMaintenanceWindowDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockMaintenanceWindowDescriber) EXPECT() *MockMaintenanceWindowDescriberMockRecorder { - return m.recorder -} - -// MaintenanceWindow mocks base method. -func (m *MockMaintenanceWindowDescriber) MaintenanceWindow(arg0 string) (*admin.GroupMaintenanceWindow, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MaintenanceWindow", arg0) - ret0, _ := ret[0].(*admin.GroupMaintenanceWindow) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// MaintenanceWindow indicates an expected call of MaintenanceWindow. -func (mr *MockMaintenanceWindowDescriberMockRecorder) MaintenanceWindow(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MaintenanceWindow", reflect.TypeOf((*MockMaintenanceWindowDescriber)(nil).MaintenanceWindow), arg0) -} diff --git a/internal/store/mocks/mock_peering_connections.go b/internal/store/mocks/mock_peering_connections.go deleted file mode 100644 index e1e87dbe32..0000000000 --- a/internal/store/mocks/mock_peering_connections.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: PeeringConnectionLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" - mongodbatlas "go.mongodb.org/atlas/mongodbatlas" -) - -// MockPeeringConnectionLister is a mock of PeeringConnectionLister interface. -type MockPeeringConnectionLister struct { - ctrl *gomock.Controller - recorder *MockPeeringConnectionListerMockRecorder -} - -// MockPeeringConnectionListerMockRecorder is the mock recorder for MockPeeringConnectionLister. -type MockPeeringConnectionListerMockRecorder struct { - mock *MockPeeringConnectionLister -} - -// NewMockPeeringConnectionLister creates a new mock instance. -func NewMockPeeringConnectionLister(ctrl *gomock.Controller) *MockPeeringConnectionLister { - mock := &MockPeeringConnectionLister{ctrl: ctrl} - mock.recorder = &MockPeeringConnectionListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockPeeringConnectionLister) EXPECT() *MockPeeringConnectionListerMockRecorder { - return m.recorder -} - -// PeeringConnections mocks base method. -func (m *MockPeeringConnectionLister) PeeringConnections(arg0 string, arg1 *mongodbatlas.ContainersListOptions) ([]admin.BaseNetworkPeeringConnectionSettings, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PeeringConnections", arg0, arg1) - ret0, _ := ret[0].([]admin.BaseNetworkPeeringConnectionSettings) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PeeringConnections indicates an expected call of PeeringConnections. -func (mr *MockPeeringConnectionListerMockRecorder) PeeringConnections(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PeeringConnections", reflect.TypeOf((*MockPeeringConnectionLister)(nil).PeeringConnections), arg0, arg1) -} diff --git a/internal/store/mocks/mock_private_endpoints.go b/internal/store/mocks/mock_private_endpoints.go deleted file mode 100644 index a287720f41..0000000000 --- a/internal/store/mocks/mock_private_endpoints.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: PrivateEndpointLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockPrivateEndpointLister is a mock of PrivateEndpointLister interface. -type MockPrivateEndpointLister struct { - ctrl *gomock.Controller - recorder *MockPrivateEndpointListerMockRecorder -} - -// MockPrivateEndpointListerMockRecorder is the mock recorder for MockPrivateEndpointLister. -type MockPrivateEndpointListerMockRecorder struct { - mock *MockPrivateEndpointLister -} - -// NewMockPrivateEndpointLister creates a new mock instance. -func NewMockPrivateEndpointLister(ctrl *gomock.Controller) *MockPrivateEndpointLister { - mock := &MockPrivateEndpointLister{ctrl: ctrl} - mock.recorder = &MockPrivateEndpointListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockPrivateEndpointLister) EXPECT() *MockPrivateEndpointListerMockRecorder { - return m.recorder -} - -// PrivateEndpoints mocks base method. -func (m *MockPrivateEndpointLister) PrivateEndpoints(arg0, arg1 string) ([]admin.EndpointService, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PrivateEndpoints", arg0, arg1) - ret0, _ := ret[0].([]admin.EndpointService) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PrivateEndpoints indicates an expected call of PrivateEndpoints. -func (mr *MockPrivateEndpointListerMockRecorder) PrivateEndpoints(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrivateEndpoints", reflect.TypeOf((*MockPrivateEndpointLister)(nil).PrivateEndpoints), arg0, arg1) -} diff --git a/internal/store/mocks/mock_project_ip_access_lists.go b/internal/store/mocks/mock_project_ip_access_lists.go deleted file mode 100644 index 4c63ebc841..0000000000 --- a/internal/store/mocks/mock_project_ip_access_lists.go +++ /dev/null @@ -1,51 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: ProjectIPAccessListLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockProjectIPAccessListLister is a mock of ProjectIPAccessListLister interface. -type MockProjectIPAccessListLister struct { - ctrl *gomock.Controller - recorder *MockProjectIPAccessListListerMockRecorder -} - -// MockProjectIPAccessListListerMockRecorder is the mock recorder for MockProjectIPAccessListLister. -type MockProjectIPAccessListListerMockRecorder struct { - mock *MockProjectIPAccessListLister -} - -// NewMockProjectIPAccessListLister creates a new mock instance. -func NewMockProjectIPAccessListLister(ctrl *gomock.Controller) *MockProjectIPAccessListLister { - mock := &MockProjectIPAccessListLister{ctrl: ctrl} - mock.recorder = &MockProjectIPAccessListListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectIPAccessListLister) EXPECT() *MockProjectIPAccessListListerMockRecorder { - return m.recorder -} - -// ProjectIPAccessLists mocks base method. -func (m *MockProjectIPAccessListLister) ProjectIPAccessLists(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedNetworkAccess, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectIPAccessLists", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedNetworkAccess) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectIPAccessLists indicates an expected call of ProjectIPAccessLists. -func (mr *MockProjectIPAccessListListerMockRecorder) ProjectIPAccessLists(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectIPAccessLists", reflect.TypeOf((*MockProjectIPAccessListLister)(nil).ProjectIPAccessLists), arg0, arg1) -} diff --git a/internal/store/mocks/mock_project_settings.go b/internal/store/mocks/mock_project_settings.go deleted file mode 100644 index 686a3c88ad..0000000000 --- a/internal/store/mocks/mock_project_settings.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: ProjectSettingsDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockProjectSettingsDescriber is a mock of ProjectSettingsDescriber interface. -type MockProjectSettingsDescriber struct { - ctrl *gomock.Controller - recorder *MockProjectSettingsDescriberMockRecorder -} - -// MockProjectSettingsDescriberMockRecorder is the mock recorder for MockProjectSettingsDescriber. -type MockProjectSettingsDescriberMockRecorder struct { - mock *MockProjectSettingsDescriber -} - -// NewMockProjectSettingsDescriber creates a new mock instance. -func NewMockProjectSettingsDescriber(ctrl *gomock.Controller) *MockProjectSettingsDescriber { - mock := &MockProjectSettingsDescriber{ctrl: ctrl} - mock.recorder = &MockProjectSettingsDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockProjectSettingsDescriber) EXPECT() *MockProjectSettingsDescriberMockRecorder { - return m.recorder -} - -// ProjectSettings mocks base method. -func (m *MockProjectSettingsDescriber) ProjectSettings(arg0 string) (*admin.GroupSettings, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ProjectSettings", arg0) - ret0, _ := ret[0].(*admin.GroupSettings) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ProjectSettings indicates an expected call of ProjectSettings. -func (mr *MockProjectSettingsDescriberMockRecorder) ProjectSettings(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectSettings", reflect.TypeOf((*MockProjectSettingsDescriber)(nil).ProjectSettings), arg0) -} diff --git a/internal/store/mocks/mock_serverless_instances.go b/internal/store/mocks/mock_serverless_instances.go deleted file mode 100644 index 41376aeab1..0000000000 --- a/internal/store/mocks/mock_serverless_instances.go +++ /dev/null @@ -1,89 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: ServerlessInstanceLister,ServerlessInstanceDescriber) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - atlas "github.com/mongodb/mongodb-atlas-cli/internal/store/atlas" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockServerlessInstanceLister is a mock of ServerlessInstanceLister interface. -type MockServerlessInstanceLister struct { - ctrl *gomock.Controller - recorder *MockServerlessInstanceListerMockRecorder -} - -// MockServerlessInstanceListerMockRecorder is the mock recorder for MockServerlessInstanceLister. -type MockServerlessInstanceListerMockRecorder struct { - mock *MockServerlessInstanceLister -} - -// NewMockServerlessInstanceLister creates a new mock instance. -func NewMockServerlessInstanceLister(ctrl *gomock.Controller) *MockServerlessInstanceLister { - mock := &MockServerlessInstanceLister{ctrl: ctrl} - mock.recorder = &MockServerlessInstanceListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockServerlessInstanceLister) EXPECT() *MockServerlessInstanceListerMockRecorder { - return m.recorder -} - -// ServerlessInstances mocks base method. -func (m *MockServerlessInstanceLister) ServerlessInstances(arg0 string, arg1 *atlas.ListOptions) (*admin.PaginatedServerlessInstanceDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServerlessInstances", arg0, arg1) - ret0, _ := ret[0].(*admin.PaginatedServerlessInstanceDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ServerlessInstances indicates an expected call of ServerlessInstances. -func (mr *MockServerlessInstanceListerMockRecorder) ServerlessInstances(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServerlessInstances", reflect.TypeOf((*MockServerlessInstanceLister)(nil).ServerlessInstances), arg0, arg1) -} - -// MockServerlessInstanceDescriber is a mock of ServerlessInstanceDescriber interface. -type MockServerlessInstanceDescriber struct { - ctrl *gomock.Controller - recorder *MockServerlessInstanceDescriberMockRecorder -} - -// MockServerlessInstanceDescriberMockRecorder is the mock recorder for MockServerlessInstanceDescriber. -type MockServerlessInstanceDescriberMockRecorder struct { - mock *MockServerlessInstanceDescriber -} - -// NewMockServerlessInstanceDescriber creates a new mock instance. -func NewMockServerlessInstanceDescriber(ctrl *gomock.Controller) *MockServerlessInstanceDescriber { - mock := &MockServerlessInstanceDescriber{ctrl: ctrl} - mock.recorder = &MockServerlessInstanceDescriberMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockServerlessInstanceDescriber) EXPECT() *MockServerlessInstanceDescriberMockRecorder { - return m.recorder -} - -// GetServerlessInstance mocks base method. -func (m *MockServerlessInstanceDescriber) GetServerlessInstance(arg0, arg1 string) (*admin.ServerlessInstanceDescription, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetServerlessInstance", arg0, arg1) - ret0, _ := ret[0].(*admin.ServerlessInstanceDescription) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetServerlessInstance indicates an expected call of GetServerlessInstance. -func (mr *MockServerlessInstanceDescriberMockRecorder) GetServerlessInstance(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServerlessInstance", reflect.TypeOf((*MockServerlessInstanceDescriber)(nil).GetServerlessInstance), arg0, arg1) -} diff --git a/internal/store/mocks/mock_serverless_private_endpoints.go b/internal/store/mocks/mock_serverless_private_endpoints.go deleted file mode 100644 index 730beacff9..0000000000 --- a/internal/store/mocks/mock_serverless_private_endpoints.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/mongodb/mongodb-atlas-cli/internal/store/atlas (interfaces: ServerlessPrivateEndpointsLister) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - admin "go.mongodb.org/atlas-sdk/v20231115007/admin" -) - -// MockServerlessPrivateEndpointsLister is a mock of ServerlessPrivateEndpointsLister interface. -type MockServerlessPrivateEndpointsLister struct { - ctrl *gomock.Controller - recorder *MockServerlessPrivateEndpointsListerMockRecorder -} - -// MockServerlessPrivateEndpointsListerMockRecorder is the mock recorder for MockServerlessPrivateEndpointsLister. -type MockServerlessPrivateEndpointsListerMockRecorder struct { - mock *MockServerlessPrivateEndpointsLister -} - -// NewMockServerlessPrivateEndpointsLister creates a new mock instance. -func NewMockServerlessPrivateEndpointsLister(ctrl *gomock.Controller) *MockServerlessPrivateEndpointsLister { - mock := &MockServerlessPrivateEndpointsLister{ctrl: ctrl} - mock.recorder = &MockServerlessPrivateEndpointsListerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockServerlessPrivateEndpointsLister) EXPECT() *MockServerlessPrivateEndpointsListerMockRecorder { - return m.recorder -} - -// ServerlessPrivateEndpoints mocks base method. -func (m *MockServerlessPrivateEndpointsLister) ServerlessPrivateEndpoints(arg0, arg1 string) ([]admin.ServerlessTenantEndpoint, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ServerlessPrivateEndpoints", arg0, arg1) - ret0, _ := ret[0].([]admin.ServerlessTenantEndpoint) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ServerlessPrivateEndpoints indicates an expected call of ServerlessPrivateEndpoints. -func (mr *MockServerlessPrivateEndpointsListerMockRecorder) ServerlessPrivateEndpoints(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServerlessPrivateEndpoints", reflect.TypeOf((*MockServerlessPrivateEndpointsLister)(nil).ServerlessPrivateEndpoints), arg0, arg1) -} diff --git a/internal/store/monitoring.go b/internal/store/monitoring.go deleted file mode 100644 index 59c7b34566..0000000000 --- a/internal/store/monitoring.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_monitoring.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store MonitoringStarter,MonitoringStopper - -type MonitoringStarter interface { - StartMonitoring(string, *opsmngr.Host) (*opsmngr.Host, error) -} - -type MonitoringStopper interface { - StopMonitoring(string, string) error -} - -// StartMonitoring encapsulates the logic to manage different cloud providers. -func (s *Store) StartMonitoring(groupID string, host *opsmngr.Host) (*opsmngr.Host, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Deployments.StartMonitoring(s.ctx, groupID, host) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// StopMonitoring encapsulates the logic to manage different cloud providers. -func (s *Store) StopMonitoring(groupID, hostID string) error { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - _, err := s.client.(*opsmngr.Client).Deployments.StopMonitoring(s.ctx, groupID, hostID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/oplog.go b/internal/store/oplog.go deleted file mode 100644 index d51eb4aa6b..0000000000 --- a/internal/store/oplog.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_backup_oplogs.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store OplogsLister,OplogsDescriber,OplogsCreator,OplogsUpdater,OplogsDeleter - -type OplogsLister interface { - ListOplogs(*opsmngr.ListOptions) (*opsmngr.BackupStores, error) -} - -type OplogsDescriber interface { - GetOplog(string) (*opsmngr.BackupStore, error) -} - -type OplogsCreator interface { - CreateOplog(*opsmngr.BackupStore) (*opsmngr.BackupStore, error) -} - -type OplogsUpdater interface { - UpdateOplog(string, *opsmngr.BackupStore) (*opsmngr.BackupStore, error) -} - -type OplogsDeleter interface { - DeleteOplog(string) error -} - -// ListOplogs encapsulates the logic to manage different cloud providers. -func (s *Store) ListOplogs(options *opsmngr.ListOptions) (*opsmngr.BackupStores, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).OplogStoreConfig.List(s.ctx, options) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// GetOplog encapsulates the logic to manage different cloud providers. -func (s *Store) GetOplog(oplogID string) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).OplogStoreConfig.Get(s.ctx, oplogID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateOplog encapsulates the logic to manage different cloud providers. -func (s *Store) CreateOplog(oplog *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).OplogStoreConfig.Create(s.ctx, oplog) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateOplog encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateOplog(oplogID string, oplog *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).OplogStoreConfig.Update(s.ctx, oplogID, oplog) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteOplog encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteOplog(oplogID string) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).OplogStoreConfig.Delete(s.ctx, oplogID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/organization_invitations.go b/internal/store/organization_invitations.go deleted file mode 100644 index 2bc16ea50f..0000000000 --- a/internal/store/organization_invitations.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlasv2 "go.mongodb.org/atlas-sdk/v20231115007/admin" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_organization_invitations.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store OrganizationInvitationLister,OrganizationInvitationDeleter,OrganizationInvitationDescriber,OrganizationInvitationUpdater,OrganizationInviter - -type OrganizationInvitationLister interface { - OrganizationInvitations(string, *atlas.InvitationOptions) (interface{}, error) -} - -type OrganizationInvitationDescriber interface { - OrganizationInvitation(string, string) (interface{}, error) -} - -type OrganizationInviter interface { - InviteUser(string, *atlas.Invitation) (interface{}, error) -} - -type OrganizationInvitationDeleter interface { - DeleteInvitation(string, string) error -} - -type OrganizationInvitationUpdater interface { - UpdateOrganizationInvitation(string, string, *atlas.Invitation) (interface{}, error) -} - -// OrganizationInvitations encapsulate the logic to manage different cloud providers. -func (s *Store) OrganizationInvitations(orgID string, opts *atlas.InvitationOptions) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - res := s.clientv2.OrganizationsApi.ListOrganizationInvitations(s.ctx, orgID) - if opts != nil { - res = res.Username(opts.Username) - } - result, _, err := res.Execute() - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Organizations.Invitations(s.ctx, orgID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// OrganizationInvitation encapsulate the logic to manage different cloud providers. -func (s *Store) OrganizationInvitation(orgID, invitationID string) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.clientv2.OrganizationsApi.GetOrganizationInvitation(s.ctx, orgID, invitationID).Execute() - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Organizations.Invitation(s.ctx, orgID, invitationID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteInvitation encapsulate the logic to manage different cloud providers. -func (s *Store) DeleteInvitation(orgID, invitationID string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).Organizations.DeleteInvitation(s.ctx, orgID, invitationID) - return err - case config.CloudManagerService, config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).Organizations.DeleteInvitation(s.ctx, orgID, invitationID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateOrganizationInvitation encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateOrganizationInvitation(orgID, invitationID string, invitation *atlas.Invitation) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - if invitationID != "" { - invitationRequest := atlasv2.OrganizationInvitationUpdateRequest{ - Roles: &invitation.Roles, - TeamIds: &invitation.TeamIDs, - } - - result, _, err := s.clientv2.OrganizationsApi.UpdateOrganizationInvitationById(s.ctx, orgID, invitationID, &invitationRequest).Execute() - return result, err - } - invitationRequest := mapInvitation(invitation) - result, _, err := s.clientv2.OrganizationsApi.UpdateOrganizationInvitation(s.ctx, orgID, &invitationRequest).Execute() - - return result, err - - case config.CloudManagerService, config.OpsManagerService: - if invitationID != "" { - result, _, err := s.client.(*opsmngr.Client).Organizations.UpdateInvitationByID(s.ctx, orgID, invitationID, invitation) - return result, err - } - result, _, err := s.client.(*opsmngr.Client).Organizations.UpdateInvitation(s.ctx, orgID, invitation) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// InviteUser encapsulates the logic to manage different cloud providers. -func (s *Store) InviteUser(orgID string, invitation *atlas.Invitation) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - invitationRequest := mapInvitation(invitation) - result, _, err := s.clientv2.OrganizationsApi.CreateOrganizationInvitation(s.ctx, orgID, &invitationRequest).Execute() - - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Organizations.InviteUser(s.ctx, orgID, invitation) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -func mapInvitation(invitation *atlas.Invitation) atlasv2.OrganizationInvitationRequest { - return atlasv2.OrganizationInvitationRequest{ - Roles: &invitation.Roles, - TeamIds: &invitation.TeamIDs, - Username: &invitation.Username, - } -} diff --git a/internal/store/owners.go b/internal/store/owners.go deleted file mode 100644 index 4cf6cbc13f..0000000000 --- a/internal/store/owners.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_owners.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store OwnerCreator - -type OwnerCreator interface { - CreateOwner(*opsmngr.User, []string) (*opsmngr.CreateUserResponse, error) -} - -// CreateOwner encapsulate the logic to manage different cloud providers. -func (s *Store) CreateOwner(u *opsmngr.User, ips []string) (*opsmngr.CreateUserResponse, error) { - switch s.service { - case config.OpsManagerService: - var opts *opsmngr.WhitelistOpts - if len(ips) > 0 { - opts = &opsmngr.WhitelistOpts{Whitelist: ips} - } - - result, _, err := s.client.(*opsmngr.Client).UnauthUsers.CreateFirstUser(s.ctx, u, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/performance_advisor.go b/internal/store/performance_advisor.go deleted file mode 100644 index b22e5facbc..0000000000 --- a/internal/store/performance_advisor.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_performance_advisor.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store PerformanceAdvisorNamespacesLister,PerformanceAdvisorSlowQueriesLister,PerformanceAdvisorIndexesLister,PerformanceAdvisorSlowOperationThresholdEnabler,PerformanceAdvisorSlowOperationThresholdDisabler -type PerformanceAdvisorNamespacesLister interface { - PerformanceAdvisorNamespaces(string, string, *atlas.NamespaceOptions) (*atlas.Namespaces, error) -} - -type PerformanceAdvisorSlowQueriesLister interface { - PerformanceAdvisorSlowQueries(string, string, *atlas.SlowQueryOptions) (*atlas.SlowQueries, error) -} - -type PerformanceAdvisorIndexesLister interface { - PerformanceAdvisorIndexes(string, string, *atlas.SuggestedIndexOptions) (*atlas.SuggestedIndexes, error) -} - -type PerformanceAdvisorSlowOperationThresholdEnabler interface { - EnablePerformanceAdvisorSlowOperationThreshold(string) error -} - -type PerformanceAdvisorSlowOperationThresholdDisabler interface { - DisablePerformanceAdvisorSlowOperationThreshold(string) error -} - -// PerformanceAdvisorNamespaces encapsulates the logic to manage different cloud providers. -func (s *Store) PerformanceAdvisorNamespaces(projectID, processName string, opts *atlas.NamespaceOptions) (*atlas.Namespaces, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).PerformanceAdvisor.GetNamespaces(s.ctx, projectID, processName, opts) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).PerformanceAdvisor.GetNamespaces(s.ctx, projectID, processName, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// PerformanceAdvisorSlowQueries encapsulates the logic to manage different cloud providers. -func (s *Store) PerformanceAdvisorSlowQueries(projectID, processName string, opts *atlas.SlowQueryOptions) (*atlas.SlowQueries, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).PerformanceAdvisor.GetSlowQueries(s.ctx, projectID, processName, opts) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).PerformanceAdvisor.GetSlowQueries(s.ctx, projectID, processName, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// PerformanceAdvisorIndexes encapsulates the logic to manage different cloud providers. -func (s *Store) PerformanceAdvisorIndexes(projectID, processName string, opts *atlas.SuggestedIndexOptions) (*atlas.SuggestedIndexes, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).PerformanceAdvisor.GetSuggestedIndexes(s.ctx, projectID, processName, opts) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).PerformanceAdvisor.GetSuggestedIndexes(s.ctx, projectID, processName, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// EnablePerformanceAdvisorSlowOperationThreshold encapsulates the logic to manage different cloud providers. -func (s *Store) EnablePerformanceAdvisorSlowOperationThreshold(projectID string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).PerformanceAdvisor.EnableManagedSlowOperationThreshold(s.ctx, projectID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DisablePerformanceAdvisorSlowOperationThreshold encapsulates the logic to manage different cloud providers. -func (s *Store) DisablePerformanceAdvisorSlowOperationThreshold(projectID string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).PerformanceAdvisor.DisableManagedSlowOperationThreshold(s.ctx, projectID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/project_invitations.go b/internal/store/project_invitations.go deleted file mode 100644 index a6b3321e9c..0000000000 --- a/internal/store/project_invitations.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2021 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_project_invitations.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store ProjectInvitationLister,ProjectInvitationDescriber,ProjectInvitationDeleter,ProjectInviter,ProjectInvitationUpdater - -type ProjectInvitationLister interface { - ProjectInvitations(string, *atlas.InvitationOptions) ([]*atlas.Invitation, error) -} - -type ProjectInvitationDescriber interface { - ProjectInvitation(string, string) (*atlas.Invitation, error) -} - -type ProjectInviter interface { - InviteUserToProject(string, *atlas.Invitation) (*atlas.Invitation, error) -} - -type ProjectInvitationDeleter interface { - DeleteProjectInvitation(string, string) error -} - -type ProjectInvitationUpdater interface { - UpdateProjectInvitation(string, string, *atlas.Invitation) (*atlas.Invitation, error) -} - -// ProjectInvitations encapsulate the logic to manage different cloud providers. -func (s *Store) ProjectInvitations(groupID string, opts *atlas.InvitationOptions) ([]*atlas.Invitation, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Projects.Invitations(s.ctx, groupID, opts) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Projects.Invitations(s.ctx, groupID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// ProjectInvitation encapsulate the logic to manage different cloud providers. -func (s *Store) ProjectInvitation(groupID, invitationID string) (*atlas.Invitation, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Projects.Invitation(s.ctx, groupID, invitationID) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Projects.Invitation(s.ctx, groupID, invitationID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteProjectInvitation encapsulate the logic to manage different cloud providers. -func (s *Store) DeleteProjectInvitation(groupID, invitationID string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).Projects.DeleteInvitation(s.ctx, groupID, invitationID) - return err - case config.CloudManagerService, config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).Projects.DeleteInvitation(s.ctx, groupID, invitationID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// InviteUserToProject encapsulate the logic to manage different cloud providers. -func (s *Store) InviteUserToProject(groupID string, invitation *atlas.Invitation) (*atlas.Invitation, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Projects.InviteUser(s.ctx, groupID, invitation) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Projects.InviteUser(s.ctx, groupID, invitation) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateProjectInvitation encapsulate the logic to manage different cloud providers. -func (s *Store) UpdateProjectInvitation(groupID, invitationID string, invitation *atlas.Invitation) (*atlas.Invitation, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - if invitationID != "" { - result, _, err := s.client.(*atlas.Client).Projects.UpdateInvitationByID(s.ctx, groupID, invitationID, invitation) - return result, err - } - result, _, err := s.client.(*atlas.Client).Projects.UpdateInvitation(s.ctx, groupID, invitation) - return result, err - - case config.CloudManagerService, config.OpsManagerService: - if invitationID != "" { - result, _, err := s.client.(*opsmngr.Client).Projects.UpdateInvitationByID(s.ctx, groupID, invitationID, invitation) - return result, err - } - result, _, err := s.client.(*opsmngr.Client).Projects.UpdateInvitation(s.ctx, groupID, invitation) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/s3_blockstores.go b/internal/store/s3_blockstores.go deleted file mode 100644 index 916e554b07..0000000000 --- a/internal/store/s3_blockstores.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_backup_s3_blockstores.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store S3BlockstoresLister,S3BlockstoresDeleter,S3BlockstoresCreator,S3BlockstoresUpdater,S3BlockstoresDescriber - -type S3BlockstoresLister interface { - ListS3Blockstores(*opsmngr.ListOptions) (*opsmngr.S3Blockstores, error) -} - -type S3BlockstoresDeleter interface { - DeleteS3Blockstore(string) error -} - -type S3BlockstoresCreator interface { - CreateS3Blockstores(*opsmngr.S3Blockstore) (*opsmngr.S3Blockstore, error) -} - -type S3BlockstoresUpdater interface { - UpdateS3Blockstores(string, *opsmngr.S3Blockstore) (*opsmngr.S3Blockstore, error) -} - -type S3BlockstoresDescriber interface { - GetS3Blockstore(string) (*opsmngr.S3Blockstore, error) -} - -// ListS3Blockstores encapsulates the logic to manage different cloud providers. -func (s *Store) ListS3Blockstores(options *opsmngr.ListOptions) (*opsmngr.S3Blockstores, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).S3BlockstoreConfig.List(s.ctx, options) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteS3Blockstores encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteS3Blockstore(blockstoreID string) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).S3BlockstoreConfig.Delete(s.ctx, blockstoreID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateS3Blockstores encapsulates the logic to manage different cloud providers. -func (s *Store) CreateS3Blockstores(blockstore *opsmngr.S3Blockstore) (*opsmngr.S3Blockstore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).S3BlockstoreConfig.Create(s.ctx, blockstore) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateS3Blockstores encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateS3Blockstores(blockstoreID string, blockstore *opsmngr.S3Blockstore) (*opsmngr.S3Blockstore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).S3BlockstoreConfig.Update(s.ctx, blockstoreID, blockstore) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// ListS3Blockstores encapsulates the logic to manage different cloud providers. -func (s *Store) GetS3Blockstore(blockstoreID string) (*opsmngr.S3Blockstore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).S3BlockstoreConfig.Get(s.ctx, blockstoreID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/server_usage.go b/internal/store/server_usage.go deleted file mode 100644 index 1e57ad2a40..0000000000 --- a/internal/store/server_usage.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - "io" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_server_usage.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store ProjectServerTypeGetter,ProjectServerTypeUpdater,OrganizationServerTypeGetter,OrganizationServerTypeUpdater,ProjectHostAssignmentLister,OrganizationHostAssignmentLister,SnapshotGenerator,ServerUsageReportDownloader - -type ProjectServerTypeGetter interface { - ProjectServerType(string) (*opsmngr.ServerType, error) -} - -type ProjectServerTypeUpdater interface { - UpdateProjectServerType(string, *opsmngr.ServerTypeRequest) error -} - -type OrganizationServerTypeGetter interface { - OrganizationServerType(string) (*opsmngr.ServerType, error) -} - -type OrganizationServerTypeUpdater interface { - UpdateOrganizationServerType(string, *opsmngr.ServerTypeRequest) error -} - -type ProjectHostAssignmentLister interface { - ProjectHostAssignments(string, *opsmngr.ServerTypeOptions) (*opsmngr.HostAssignments, error) -} - -type OrganizationHostAssignmentLister interface { - OrganizationHostAssignments(string, *opsmngr.ServerTypeOptions) (*opsmngr.HostAssignments, error) -} - -type SnapshotGenerator interface { - GenerateSnapshot() error -} - -type ServerUsageReportDownloader interface { - DownloadServerUsageReport(opts *opsmngr.ServerTypeOptions, out io.Writer) error -} - -// ProjectServerType encapsulates the logic to manage different cloud providers. -func (s *Store) ProjectServerType(projectID string) (*opsmngr.ServerType, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).ServerUsage.GetServerTypeProject(s.ctx, projectID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateProjectServerType encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateProjectServerType(projectID string, serverType *opsmngr.ServerTypeRequest) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).ServerUsage.UpdateProjectServerType(s.ctx, projectID, serverType) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// OrganizationServerType encapsulates the logic to manage different cloud providers. -func (s *Store) OrganizationServerType(orgID string) (*opsmngr.ServerType, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).ServerUsage.GetServerTypeOrganization(s.ctx, orgID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateOrganizationServerType encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateOrganizationServerType(orgID string, serverType *opsmngr.ServerTypeRequest) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).ServerUsage.UpdateOrganizationServerType(s.ctx, orgID, serverType) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// ProjectHostAssignments encapsulates the logic to manage different cloud providers. -func (s *Store) ProjectHostAssignments(projectID string, opts *opsmngr.ServerTypeOptions) (*opsmngr.HostAssignments, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).ServerUsage.ProjectHostAssignments(s.ctx, projectID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// OrganizationHostAssignments encapsulates the logic to manage different cloud providers. -func (s *Store) OrganizationHostAssignments(orgID string, opts *opsmngr.ServerTypeOptions) (*opsmngr.HostAssignments, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).ServerUsage.OrganizationHostAssignments(s.ctx, orgID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// GenerateSnapshot encapsulates the logic to manage different cloud providers. -func (s *Store) GenerateSnapshot() error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).ServerUsage.GenerateDailyUsageSnapshot(s.ctx) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DownloadServerUsageReport encapsulate the logic to manage different cloud providers. -func (s *Store) DownloadServerUsageReport(opts *opsmngr.ServerTypeOptions, out io.Writer) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).ServerUsageReport.Download(s.ctx, opts, out) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/snapshot_schedule.go b/internal/store/snapshot_schedule.go deleted file mode 100644 index 72f47821be..0000000000 --- a/internal/store/snapshot_schedule.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_backup_snapshot_schedule.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store SnapshotScheduleDescriber,SnapshotScheduleUpdater - -type SnapshotScheduleDescriber interface { - GetSnapshotSchedule(string, string) (*opsmngr.SnapshotSchedule, error) -} - -type SnapshotScheduleUpdater interface { - UpdateSnapshotSchedule(string, string, *opsmngr.SnapshotSchedule) (*opsmngr.SnapshotSchedule, error) -} - -// GetSnapshotSchedule encapsulates the logic to manage different cloud providers. -func (s *Store) GetSnapshotSchedule(projectID, clusterID string) (*opsmngr.SnapshotSchedule, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).SnapshotSchedule.Get(s.ctx, projectID, clusterID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateSnapshotSchedule encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateSnapshotSchedule(projectID, clusterID string, snapshotSchedule *opsmngr.SnapshotSchedule) (*opsmngr.SnapshotSchedule, error) { - switch s.service { - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).SnapshotSchedule.Update(s.ctx, projectID, clusterID, snapshotSchedule) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/sync.go b/internal/store/sync.go deleted file mode 100644 index 0927402da3..0000000000 --- a/internal/store/sync.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_backup_sync.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store SyncsLister,SyncsDescriber,SyncsCreator,SyncsUpdater,SyncsDeleter - -type SyncsLister interface { - ListSyncs(*opsmngr.ListOptions) (*opsmngr.BackupStores, error) -} - -type SyncsDescriber interface { - GetSync(string) (*opsmngr.BackupStore, error) -} - -type SyncsCreator interface { - CreateSync(*opsmngr.BackupStore) (*opsmngr.BackupStore, error) -} - -type SyncsUpdater interface { - UpdateSync(string, *opsmngr.BackupStore) (*opsmngr.BackupStore, error) -} - -type SyncsDeleter interface { - DeleteSync(string) error -} - -// ListSyncs encapsulates the logic to manage different cloud providers. -func (s *Store) ListSyncs(options *opsmngr.ListOptions) (*opsmngr.BackupStores, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).SyncStoreConfig.List(s.ctx, options) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// GetSync encapsulates the logic to manage different cloud providers. -func (s *Store) GetSync(syncID string) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).SyncStoreConfig.Get(s.ctx, syncID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateSync encapsulates the logic to manage different cloud providers. -func (s *Store) CreateSync(sync *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).SyncStoreConfig.Create(s.ctx, sync) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateSync encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateSync(syncID string, sync *opsmngr.BackupStore) (*opsmngr.BackupStore, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).SyncStoreConfig.Update(s.ctx, syncID, sync) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteSync encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteSync(syncID string) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).SyncStoreConfig.Delete(s.ctx, syncID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/teams.go b/internal/store/teams.go deleted file mode 100644 index 2ae757d4cf..0000000000 --- a/internal/store/teams.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_teams.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store TeamLister,TeamDescriber,TeamCreator,TeamDeleter,TeamAdder,TeamUserRemover,TeamRolesUpdater - -type TeamLister interface { - Teams(string, *atlas.ListOptions) ([]atlas.Team, error) -} - -type TeamDescriber interface { - TeamByID(string, string) (*atlas.Team, error) - TeamByName(string, string) (*atlas.Team, error) -} - -type TeamCreator interface { - CreateTeam(string, *atlas.Team) (*atlas.Team, error) -} - -type TeamDeleter interface { - DeleteTeam(string, string) error -} - -type TeamAdder interface { - AddUsersToTeam(string, string, []string) (interface{}, error) -} - -type TeamUserRemover interface { - RemoveUserFromTeam(string, string, string) error -} - -type TeamRolesUpdater interface { - UpdateProjectTeamRoles(string, string, *atlas.TeamUpdateRoles) ([]atlas.TeamRoles, error) -} - -// TeamByID encapsulates the logic to manage different cloud providers. -func (s *Store) TeamByID(orgID, teamID string) (*atlas.Team, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Teams.Get(s.ctx, orgID, teamID) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Teams.Get(s.ctx, orgID, teamID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// TeamByName encapsulates the logic to manage different cloud providers. -func (s *Store) TeamByName(orgID, teamName string) (*atlas.Team, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Teams.GetOneTeamByName(s.ctx, orgID, teamName) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Teams.GetOneTeamByName(s.ctx, orgID, teamName) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// Teams encapsulates the logic to manage different cloud providers. -func (s *Store) Teams(orgID string, opts *atlas.ListOptions) ([]atlas.Team, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Teams.List(s.ctx, orgID, opts) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Teams.List(s.ctx, orgID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// CreateTeam encapsulates the logic to manage different cloud providers. -func (s *Store) CreateTeam(orgID string, team *atlas.Team) (*atlas.Team, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Teams.Create(s.ctx, orgID, team) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Teams.Create(s.ctx, orgID, team) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteTeam encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteTeam(orgID, teamID string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).Teams.RemoveTeamFromOrganization(s.ctx, orgID, teamID) - return err - case config.CloudManagerService, config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).Teams.RemoveTeamFromOrganization(s.ctx, orgID, teamID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// AddUsersToTeam encapsulates the logic to manage different cloud providers. -func (s *Store) AddUsersToTeam(orgID, teamID string, users []string) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Teams.AddUsersToTeam(s.ctx, orgID, teamID, users) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Teams.AddUsersToTeam(s.ctx, orgID, teamID, users) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// RemoveUserFromTeam encapsulates the logic to manage different cloud providers. -func (s *Store) RemoveUserFromTeam(orgID, teamID, userID string) error { - switch s.service { - case config.CloudService, config.CloudGovService: - _, err := s.client.(*atlas.Client).Teams.RemoveUserToTeam(s.ctx, orgID, teamID, userID) - return err - case config.CloudManagerService, config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).Teams.RemoveUserToTeam(s.ctx, orgID, teamID, userID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UpdateProjectTeamRoles encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateProjectTeamRoles(projectID, teamID string, team *atlas.TeamUpdateRoles) ([]atlas.TeamRoles, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Teams.UpdateTeamRoles(s.ctx, projectID, teamID, team) - return result, err - case config.CloudManagerService, config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).Teams.UpdateTeamRoles(s.ctx, projectID, teamID, team) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/users.go b/internal/store/users.go deleted file mode 100644 index caa1f40450..0000000000 --- a/internal/store/users.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - atlas "go.mongodb.org/atlas/mongodbatlas" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_users.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store UserCreator,UserDescriber,UserDeleter,UserLister,TeamUserLister - -type UserCreator interface { - CreateUser(*UserRequest) (interface{}, error) -} - -type UserDeleter interface { - DeleteUser(string) error -} - -type UserLister interface { - OrganizationUsers(string, *atlas.ListOptions) (interface{}, error) -} - -type TeamUserLister interface { - TeamUsers(string, string) (interface{}, error) -} - -type UserDescriber interface { - UserByID(string) (interface{}, error) - UserByName(string) (interface{}, error) -} - -type UserRequest struct { - *opsmngr.User - AtlasRoles []atlas.AtlasRole -} - -// CreateUser encapsulates the logic to manage different cloud providers. -func (s *Store) CreateUser(user *UserRequest) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - atlasUser := &atlas.AtlasUser{ - EmailAddress: user.EmailAddress, - FirstName: user.FirstName, - LastName: user.LastName, - Roles: user.AtlasRoles, - Username: user.Username, - MobileNumber: user.MobileNumber, - Password: user.Password, - Country: user.Country, - } - result, _, err := s.client.(*atlas.Client).AtlasUsers.Create(s.ctx, atlasUser) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Users.Create(s.ctx, user.User) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UserByID encapsulates the logic to manage different cloud providers. -func (s *Store) UserByID(userID string) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AtlasUsers.Get(s.ctx, userID) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Users.Get(s.ctx, userID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// UserByName encapsulates the logic to manage different cloud providers. -func (s *Store) UserByName(username string) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).AtlasUsers.GetByName(s.ctx, username) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Users.GetByName(s.ctx, username) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// DeleteUser encapsulates the logic to manage different cloud providers. -func (s *Store) DeleteUser(userID string) error { - switch s.service { - case config.OpsManagerService: - _, err := s.client.(*opsmngr.Client).Users.Delete(s.ctx, userID) - return err - default: - return fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// OrganizationUsers encapsulates the logic to manage different cloud providers. -func (s *Store) OrganizationUsers(organizationID string, opts *atlas.ListOptions) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Organizations.Users(s.ctx, organizationID, opts) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Organizations.ListUsers(s.ctx, organizationID, opts) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// TeamUsers encapsulates the logic to manage different cloud providers. -func (s *Store) TeamUsers(orgID, teamID string) (interface{}, error) { - switch s.service { - case config.CloudService, config.CloudGovService: - result, _, err := s.client.(*atlas.Client).Teams.GetTeamUsersAssigned(s.ctx, orgID, teamID) - return result, err - case config.OpsManagerService, config.CloudManagerService: - result, _, err := s.client.(*opsmngr.Client).Teams.GetTeamUsersAssigned(s.ctx, orgID, teamID) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} diff --git a/internal/store/version_manifest.go b/internal/store/version_manifest.go deleted file mode 100644 index 8d830a8ac0..0000000000 --- a/internal/store/version_manifest.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 MongoDB Inc -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package store - -import ( - "fmt" - - "github.com/mongodb/mongodb-atlas-cli/internal/config" - "go.mongodb.org/ops-manager/opsmngr" -) - -//go:generate mockgen -destination=../mocks/mock_version_manifest.go -package=mocks github.com/mongodb/mongodb-atlas-cli/internal/store VersionManifestUpdater,VersionManifestGetter,VersionManifestUpdaterServiceVersionDescriber - -type VersionManifestUpdater interface { - UpdateVersionManifest(*opsmngr.VersionManifest) (*opsmngr.VersionManifest, error) -} - -type VersionManifestGetter interface { - GetVersionManifest(string) (*opsmngr.VersionManifest, error) -} - -type VersionManifestUpdaterServiceVersionDescriber interface { - VersionManifestUpdater - ServiceVersionDescriber -} - -// UpdateVersionManifest encapsulates the logic to manage different cloud providers. -func (s *Store) UpdateVersionManifest(versionManifest *opsmngr.VersionManifest) (*opsmngr.VersionManifest, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).VersionManifest.Update(s.ctx, versionManifest) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -} - -// GetVersionManifest encapsulates the logic to manage different cloud providers. -func (s *Store) GetVersionManifest(version string) (*opsmngr.VersionManifest, error) { - switch s.service { - case config.OpsManagerService: - result, _, err := s.client.(*opsmngr.Client).VersionManifest.Get(s.ctx, version) - return result, err - default: - return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service) - } -}