dt-extract-compatibles 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. import fnmatch
  4. import os
  5. import re
  6. import argparse
  7. def parse_of_declare_macros(data):
  8. """ Find all compatible strings in OF_DECLARE() style macros """
  9. compat_list = []
  10. # CPU_METHOD_OF_DECLARE does not have a compatible string
  11. for m in re.finditer(r'(?<!CPU_METHOD_)(IRQCHIP|OF)_(DECLARE|MATCH)(_DRIVER)?\(.*?\)', data):
  12. try:
  13. compat = re.search(r'"(.*?)"', m[0])[1]
  14. except:
  15. # Fails on compatible strings in #define, so just skip
  16. continue
  17. compat_list += [compat]
  18. return compat_list
  19. def parse_of_device_id(data):
  20. """ Find all compatible strings in of_device_id structs """
  21. compat_list = []
  22. for m in re.finditer(r'of_device_id\s+[a-zA-Z0-9_]+\[\]\s*=\s*({.*?);', data):
  23. compat_list += re.findall(r'\.compatible\s+=\s+"([a-zA-Z0-9_\-,]+)"', m[1])
  24. return compat_list
  25. def parse_compatibles(file):
  26. with open(file, 'r', encoding='utf-8') as f:
  27. data = f.read().replace('\n', '')
  28. compat_list = parse_of_declare_macros(data)
  29. compat_list += parse_of_device_id(data)
  30. return compat_list
  31. def print_compat(filename, compatibles):
  32. if not compatibles:
  33. return
  34. if show_filename:
  35. compat_str = ' '.join(compatibles)
  36. print(filename + ": compatible(s): " + compat_str)
  37. else:
  38. print(*compatibles, sep='\n')
  39. def glob_without_symlinks(root, glob):
  40. for path, dirs, files in os.walk(root):
  41. # Ignore hidden directories
  42. for d in dirs:
  43. if fnmatch.fnmatch(d, ".*"):
  44. dirs.remove(d)
  45. for f in files:
  46. if fnmatch.fnmatch(f, glob):
  47. yield os.path.join(path, f)
  48. def files_to_parse(path_args):
  49. for f in path_args:
  50. if os.path.isdir(f):
  51. for filename in glob_without_symlinks(f, "*.c"):
  52. yield filename
  53. else:
  54. yield f
  55. show_filename = False
  56. if __name__ == "__main__":
  57. ap = argparse.ArgumentParser()
  58. ap.add_argument("cfile", type=str, nargs='*', help="C source files or directories to parse")
  59. ap.add_argument('-H', '--with-filename', help="Print filename with compatibles", action="store_true")
  60. args = ap.parse_args()
  61. show_filename = args.with_filename
  62. for f in files_to_parse(args.cfile):
  63. compat_list = parse_compatibles(f)
  64. print_compat(f, compat_list)