github.com/wanddynosios/cli/v8@v8.7.9-0.20240221182337-1a92e3a7017f/command/flag/bytes_with_unlimited.go (about)

     1  package flag
     2  
     3  import (
     4  	"regexp"
     5  	"strings"
     6  
     7  	"code.cloudfoundry.org/bytefmt"
     8  	"code.cloudfoundry.org/cli/types"
     9  	flags "github.com/jessevdk/go-flags"
    10  )
    11  
    12  type BytesWithUnlimited types.NullInt
    13  
    14  var zeroBytes *regexp.Regexp = regexp.MustCompile(`^0[KMGT]?B?$`)
    15  var negativeOneBytes *regexp.Regexp = regexp.MustCompile(`^-1[KMGT]?B?$`)
    16  
    17  func (m *BytesWithUnlimited) UnmarshalFlag(val string) error {
    18  	if val == "" {
    19  		return nil
    20  	}
    21  
    22  	if negativeOneBytes.MatchString(val) {
    23  		m.Value = -1
    24  		m.IsSet = true
    25  		return nil
    26  	}
    27  
    28  	if zeroBytes.MatchString(val) {
    29  		m.Value = 0
    30  		m.IsSet = true
    31  		return nil
    32  	}
    33  
    34  	size, err := ConvertToBytes(val)
    35  	if err != nil {
    36  		return err
    37  	}
    38  
    39  	m.Value = int(size)
    40  	m.IsSet = true
    41  
    42  	return nil
    43  }
    44  
    45  func (m *BytesWithUnlimited) IsValidValue(val string) error {
    46  	return m.UnmarshalFlag(val)
    47  }
    48  
    49  func ConvertToBytes(val string) (uint64, error) {
    50  	size, err := bytefmt.ToBytes(val)
    51  
    52  	if err != nil || strings.Contains(strings.ToLower(val), ".") {
    53  		return size, &flags.Error{
    54  			Type:    flags.ErrRequired,
    55  			Message: `Byte quantity must be an integer with a unit of measurement like B, K, KB, M, MB, G, or GB`,
    56  		}
    57  	}
    58  	return size, nil
    59  }