nvram_prop.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env python3
  2. #
  3. # Actions NVRAM properties helper
  4. #
  5. # Copyright (c) 2017 Actions Semiconductor Co., Ltd
  6. #
  7. # SPDX-License-Identifier: Apache-2.0
  8. #
  9. import sys
  10. PROP_NAME_MAX = 127
  11. PROP_VALUE_MAX = 1023
  12. class PropFile:
  13. def __init__(self, lines):
  14. self.props = {}
  15. self.lines = [s.strip() for s in lines]
  16. self.__to_dict(self.lines)
  17. def validate_prop(self, name, value):
  18. if name == '':
  19. return False
  20. if len(name) > PROP_NAME_MAX:
  21. print('PropFile: WARNING: %s name cannot exceed %d bytes.' %
  22. (name, PROP_NAME_MAX))
  23. return False
  24. if len(value) > PROP_VALUE_MAX:
  25. print('PropFile: WARNING: %s value cannot exceed %d bytes.' %
  26. (name, PROP_VALUE_MAX))
  27. return False
  28. return True
  29. def __to_dict(self, lines):
  30. for line in lines:
  31. if not line or line.startswith("#"):
  32. continue
  33. if "=" in line:
  34. key, value = line.split("=", 1)
  35. self.set(key, value)
  36. def get_all(self):
  37. return self.props
  38. def get(self, name):
  39. if name in self.props:
  40. return self.props[name]
  41. return ''
  42. def set(self, name, value):
  43. name = name.strip()
  44. value = value.strip()
  45. if self.validate_prop(name, value):
  46. self.props[name] = value
  47. def delete(self, name):
  48. self.props.pop(name)
  49. def write(self, filename):
  50. with open(filename, 'w') as f:
  51. for key, value in self.props.items():
  52. f.write(key + '=' + value + '\n')
  53. f.write('\n')