github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/elvish/eval/variable_ref.go (about) 1 package eval 2 3 import "strings" 4 5 // ParseVariableRef parses a variable reference. 6 func ParseVariableRef(text string) (explode bool, ns string, name string) { 7 return parseVariableRef(text, true) 8 } 9 10 // ParseIncompleteVariableRef parses an incomplete variable reference. 11 func ParseIncompleteVariableRef(text string) (explode bool, ns string, name string) { 12 return parseVariableRef(text, false) 13 } 14 15 func parseVariableRef(text string, complete bool) (explode bool, ns string, name string) { 16 explodePart, nsPart, name := splitVariableRef(text, complete) 17 ns = nsPart 18 if len(ns) > 0 { 19 ns = ns[:len(ns)-1] 20 } 21 return explodePart != "", ns, name 22 } 23 24 // SplitVariableRef splits a variable reference into three parts: an optional 25 // explode operator (either "" or "@"), a namespace part, and a name part. 26 func SplitVariableRef(text string) (explodePart, nsPart, name string) { 27 return splitVariableRef(text, true) 28 } 29 30 // SplitIncompleteVariableRef splits an incomplete variable reference into three 31 // parts: an optional explode operator (either "" or "@"), a namespace part, and 32 // a name part. 33 func SplitIncompleteVariableRef(text string) (explodePart, nsPart, name string) { 34 return splitVariableRef(text, false) 35 } 36 37 func splitVariableRef(text string, complete bool) (explodePart, nsPart, name string) { 38 if text == "" { 39 return "", "", "" 40 } 41 e, qname := "", text 42 if text[0] == '@' { 43 e = "@" 44 qname = text[1:] 45 } 46 if qname == "" { 47 return e, "", "" 48 } 49 i := strings.LastIndexByte(qname, ':') 50 if complete && i == len(qname)-1 { 51 i = strings.LastIndexByte(qname[:len(qname)-1], ':') 52 } 53 return e, qname[:i+1], qname[i+1:] 54 } 55 56 // MakeVariableRef builds a variable reference. 57 func MakeVariableRef(explode bool, ns string, name string) string { 58 prefix := "" 59 if explode { 60 prefix = "@" 61 } 62 if ns != "" { 63 prefix += ns + ":" 64 } 65 return prefix + name 66 }