yaml2dir 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/python
  2. import os
  3. import sys
  4. import json
  5. import yaml
  6. def die(msg, *args):
  7. sys.stderr.write(msg + '\n', *args)
  8. sys.exit(99)
  9. def emit(datum, root='./'):
  10. if type(datum) is not dict:
  11. die("Unexpected type: {0} of type {1}", datum, type(datum))
  12. else:
  13. for key, val in datum.items():
  14. if type(val) is dict:
  15. new_root = os.path.join(root, key)
  16. os.makedir(new_root)
  17. emit(val, root=new_root)
  18. elif type(val) is list:
  19. die("Cannot serialize lists: {0}", datum)
  20. elif type(val) is str or type(val) is unicode:
  21. with open(os.path.join(root, key), 'w') as f:
  22. f.write(val)
  23. f.write('\n')
  24. else:
  25. with open(os.path.join(root, key), 'w') as f:
  26. json.dump(val, f)
  27. f.write('\n')
  28. if __name__ == '__main__':
  29. if sys.argv[:1] and sys.argv[1] != '-':
  30. with open(sys.argv[1]) as f:
  31. datum = yaml.load(f)
  32. else:
  33. datum = yaml.load(sys.stdin)
  34. emit(datum)