Debian Codegraph @

gen.go

raw symbols SCIP
1 //go:build ignore
2
3 package main
4
5 import (
6 "archive/tar"
7 "bufio"
8 "bytes"
9 "compress/gzip"
10 "errors"
11 "flag"
12 "fmt"
13 "go/format"
14 "io"
15 "io/ioutil"
16 "log"
17 "net/http"
18 "os"
19 "path/filepath"
20 "regexp"
21 "sort"
22 "strconv"
23 "strings"
24 "unicode"
25
26 "github.com/kenshaw/snaker"
27 )
28
29 func main() {
30 out := flag.String("out", "capvals.go", "out file")
31 cache := flag.String("cache", ".cache", "cache directory")
32 ver := flag.String("ver", "", "version")
33 flag.Parse()
34 if err := run(*out, *cache, *ver); err != nil {
35 fmt.Fprintf(os.Stderr, "error: %v\n", err)
36 os.Exit(1)
37 }
38 }
39
40 func run(dest, cache, ver string) error {
41 // get version
42 ver, err := getVer(ver)
43 if err != nil {
44 return err
45 }
46 // get archive
47 buf, err := get(cache, ver)
48 if err != nil {
49 return err
50 }
51 // load caps file
52 caps, err := load(buf, ver)
53 if err != nil {
54 return err
55 }
56 // process caps
57 buf, err = processCaps(caps)
58 if err != nil {
59 return err
60 }
61 // write
62 buf, err = format.Source(buf)
63 if err != nil {
64 return err
65 }
66 return ioutil.WriteFile(dest, buf, 0o644)
67 }
68
69 func getVer(ver string) (string, error) {
70 if ver != "" {
71 return ver, nil
72 }
73 res, err := http.Get("https://ftp.gnu.org/pub/gnu/ncurses/")
74 if err != nil {
75 return "", err
76 }
77 defer res.Body.Close()
78 buf, err := io.ReadAll(res.Body)
79 if err != nil {
80 return "", err
81 }
82 m := verRE.FindAllStringSubmatch(string(buf), -1)
83 sort.Slice(m, func(i, j int) bool {
84 va, _ := strconv.Atoi(m[i][1])
85 vb, _ := strconv.Atoi(m[j][1])
86 if va == vb {
87 va, _ = strconv.Atoi(m[i][2])
88 vb, _ = strconv.Atoi(m[j][2])
89 return va > vb
90 }
91 return va > vb
92 })
93 return m[0][1] + "." + m[0][2], nil
94 }
95
96 var verRE = regexp.MustCompile(`href="ncurses-([0-9]+)\.([0-9]+)\.tar\.gz"`)
97
98 // get retrieves a file either from the the http path, or from disk.
99 func get(cache, ver string) ([]byte, error) {
100 file := fmt.Sprintf("https://ftp.gnu.org/pub/gnu/ncurses/ncurses-%s.tar.gz", ver)
101 if err := os.MkdirAll(cache, 0o755); err != nil {
102 return nil, err
103 }
104 // check if the file exists
105 cacheFile := filepath.Join(cache, filepath.Base(file))
106 fi, err := os.Stat(cacheFile)
107 if err == nil && !fi.IsDir() {
108 log.Printf("loading %s", cacheFile)
109 return ioutil.ReadFile(cacheFile)
110 }
111 // retrieve
112 log.Printf("retrieving %s", file)
113 res, err := http.Get(file)
114 if err != nil {
115 return nil, err
116 }
117 defer res.Body.Close()
118 // read
119 buf, err := ioutil.ReadAll(res.Body)
120 if err != nil {
121 return nil, err
122 }
123 // cache
124 log.Printf("saving %s", cacheFile)
125 if err := ioutil.WriteFile(cacheFile, buf, 0o644); err != nil {
126 return nil, err
127 }
128 return buf, nil
129 }
130
131 // load extracts a file from a tar.gz.
132 func load(buf []byte, ver string) ([]byte, error) {
133 file := fmt.Sprintf("ncurses-%s/include/Caps", ver)
134 // create gzip reader
135 gr, err := gzip.NewReader(bytes.NewReader(buf))
136 if err != nil {
137 return nil, err
138 }
139 defer gr.Close()
140 // walk files in tar
141 tr := tar.NewReader(gr)
142 for {
143 h, err := tr.Next()
144 if err == io.EOF {
145 break
146 } else if err != nil {
147 return nil, err
148 }
149 // found file, read contents
150 if h.Name == file {
151 b := bytes.NewBuffer(make([]byte, h.Size))
152 var n int64
153 n, err = io.Copy(b, tr)
154 if err != nil {
155 return nil, err
156 }
157 // check that all bytes were copied
158 if n != h.Size {
159 return nil, errors.New("could not read entire file")
160 }
161 return b.Bytes(), nil
162 }
163 }
164 return nil, fmt.Errorf("could not load file %s", file)
165 }
166
167 // processCaps processes the data in the Caps file.
168 func processCaps(capsBuf []byte) ([]byte, error) {
169 // create scanner
170 s := bufio.NewScanner(bytes.NewReader(capsBuf))
171 s.Buffer(make([]byte, 1024*1024), 1024*1024)
172 // storage
173 bools, nums, strs := new(bytes.Buffer), new(bytes.Buffer), new(bytes.Buffer)
174 var boolCount, numCount, stringCount int
175 var lastBool, lastNum, lastString string
176 var boolNames, numNames, stringNames []string
177 // process caps
178 var n int
179 for s.Scan() {
180 // read line
181 line := strings.TrimSpace(commentRE.ReplaceAllString(strings.Trim(s.Text(), "\x00"), ""))
182 if len(line) == 0 || strings.HasPrefix(line, "capalias") || strings.HasPrefix(line, "infoalias") {
183 continue
184 }
185 // split line's columns
186 row := make([]string, 8)
187 for i := 0; i < 7; i++ {
188 start := strings.IndexFunc(line, unicode.IsSpace)
189 end := strings.IndexFunc(line[start:], notSpace)
190 row[i] = strings.TrimSpace(line[:start+end])
191 line = line[start+end:]
192 }
193 row[7] = strings.TrimSpace(line)
194 // manipulation
195 var buf *bytes.Buffer
196 var names *[]string
197 var typ, isFirst, prefix, suffix string
198 // format variable name
199 name := snaker.SnakeToCamel(row[0])
200 switch row[2] {
201 case "bool":
202 if boolCount == 0 {
203 isFirst = " = iota"
204 }
205 buf, names, lastBool, prefix, suffix = bools, &boolNames, name, "indicates", ""
206 typ = "bool"
207 boolCount++
208 case "num":
209 if numCount == 0 {
210 isFirst = " = iota"
211 }
212 buf, names, lastNum, prefix, suffix = nums, &numNames, name, "is", ""
213 typ = "num"
214 numCount++
215 case "str":
216 if stringCount == 0 {
217 isFirst = " = iota"
218 }
219 buf, names, lastString, prefix, suffix = strs, &stringNames, name, "is the", ""
220 typ = "string"
221 stringCount++
222 default:
223 return nil, fmt.Errorf("line %d is invalid, has type: %s", n, row[2])
224 }
225 if isFirst == "" {
226 buf.WriteString("\n")
227 }
228 fmt.Fprintf(buf, "// The %s [%s, %s] %s capability %s\n%s%s", name, row[0], row[1], typ, formatComment(row[7], prefix, suffix), name, isFirst)
229 *names = append(*names, row[0], row[1])
230 n++
231 }
232 if err := s.Err(); err != nil {
233 return nil, err
234 }
235 f := new(bytes.Buffer)
236 f.WriteString(hdr)
237 // add consts
238 typs := []string{"Bool", "Num", "String"}
239 for i, b := range []*bytes.Buffer{bools, nums, strs} {
240 f.WriteString(fmt.Sprintf("// %s capabilities.\nconst (\n", typs[i]))
241 b.WriteTo(f)
242 f.WriteString(")\n")
243 }
244 // add counts
245 f.WriteString("const (\n")
246 f.WriteString(fmt.Sprintf("// CapCountBool is the count of bool capabilities.\nCapCountBool = %s+1\n", lastBool))
247 f.WriteString(fmt.Sprintf("// CapCountNum is the count of num capabilities.\nCapCountNum = %s+1\n", lastNum))
248 f.WriteString(fmt.Sprintf("// CapCountString is the count of string capabilities.\nCapCountString = %s+1\n", lastString))
249 f.WriteString(")\n")
250 // add names
251 z := []string{"bool", "num", "string"}
252 for n, s := range [][]string{boolNames, numNames, stringNames} {
253 y := z[n]
254 f.WriteString(fmt.Sprintf("// %sCapNames are the %s term cap names.\n", y, y))
255 f.WriteString(fmt.Sprintf("var %sCapNames = [...]string{\n", y))
256 for i := 0; i < len(s); i += 2 {
257 f.WriteString(fmt.Sprintf(`"%s", "%s",`+"\n", s[i], s[i+1]))
258 }
259 f.WriteString("}\n")
260 }
261 return f.Bytes(), nil
262 }
263
264 // formatComment formats comments with prefix and suffix.
265 func formatComment(s, prefix, suffix string) string {
266 s = strings.TrimPrefix(s, prefix)
267 s = strings.TrimSuffix(s, ".")
268 s = strings.TrimSuffix(s, suffix)
269 return strings.TrimSpace(prefix+" "+s+" "+suffix) + "."
270 }
271
272 func notSpace(r rune) bool {
273 return !unicode.IsSpace(r)
274 }
275
276 var commentRE = regexp.MustCompile(`^#.*`)
277
278 const hdr = `package terminfo
279 // Code generated by gen.go. DO NOT EDIT.
280 `