...

Source file src/kubevirt.io/client-go/precond/precond.go

Documentation: kubevirt.io/client-go/precond

     1  /*
     2   * This file is part of the KubeVirt project
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   * Copyright 2017 Red Hat, Inc.
    17   *
    18   */
    19  
    20  package precond
    21  
    22  import (
    23  	"fmt"
    24  )
    25  
    26  type PreconditionError struct {
    27  	msg string
    28  }
    29  
    30  func (e *PreconditionError) Error() string {
    31  	return e.msg
    32  }
    33  
    34  func MustNotBeEmpty(str string, msg ...interface{}) string {
    35  	panicOnError(CheckNotEmpty(str, msg...))
    36  	return str
    37  }
    38  
    39  func MustNotBeNil(obj interface{}, msg ...interface{}) interface{} {
    40  	panicOnError(CheckNotNil(obj, msg...))
    41  	return obj
    42  }
    43  
    44  func MustBeTrue(b bool, msg ...interface{}) {
    45  	panicOnError(CheckTrue(b, msg...))
    46  }
    47  
    48  func CheckNotEmpty(str string, msg ...interface{}) error {
    49  	if str == "" {
    50  		return newError("String must not be empty", msg...)
    51  	}
    52  	return nil
    53  }
    54  
    55  func CheckNotNil(obj interface{}, msg ...interface{}) error {
    56  	if obj == nil {
    57  		return newError("Object must not be nil", msg...)
    58  	}
    59  	return nil
    60  }
    61  
    62  func CheckTrue(b bool, msg ...interface{}) error {
    63  	if b == false {
    64  		return newError("Expression must be true", msg...)
    65  	}
    66  	return nil
    67  }
    68  
    69  func panicOnError(e error) {
    70  	if e != nil {
    71  		panic(e)
    72  	}
    73  }
    74  
    75  func newError(defaultMsg string, msg ...interface{}) *PreconditionError {
    76  	return &PreconditionError{msg: newErrMsg(defaultMsg, msg...)}
    77  }
    78  
    79  func newErrMsg(defaultMsg string, msg ...interface{}) string {
    80  	if msg != nil {
    81  		switch t := msg[0].(type) {
    82  		case string:
    83  			return fmt.Sprintf(t, msg[1:]...)
    84  		default:
    85  			return fmt.Sprint(msg...)
    86  		}
    87  	}
    88  	return defaultMsg
    89  }
    90  

View as plain text