fix_cocci_output.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env python
  2. import sys
  3. import re
  4. # XXX Could be something else, like a file.
  5. output = sys.stdout
  6. def get_indentation_level(s):
  7. cnt = 0
  8. for c in s:
  9. if c != '\t':
  10. return -1
  11. cnt = cnt + 1
  12. return cnt
  13. def fix(f):
  14. modes = {}
  15. trailing_comma = False
  16. indentation_level = -1
  17. for line in f.readlines():
  18. # This regexp could be more precise, but it should be good
  19. # enough
  20. regexp = "((\s)*)\.modes\[(\d)+\](\s)*=(\s)*(.*)"
  21. m = re.search(regexp, line)
  22. if not m:
  23. if modes:
  24. output.write("".join(["\t" for i in range(indentation_level)]))
  25. output.write(".modes = { ")
  26. idx = 0
  27. while modes.get(str(idx)):
  28. if idx != 0:
  29. output.write(", ")
  30. output.write(modes[str(idx)])
  31. idx = idx+1
  32. if trailing_comma:
  33. output.write(" },\n")
  34. else:
  35. output.write(" }\n")
  36. # Resetting these..
  37. modes.clear()
  38. trailing_comma = False
  39. indentation_level = -1
  40. output.write(line)
  41. else:
  42. idx = m.group(3)
  43. mode = m.group(6)
  44. # Remove traling comma
  45. if mode[-1] == ',':
  46. mode = mode[:-1]
  47. # This is the last mode for this
  48. # codelet. Was this also the last
  49. # field ?
  50. if int(idx) == 0:
  51. trailing_comma = True
  52. # Try and guess the level of indentation
  53. if int(idx) == 0:
  54. s = m.group(1)
  55. indentation_level = get_indentation_level(s)
  56. modes[idx] = mode
  57. def fix_file(filename):
  58. with open(filename, 'r') as f:
  59. fix(f)
  60. def usage():
  61. print "%s <filename>" % sys.argv[0]
  62. sys.exit(1)
  63. if __name__ == '__main__':
  64. if len(sys.argv) != 2:
  65. usage()
  66. sys.exit(1)
  67. fix_file(sys.argv[1])