cuelang.org/go@v0.10.1/internal/cli/cli.go (about) 1 // Copyright 2020 CUE Authors 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 cli 16 17 import ( 18 "strings" 19 20 "cuelang.org/go/cue" 21 "cuelang.org/go/cue/ast" 22 "cuelang.org/go/cue/errors" 23 "cuelang.org/go/cue/parser" 24 "cuelang.org/go/cue/token" 25 ) 26 27 func ParseValue(pos token.Pos, name, str string, k cue.Kind) (x ast.Expr, errs errors.Error) { 28 var expr ast.Expr 29 30 if k&cue.NumberKind != 0 { 31 var err error 32 expr, err = parser.ParseExpr(name, str) 33 if err != nil { 34 errs = errors.Wrapf(err, pos, 35 "invalid number for injection tag %q", name) 36 } 37 } 38 39 if k&cue.BoolKind != 0 { 40 str = strings.TrimSpace(str) 41 b, ok := boolValues[str] 42 if !ok { 43 errs = errors.Append(errs, errors.Newf(pos, 44 "invalid boolean value %q for injection tag %q", str, name)) 45 } else if expr != nil || k&cue.StringKind != 0 { 46 // Convert into an expression 47 bl := ast.NewBool(b) 48 if expr != nil { 49 expr = &ast.BinaryExpr{Op: token.OR, X: expr, Y: bl} 50 } else { 51 expr = bl 52 } 53 } else { 54 x = ast.NewBool(b) 55 } 56 } 57 58 if k&cue.StringKind != 0 { 59 if expr != nil { 60 expr = &ast.BinaryExpr{Op: token.OR, X: expr, Y: ast.NewString(str)} 61 } else { 62 x = ast.NewString(str) 63 } 64 } 65 66 switch { 67 case expr != nil: 68 return expr, nil 69 case x != nil: 70 return x, nil 71 case errs == nil: 72 return nil, errors.Newf(pos, 73 "invalid type for injection tag %q", name) 74 } 75 return nil, errs 76 } 77 78 var boolValues = map[string]bool{ 79 "1": true, 80 "0": false, 81 "t": true, 82 "f": false, 83 "T": true, 84 "F": false, 85 "true": true, 86 "false": false, 87 "TRUE": true, 88 "FALSE": false, 89 "True": true, 90 "False": false, 91 }