github.com/GoogleCloudPlatform/compute-image-tools/cli_tools@v0.0.0-20240516224744-de2dabc4ed1b/common/assert/assert.go (about)

     1  //  Copyright 2020 Google Inc. All Rights Reserved.
     2  //
     3  //  Licensed under the Apache License, Version 2.0 (the "License");
     4  //  you may not use this file except in compliance with the License.
     5  //  You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  //  Unless required by applicable law or agreed to in writing, software
    10  //  distributed under the License is distributed on an "AS IS" BASIS,
    11  //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  //  See the License for the specific language governing permissions and
    13  //  limitations under the License.
    14  
    15  package assert
    16  
    17  import (
    18  	"fmt"
    19  	"reflect"
    20  
    21  	"github.com/GoogleCloudPlatform/compute-image-tools/cli_tools/common/utils/files"
    22  )
    23  
    24  // NotEmpty asserts that obj is non-null and does not have a zero value.
    25  func NotEmpty(obj interface{}) {
    26  	if isEmpty(obj) {
    27  		panic("Expected non-empty value")
    28  	}
    29  }
    30  
    31  func isEmpty(obj interface{}) bool {
    32  	if obj == nil {
    33  		return true
    34  	}
    35  
    36  	v := reflect.ValueOf(obj)
    37  	switch v.Kind() {
    38  	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
    39  		return v.Len() == 0
    40  	}
    41  	return v.IsZero()
    42  }
    43  
    44  // GreaterThanOrEqualTo asserts that value is greater than or equal to limit.
    45  func GreaterThanOrEqualTo(value int, limit int) {
    46  	if value < limit {
    47  		panic(fmt.Sprintf("Expected %d >= %d", value, limit))
    48  	}
    49  }
    50  
    51  // Contains asserts that element is a member of arr.
    52  func Contains(element string, arr []string) {
    53  	for _, e := range arr {
    54  		if e == element {
    55  			return
    56  		}
    57  	}
    58  	panic(fmt.Sprintf("%s is not a member of %v", element, arr))
    59  }
    60  
    61  // DirectoryExists asserts that a directory is on the current filesystem.
    62  func DirectoryExists(dir string) {
    63  	if !files.DirectoryExists(dir) {
    64  		panic(fmt.Sprintf("%s: Directory not found", dir))
    65  	}
    66  }