cli_tools/common/image/importer/validator.go (30 lines of code) (raw):
// Copyright 2020 Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package importer
import (
"fmt"
"google.golang.org/api/compute/v1"
)
// validator is the interface for performing validations.
//
// validate returns nil when passing, and non-nil when failing.
type validator interface {
validate() error
}
func newPreValidator(request ImageImportRequest, client getImageClient) validator {
return validateImageNameAvailable{
project: request.Project,
name: request.ImageName,
client: client,
}
}
// validateImageNameAvailable is an importer.validator that
// ensures the user's destination image name hasn't already
// been used.
type validateImageNameAvailable struct {
project, name string
client getImageClient
}
func (v validateImageNameAvailable) validate() error {
// We ignore the error, with the assumption that if there's an error,
// then the image name may be available.
image, _ := v.client.GetImage(v.project, v.name)
if image != nil {
return fmt.Errorf("The resource '%s' already exists. "+
"Please pick an image name that isn't already used.", v.name)
}
return nil
}
// diskClient is the subset of the GCP API that is used by validateImageNameAvailable.
type getImageClient interface {
GetImage(project, name string) (*compute.Image, error)
}