code.vegaprotocol.io/vega@v0.79.0/cmd/vegawallet/commands/cli/template.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package cli 17 18 import ( 19 "bytes" 20 "fmt" 21 "os" 22 "strings" 23 "text/template" 24 ) 25 26 const indentation = ` ` 27 28 type exampleData struct { 29 Software string 30 } 31 32 // LongDesc normalizes a command's long description to follow the conventions. 33 func LongDesc(s string) string { 34 if len(s) == 0 { 35 return s 36 } 37 return normalizer{s}.trim().noIndent().string 38 } 39 40 // Examples normalizes a command's examples to follow the conventions. 41 func Examples(s string) string { 42 if len(s) == 0 { 43 return s 44 } 45 46 software := os.Args[0] 47 48 // If the wallet cmd is embedded inside vega, we display the software as 49 // a sub-command in the examples. 50 if software == "vega" || strings.HasSuffix(software, "/vega") { 51 software = fmt.Sprintf("%s wallet", software) 52 } 53 54 sweaters := exampleData{ 55 Software: software, 56 } 57 tmpl, err := template.New("example").Parse(s) 58 if err != nil { 59 panic(err) 60 } 61 62 var tpl bytes.Buffer 63 err = tmpl.Execute(&tpl, sweaters) 64 if err != nil { 65 panic(err) 66 } 67 68 return normalizer{tpl.String()}.trim().indent().string 69 } 70 71 type normalizer struct { 72 string 73 } 74 75 func (s normalizer) trim() normalizer { 76 s.string = strings.TrimSpace(s.string) 77 return s 78 } 79 80 func (s normalizer) indent() normalizer { 81 indentedLines := []string{} 82 for _, line := range strings.Split(s.string, "\n") { 83 trimmed := strings.TrimSpace(line) 84 indented := indentation + trimmed 85 indentedLines = append(indentedLines, indented) 86 } 87 s.string = strings.Join(indentedLines, "\n") 88 return s 89 } 90 91 func (s normalizer) noIndent() normalizer { 92 indentedLines := []string{} 93 for _, line := range strings.Split(s.string, "\n") { 94 trimmed := strings.TrimSpace(line) 95 indentedLines = append(indentedLines, trimmed) 96 } 97 s.string = strings.Join(indentedLines, "\n") 98 return s 99 }