clean_rosdep_yaml.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python
  2. import yaml
  3. import argparse
  4. import re
  5. import io
  6. dont_bracket = ['uri', 'md5sum']
  7. def paddify(s, l):
  8. a = s.split('\n')
  9. buf = ''
  10. pad = ' ' * l
  11. for i, r in enumerate(a[:-1]):
  12. buf += "%s%s\n" % (pad, r)
  13. return buf
  14. def quote_if_necessary(s):
  15. if type(s) is list:
  16. return [quote_if_necessary(a) for a in s]
  17. return re.search('a: (.*)\n', yaml.dump({'a': s})).group(1)
  18. def prn(n, nm, lvl):
  19. if nm == '*':
  20. # quote wildcard keys
  21. nm = "'*'"
  22. else:
  23. # quote numeric keys
  24. try:
  25. nm_int = int(nm)
  26. except ValueError:
  27. pass
  28. else:
  29. if str(nm_int) == nm:
  30. nm = "'%d'" % nm_int
  31. pad = ' ' * lvl
  32. if isinstance(n, list):
  33. return "%s%s: [%s]\n" % (pad, nm, ', '.join(quote_if_necessary(n)))
  34. elif n is None:
  35. return "%s%s: %s\n" % (pad, nm, 'null')
  36. elif isinstance(n, str):
  37. if len(n.split('\n')) > 1:
  38. return "%s%s: |\n%s" % (pad, nm, paddify(n, lvl+1))
  39. else:
  40. if nm in dont_bracket:
  41. return "%s%s: %s\n" % (pad, nm, quote_if_necessary(n))
  42. return "%s%s: [%s]\n" % (pad, nm, ', '.join(quote_if_necessary(n.split())))
  43. buf = "%s%s:\n" % (pad, nm)
  44. for a in sorted(n.keys()):
  45. buf += prn(n[a], a, lvl+1)
  46. return buf
  47. if __name__ == '__main__':
  48. parser = argparse.ArgumentParser(
  49. description='Cleans a rosdep YAML file to a correct format')
  50. parser.add_argument('infile', help='input rosdep YAML file')
  51. parser.add_argument('outfile', help='output YAML file to be written')
  52. args = parser.parse_args()
  53. with open(args.infile) as f:
  54. iny = yaml.safe_load(f.read())
  55. buf = ''
  56. for a in sorted(iny):
  57. buf += prn(iny[a], a, 0)
  58. with io.open(args.outfile, 'wb') as f:
  59. f.write(buf.encode('utf-8'))