Debian Codegraph @

properties.go

raw
1 // This file is part of go-properties-orderedmap library.
2 //
3 // SPDX-FileCopyrightText: Arduino s.r.l. and/or its affiliated companies
4 // SPDX-License-Identifier: GPL-2.0-or-later
5
6 /*
7 Package properties is a library for handling maps of hierarchical properties.
8 This library is mainly used in the Arduino platform software to handle
9 configurations made of key/value pairs stored in files with an INI like
10 syntax, for example:
11
12 ...
13 uno.name=Arduino/Genuino Uno
14 uno.upload.tool=avrdude
15 uno.upload.protocol=arduino
16 uno.upload.maximum_size=32256
17 uno.upload.maximum_data_size=2048
18 uno.upload.speed=115200
19 uno.build.mcu=atmega328p
20 uno.build.f_cpu=16000000L
21 uno.build.board=AVR_UNO
22 uno.build.core=arduino
23 uno.build.variant=standard
24 diecimila.name=Arduino Duemilanove or Diecimila
25 diecimila.upload.tool=avrdude
26 diecimila.upload.protocol=arduino
27 diecimila.build.f_cpu=16000000L
28 diecimila.build.board=AVR_DUEMILANOVE
29 diecimila.build.core=arduino
30 diecimila.build.variant=standard
31 ...
32
33 This library has methods to parse this kind of file into a Map object.
34
35 The Map internally keeps the insertion order so it can be retrieved later when
36 cycling through the key sets.
37
38 The Map object has many helper methods to accomplish some common operations
39 on this kind of data like cloning, merging, comparing and also extracting
40 a submap or generating a map-of-submaps from the first "level" of the hierarchy.
41
42 On the Arduino platform the properties are used to populate command line recipes
43 so there are some methods to help this task like SplitQuotedString or ExpandPropsInString.
44 */
45 package properties
46
47 import (
48 "fmt"
49 "iter"
50 "maps"
51 "math/rand"
52 "os"
53 "reflect"
54 "regexp"
55 "runtime"
56 "sort"
57 "strconv"
58 "strings"
59 "unicode/utf8"
60
61 "github.com/arduino/go-paths-helper"
62 )
63
64 // Map is a container of properties
65 type Map struct {
66 kv map[string]string
67 o []string
68
69 // Debug if set to true ExpandPropsInString will always output debugging information
70 Debug bool
71 }
72
73 var osSuffix string
74
75 func init() {
76 switch value := runtime.GOOS; value {
77 case "darwin":
78 osSuffix = "macosx"
79 default:
80 osSuffix = runtime.GOOS
81 }
82 }
83
84 // GetOSSuffix returns the os name used to filter os-specific properties in Load* functions
85 func GetOSSuffix() string {
86 return osSuffix
87 }
88
89 // SetOSSuffix forces the OS suffix to the given value
90 func SetOSSuffix(suffix string) {
91 osSuffix = suffix
92 }
93
94 // NewMap returns a new Map
95 func NewMap() *Map {
96 return &Map{
97 kv: map[string]string{},
98 o: []string{},
99 }
100 }
101
102 // NewFromHashmap creates a new Map from the given map[string]string.
103 // Insertion order is not preserved.
104 func NewFromHashmap(orig map[string]string) *Map {
105 res := NewMap()
106 for k, v := range orig {
107 res.Set(k, v)
108 }
109 return res
110 }
111
112 func toUtf8(iso8859_1_buf []byte) string {
113 buf := make([]rune, len(iso8859_1_buf))
114 for i, b := range iso8859_1_buf {
115 buf[i] = rune(b)
116 }
117 return string(buf)
118 }
119
120 // LoadFromBytes reads properties data and makes a Map out of it.
121 func LoadFromBytes(bytes []byte) (*Map, error) {
122 var text string
123 if utf8.Valid(bytes) {
124 text = string(bytes)
125 } else {
126 // Assume ISO8859-1 encoding and convert to UTF-8
127 text = toUtf8(bytes)
128 }
129 text = strings.Replace(text, "\r\n", "\n", -1)
130 text = strings.Replace(text, "\r", "\n", -1)
131
132 properties := NewMap()
133
134 for lineNum, line := range strings.Split(text, "\n") {
135 if err := properties.parseLine(line); err != nil {
136 return nil, fmt.Errorf("error parsing data at line %d: %s", lineNum, err)
137 }
138 }
139
140 return properties, nil
141 }
142
143 // Load reads a properties file and makes a Map out of it.
144 func Load(filepath string) (*Map, error) {
145 bytes, err := os.ReadFile(filepath)
146 if err != nil {
147 return nil, fmt.Errorf("error reading file: %s", err)
148 }
149
150 res, err := LoadFromBytes(bytes)
151 if err != nil {
152 return nil, fmt.Errorf("error reading file: %s", err)
153 }
154 return res, nil
155 }
156
157 // LoadFromPath reads a properties file and makes a Map out of it.
158 func LoadFromPath(path *paths.Path) (*Map, error) {
159 return Load(path.String())
160 }
161
162 // LoadFromSlice reads a properties file from an array of string
163 // and makes a Map out of it
164 func LoadFromSlice(lines []string) (*Map, error) {
165 properties := NewMap()
166
167 for lineNum, line := range lines {
168 if err := properties.parseLine(line); err != nil {
169 return nil, fmt.Errorf("error reading from slice (index:%d): %s", lineNum, err)
170 }
171 }
172
173 return properties, nil
174 }
175
176 func (m *Map) parseLine(line string) error {
177 line = strings.TrimSpace(line)
178
179 // Skip empty lines or comments
180 if len(line) == 0 || line[0] == '#' {
181 return nil
182 }
183
184 lineParts := strings.SplitN(line, "=", 2)
185 if len(lineParts) != 2 {
186 return fmt.Errorf("invalid line format, should be 'key=value'")
187 }
188 key := strings.TrimSpace(lineParts[0])
189 value := strings.TrimSpace(lineParts[1])
190
191 key = strings.Replace(key, "."+osSuffix, "", 1)
192 m.Set(key, value)
193
194 return nil
195 }
196
197 // SafeLoadFromPath is like LoadFromPath, except that it returns an empty Map if
198 // the specified file doesn't exist
199 func SafeLoadFromPath(path *paths.Path) (*Map, error) {
200 return SafeLoad(path.String())
201 }
202
203 // SafeLoad is like Load, except that it returns an empty Map if the specified
204 // file doesn't exist
205 func SafeLoad(filepath string) (*Map, error) {
206 _, err := os.Stat(filepath)
207 if os.IsNotExist(err) {
208 return NewMap(), nil
209 }
210
211 properties, err := Load(filepath)
212 if err != nil {
213 return nil, err
214 }
215 return properties, nil
216 }
217
218 // Get retrieves the value corresponding to key
219 func (m *Map) Get(key string) string {
220 return m.kv[key]
221 }
222
223 // GetOk retrieves the value corresponding to key and returns a true/false indicator
224 // to check if the key is present in the map (true if the key is present)
225 func (m *Map) GetOk(key string) (string, bool) {
226 v, ok := m.kv[key]
227 return v, ok
228 }
229
230 // ContainsKey returns true if the map contains the specified key
231 func (m *Map) ContainsKey(key string) bool {
232 _, has := m.kv[key]
233 return has
234 }
235
236 // ContainsValue returns true if the map contains the specified value
237 func (m *Map) ContainsValue(value string) bool {
238 for _, v := range m.kv {
239 if v == value {
240 return true
241 }
242 }
243 return false
244 }
245
246 // Set inserts or replaces an existing key-value pair in the map
247 func (m *Map) Set(key, value string) {
248 if _, has := m.kv[key]; has {
249 m.Remove(key)
250 }
251 m.kv[key] = value
252 m.o = append(m.o, key)
253 }
254
255 // Size returns the number of elements in the map
256 func (m *Map) Size() int {
257 return len(m.kv)
258 }
259
260 // Remove removes the key from the map
261 func (m *Map) Remove(key string) {
262 delete(m.kv, key)
263 for i, k := range m.o {
264 if k == key {
265 m.o = append(m.o[:i], m.o[i+1:]...)
266 return
267 }
268 }
269 }
270
271 // FirstLevelOf generates a map-of-Maps using the first level of the hierarchy
272 // of the current Map. For example the following Map:
273 //
274 // properties.Map{
275 // "uno.name": "Arduino/Genuino Uno",
276 // "uno.upload.tool": "avrdude",
277 // "uno.upload.protocol": "arduino",
278 // "uno.upload.maximum_size": "32256",
279 // "diecimila.name": "Arduino Duemilanove or Diecimila",
280 // "diecimila.upload.tool": "avrdude",
281 // "diecimila.upload.protocol": "arduino",
282 // "diecimila.bootloader.tool": "avrdude",
283 // "diecimila.bootloader.low_fuses": "0xFF",
284 // }
285 //
286 // is transformed into the following map-of-Maps:
287 //
288 // map[string]Map{
289 // "uno" : properties.Map{
290 // "name": "Arduino/Genuino Uno",
291 // "upload.tool": "avrdude",
292 // "upload.protocol": "arduino",
293 // "upload.maximum_size": "32256",
294 // },
295 // "diecimila" : properties.Map{
296 // "name": "Arduino Duemilanove or Diecimila",
297 // "upload.tool": "avrdude",
298 // "upload.protocol": "arduino",
299 // "bootloader.tool": "avrdude",
300 // "bootloader.low_fuses": "0xFF",
301 // }
302 // }
303 func (m *Map) FirstLevelOf() map[string]*Map {
304 newMap := make(map[string]*Map)
305 for _, key := range m.o {
306 if !strings.Contains(key, ".") {
307 continue
308 }
309 keyParts := strings.SplitN(key, ".", 2)
310 if newMap[keyParts[0]] == nil {
311 newMap[keyParts[0]] = NewMap()
312 }
313 value := m.kv[key]
314 newMap[keyParts[0]].Set(keyParts[1], value)
315 }
316 return newMap
317 }
318
319 // FirstLevelKeys returns the keys in the first level of the hierarchy
320 // of the current Map. For example the following Map:
321 //
322 // properties.Map{
323 // "uno.name": "Arduino/Genuino Uno",
324 // "uno.upload.tool": "avrdude",
325 // "uno.upload.protocol": "arduino",
326 // "uno.upload.maximum_size": "32256",
327 // "diecimila.name": "Arduino Duemilanove or Diecimila",
328 // "diecimila.upload.tool": "avrdude",
329 // "diecimila.upload.protocol": "arduino",
330 // "diecimila.bootloader.tool": "avrdude",
331 // "diecimila.bootloader.low_fuses": "0xFF",
332 // }
333 //
334 // will produce the following result:
335 //
336 // []string{
337 // "uno",
338 // "diecimila",
339 // }
340 //
341 // the order of the original map is preserved
342 func (m *Map) FirstLevelKeys() []string {
343 res := []string{}
344 taken := map[string]bool{}
345 for _, k := range m.o {
346 first := strings.SplitN(k, ".", 2)[0]
347 if taken[first] {
348 continue
349 }
350 taken[first] = true
351 res = append(res, first)
352 }
353 return res
354 }
355
356 // SubTree extracts a sub Map from an existing map using the first level
357 // of the keys hierarchy as selector.
358 // For example the following Map:
359 //
360 // properties.Map{
361 // "uno.name": "Arduino/Genuino Uno",
362 // "uno.upload.tool": "avrdude",
363 // "uno.upload.protocol": "arduino",
364 // "uno.upload.maximum_size": "32256",
365 // "diecimila.name": "Arduino Duemilanove or Diecimila",
366 // "diecimila.upload.tool": "avrdude",
367 // "diecimila.upload.protocol": "arduino",
368 // "diecimila.bootloader.tool": "avrdude",
369 // "diecimila.bootloader.low_fuses": "0xFF",
370 // }
371 //
372 // after calling SubTree("uno") will be transformed into:
373 //
374 // properties.Map{
375 // "name": "Arduino/Genuino Uno",
376 // "upload.tool": "avrdude",
377 // "upload.protocol": "arduino",
378 // "upload.maximum_size": "32256",
379 // },
380 func (m *Map) SubTree(rootKey string) *Map {
381 rootKey += "."
382 newMap := NewMap()
383 for _, key := range m.o {
384 if !strings.HasPrefix(key, rootKey) {
385 continue
386 }
387 value := m.kv[key]
388 newMap.Set(key[len(rootKey):], value)
389 }
390 return newMap
391 }
392
393 // ExpandPropsInString uses the Map to replace values into a format string.
394 // The format string should contains markers between braces, for example:
395 //
396 // "The selected upload protocol is {upload.protocol}."
397 //
398 // Each marker is replaced by the corresponding value of the Map.
399 // The values in the Map may contain other markers, they are evaluated
400 // recursively up to 10 times.
401 func (m *Map) ExpandPropsInString(str string) string {
402 return m.expandProps(str, false)
403 }
404
405 // IsPropertyMissingInExpandPropsInString checks if a property 'prop' is missing
406 // when the ExpandPropsInString method is applied to the input string 'str'.
407 // This method returns false if the 'prop' is defined in the map
408 // or if 'prop' is not used in the string expansion of 'str', otherwise
409 // the method returns true.
410 func (m *Map) IsPropertyMissingInExpandPropsInString(prop, str string) bool {
411 if m.ContainsKey(prop) {
412 return false
413 }
414
415 xm := m.Clone()
416
417 // Find a random tag that is not contained in the dictionary and the src pattern
418 var token string
419 for {
420 token = fmt.Sprintf("%d", rand.Int63())
421 if strings.Contains(str, token) {
422 continue
423 }
424 if xm.ContainsKey(token) {
425 continue
426 }
427 if xm.ContainsValue(token) {
428 continue
429 }
430 break
431 }
432 xm.Set(prop, token)
433
434 res := xm.expandProps(str, false)
435 return strings.Contains(res, token)
436 }
437
438 // Merge merges other Maps into this one. Each key/value of the merged Maps replaces
439 // the key/value present in the original Map.
440 func (m *Map) Merge(sources ...*Map) *Map {
441 for _, source := range sources {
442 for _, key := range source.o {
443 value := source.kv[key]
444 m.Set(key, value)
445 }
446 }
447 return m
448 }
449
450 // Keys returns an array of the keys contained in the Map
451 func (m *Map) Keys() []string {
452 keys := make([]string, len(m.o))
453 copy(keys, m.o)
454 return keys
455 }
456
457 // IterKeys return a range-iterator over the keys of the Map in insertion order.
458 func (m *Map) IterKeys() iter.Seq[string] {
459 return func(yield func(string) bool) {
460 for _, key := range m.o {
461 if !yield(key) {
462 return
463 }
464 }
465 }
466 }
467
468 // Values returns an array of the values contained in the Map. Duplicated
469 // values are repeated in the list accordingly.
470 func (m *Map) Values() []string {
471 values := make([]string, len(m.o))
472 for i, key := range m.o {
473 values[i] = m.kv[key]
474 }
475 return values
476 }
477
478 // IterValues return a range-iterator over the values of the Map in insertion order.
479 func (m *Map) IterValues() iter.Seq[string] {
480 return func(yield func(string) bool) {
481 for _, key := range m.o {
482 if !yield(m.kv[key]) {
483 return
484 }
485 }
486 }
487 }
488
489 // AsMap returns the underlying map[string]string. This is useful if you need to
490 // for ... range but without the requirement of the ordered elements.
491 //
492 // Deprecated: Use IterMap() if you want to iterate without copy. Use CloneAsMap() if you want a copy of the Map as a golang map.
493 func (m *Map) AsMap() map[string]string {
494 return m.kv
495 }
496
497 // IterMap return a range-iterator over the key/value pairs of the Map in insertion order.
498 func (m *Map) IterMap() iter.Seq2[string, string] {
499 return func(yield func(string, string) bool) {
500 for _, key := range m.o {
501 if !yield(key, m.kv[key]) {
502 return
503 }
504 }
505 }
506 }
507
508 // AsSlice returns the underlying map[string]string as a slice of
509 // strings with the pattern `{key}={value}`, maintaining the insertion order of the keys.
510 func (m *Map) AsSlice() []string {
511 properties := make([]string, len(m.o))
512 for i, key := range m.o {
513 properties[i] = strings.Join([]string{key, m.kv[key]}, "=")
514 }
515 return properties
516 }
517
518 // Clone makes a copy of the Map
519 func (m *Map) Clone() *Map {
520 clone := NewMap()
521 clone.Merge(m)
522 return clone
523 }
524
525 // CloneAsMap makes a copy of the Map and returns it as a golang map[string]string.
526 func (m *Map) CloneAsMap() map[string]string {
527 clone := map[string]string{}
528 maps.Copy(clone, m.kv)
529 return clone
530 }
531
532 // Equals returns true if the current Map contains the same key/value pairs of
533 // the Map passed as argument, the order of insertion does not matter.
534 func (m *Map) Equals(other *Map) bool {
535 return reflect.DeepEqual(m.kv, other.kv)
536 }
537
538 // EqualsWithOrder returns true if the current Map contains the same key/value pairs of
539 // the Map passed as argument with the same order of insertion.
540 func (m *Map) EqualsWithOrder(other *Map) bool {
541 return reflect.DeepEqual(m.o, other.o) && reflect.DeepEqual(m.kv, other.kv)
542 }
543
544 // MergeMapsOfProperties merges the map-of-Maps (obtained from the method FirstLevelOf()) into the
545 // target map-of-Maps.
546 func MergeMapsOfProperties(target map[string]*Map, sources ...map[string]*Map) map[string]*Map {
547 for _, source := range sources {
548 maps.Copy(target, source)
549 }
550 return target
551 }
552
553 // DeleteUnexpandedPropsFromString removes all the brace markers "{xxx}" that are not expanded
554 // into a value using the Map.ExpandPropsInString() method.
555 func DeleteUnexpandedPropsFromString(str string) string {
556 rxp := regexp.MustCompile(`\{.+?\}`)
557 return rxp.ReplaceAllString(str, "")
558 }
559
560 // ExtractSubIndexSets works like SubTree but it considers also the numeric sub index in the form
561 // `root.N.xxx...` as separate subsets.
562 // For example the following Map:
563 //
564 // properties.Map{
565 // "uno.upload_port.vid": "0x1000",
566 // "uno.upload_port.pid": "0x2000",
567 // "due.upload_port.0.vid": "0x1000",
568 // "due.upload_port.0.pid": "0x2000",
569 // "due.upload_port.1.vid": "0x1001",
570 // "due.upload_port.1.pid": "0x2001",
571 // "tre.upload_port.1.vid": "0x1001",
572 // "tre.upload_port.1.pid": "0x2001",
573 // "tre.upload_port.2.vid": "0x1002",
574 // "tre.upload_port.2.pid": "0x2002",
575 // }
576 //
577 // calling ExtractSubIndexSets("uno.upload_port") returns the array:
578 //
579 // [ properties.Map{
580 // "vid": "0x1000",
581 // "pid": "0x2000",
582 // },
583 // ]
584 //
585 // calling ExtractSubIndexSets("due.upload_port") returns the array:
586 //
587 // [ properties.Map{
588 // "vid": "0x1000",
589 // "pid": "0x2000",
590 // },
591 // properties.Map{
592 // "vid": "0x1001",
593 // "pid": "0x2001",
594 // },
595 // ]
596 //
597 // the sub-index may start with .1 too, so calling ExtractSubIndexSets("tre.upload_port") returns:
598 //
599 // [ properties.Map{
600 // "vid": "0x1001",
601 // "pid": "0x2001",
602 // },
603 // properties.Map{
604 // "vid": "0x1002",
605 // "pid": "0x2002",
606 // },
607 // ]
608 //
609 // Numeric subindex cannot be mixed with non-numeric, in that case only the numeric sub
610 // index sets will be returned.
611 func (m *Map) ExtractSubIndexSets(root string) []*Map {
612 res := []*Map{}
613 portIDPropsSet := m.SubTree(root)
614 if portIDPropsSet.Size() == 0 {
615 return res
616 }
617
618 // First check the properties with numeric sub index "root.N.xxx"
619 idx := 0
620 haveIndexedProperties := false
621 for {
622 idProps := portIDPropsSet.SubTree(fmt.Sprintf("%d", idx))
623 idx++
624 if idProps.Size() > 0 {
625 haveIndexedProperties = true
626 res = append(res, idProps)
627 } else if idx > 1 {
628 // Always check sub-id 0 and 1 (https://github.com/arduino/arduino-cli/issues/456)
629 break
630 }
631 }
632
633 // if there are no subindexed then return the whole "roox.xxx" subtree
634 if !haveIndexedProperties {
635 res = append(res, portIDPropsSet)
636 }
637
638 return res
639 }
640
641 // ExtractSubIndexLists extracts a list of arguments from a root `root.N=...`.
642 // For example the following Map:
643 //
644 // properties.Map{
645 // "uno.discovery.required": "item",
646 // "due.discovery.required.0": "item1",
647 // "due.discovery.required.1": "item2",
648 // "due.discovery.required.2": "item3",
649 // "tre.discovery.required.1": "itemA",
650 // "tre.discovery.required.2": "itemB",
651 // "tre.discovery.required.3": "itemC",
652 // "quattro.discovery.required.1": "itemA",
653 // "quattro.discovery.required.4": "itemB",
654 // "quattro.discovery.required.5": "itemC",
655 // }
656 //
657 // calling ExtractSubIndexLists("uno.discovery.required") returns the array:
658 //
659 // [ "item" ]
660 //
661 // calling ExtractSubIndexLists("due.discovery.required") returns the array:
662 //
663 // [ "item1", "item2", "item3" ]
664 //
665 // the sub-index may start with .1 too, so calling ExtractSubIndexLists("tre.discovery.required") returns:
666 //
667 // [ "itemA", "itemB", "itemC" ]
668 //
669 // also the list may contains holes, so calling ExtractSubIndexLists("quattro.discovery.required") returns:
670 //
671 // [ "itemA", "itemB", "itemC" ]
672 //
673 // Numeric subindex cannot be mixed with non-numeric, in that case only the numeric sub
674 // index sets will be returned.
675 func (m *Map) ExtractSubIndexLists(root string) []string {
676 isNotDigit := func(in string) bool {
677 for _, r := range in {
678 if r < '0' || r > '9' {
679 return true
680 }
681 }
682 return false
683 }
684
685 // Extract numeric keys
686 subProps := m.SubTree(root)
687 indexes := []int{}
688 for _, key := range subProps.o {
689 if isNotDigit(key) {
690 continue
691 }
692 if idx, err := strconv.Atoi(key); err == nil {
693 indexes = append(indexes, idx)
694 }
695 }
696 sort.Ints(indexes)
697
698 res := []string{}
699 haveIndexedProperties := false
700 for i, idx := range indexes {
701 if i > 0 && idx == indexes[i-1] {
702 // de-duplicate cases like "05" and "5"
703 continue
704 }
705 if v, ok := subProps.GetOk(strconv.Itoa(idx)); ok {
706 haveIndexedProperties = true
707 res = append(res, v)
708 }
709 }
710
711 // if there are no subindexed then return the whole "roox.xxx" subtree
712 if !haveIndexedProperties {
713 if value, ok := m.GetOk(root); ok {
714 res = append(res, value)
715 }
716 }
717
718 return res
719 }