github.com/minio/minio@v0.0.0-20240328213742-3f72439b8a27/internal/config/bool-flag.go (about) 1 // Copyright (c) 2015-2021 MinIO, Inc. 2 // 3 // This file is part of MinIO Object Storage stack 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 package config 19 20 import ( 21 "encoding/json" 22 "fmt" 23 "strconv" 24 "strings" 25 ) 26 27 // BoolFlag - wrapper bool type. 28 type BoolFlag bool 29 30 // String - returns string of BoolFlag. 31 func (bf BoolFlag) String() string { 32 if bf { 33 return "on" 34 } 35 36 return "off" 37 } 38 39 // MarshalJSON - converts BoolFlag into JSON data. 40 func (bf BoolFlag) MarshalJSON() ([]byte, error) { 41 return json.Marshal(bf.String()) 42 } 43 44 // UnmarshalJSON - parses given data into BoolFlag. 45 func (bf *BoolFlag) UnmarshalJSON(data []byte) (err error) { 46 var s string 47 if err = json.Unmarshal(data, &s); err == nil { 48 b := BoolFlag(true) 49 if s == "" { 50 // Empty string is treated as valid. 51 *bf = b 52 } else if b, err = ParseBoolFlag(s); err == nil { 53 *bf = b 54 } 55 } 56 57 return err 58 } 59 60 // FormatBool prints stringified version of boolean. 61 func FormatBool(b bool) string { 62 if b { 63 return "on" 64 } 65 return "off" 66 } 67 68 // ParseBool returns the boolean value represented by the string. 69 // It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. 70 // Any other value returns an error. 71 func ParseBool(str string) (bool, error) { 72 switch str { 73 case "1", "t", "T", "true", "TRUE", "True", "on", "ON", "On": 74 return true, nil 75 case "0", "f", "F", "false", "FALSE", "False", "off", "OFF", "Off": 76 return false, nil 77 } 78 if strings.EqualFold(str, "enabled") { 79 return true, nil 80 } 81 if strings.EqualFold(str, "disabled") { 82 return false, nil 83 } 84 return false, fmt.Errorf("ParseBool: parsing '%s': %w", str, strconv.ErrSyntax) 85 } 86 87 // ParseBoolFlag - parses string into BoolFlag. 88 func ParseBoolFlag(s string) (bf BoolFlag, err error) { 89 b, err := ParseBool(s) 90 return BoolFlag(b), err 91 }