github.com/jenspinney/cli@v6.42.1-0.20190207184520-7450c600020e+incompatible/types/null_bool.go (about)

     1  package types
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strconv"
     7  )
     8  
     9  // NullBool is a wrapper around bool values that can be null or an bool.
    10  // Use IsSet to check if the value is provided, instead of checking against false.
    11  type NullBool struct {
    12  	IsSet bool
    13  	Value bool
    14  }
    15  
    16  // ParseStringValue is used to parse a user provided flag argument.
    17  func (n *NullBool) ParseStringValue(val string) error {
    18  	if val == "" {
    19  		return nil
    20  	}
    21  
    22  	boolVal, err := strconv.ParseBool(val)
    23  	if err != nil {
    24  		return err
    25  	}
    26  
    27  	n.Value = boolVal
    28  	n.IsSet = true
    29  
    30  	return nil
    31  }
    32  
    33  // ParseBoolValue is used to parse a user provided *bool argument.
    34  func (n *NullBool) ParseBoolValue(val *bool) {
    35  	if val == nil {
    36  		n.IsSet = false
    37  		n.Value = false
    38  		return
    39  	}
    40  
    41  	n.Value = *val
    42  	n.IsSet = true
    43  }
    44  
    45  func (n *NullBool) UnmarshalJSON(rawJSON []byte) error {
    46  	var value *bool
    47  	err := json.Unmarshal(rawJSON, &value)
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	if value == nil {
    53  		n.Value = false
    54  		n.IsSet = false
    55  		return nil
    56  	}
    57  
    58  	n.Value = *value
    59  	n.IsSet = true
    60  
    61  	return nil
    62  }
    63  
    64  func (n NullBool) MarshalJSON() ([]byte, error) {
    65  	if n.IsSet {
    66  		return []byte(fmt.Sprint(n.Value)), nil
    67  	}
    68  	return []byte("null"), nil
    69  }