dir2yaml 837 B

1234567891011121314151617181920212223242526272829303132333435363738
  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 load_dir(dir_name):
  10. if not os.path.isdir(dir_name):
  11. die("{0} is not a directory", dir_name)
  12. else:
  13. return dict((path, load_elem(os.path.join(dir_name, path)))
  14. for path in os.listdir(dir_name) if path[0] != '.')
  15. def load_elem(path):
  16. if os.path.isdir(path):
  17. return load_dir(path)
  18. else:
  19. with open(path) as f:
  20. content = f.read()
  21. try:
  22. return json.loads(content)
  23. except ValueError:
  24. return content.strip()
  25. if __name__ == '__main__':
  26. if sys.argv[1:]:
  27. dir_name = sys.argv[1]
  28. else:
  29. dir_name = os.getcwd()
  30. yaml.dump(load_dir(dir_name), sys.stdout)