gdritter repos GRUtils / master scripts / dir2yaml
master

Tree @master (Download .tar.gz)

dir2yaml @masterraw · history · blame

#!/usr/bin/python

import os
import sys
import json
import yaml


def die(msg, *args):
    sys.stderr.write(msg + '\n', *args)
    sys.exit(99)


def load_dir(dir_name):
    if not os.path.isdir(dir_name):
        die("{0} is not a directory", dir_name)
    else:
        return dict((path, load_elem(os.path.join(dir_name, path)))
                    for path in os.listdir(dir_name) if path[0] != '.')


def load_elem(path):
    if os.path.isdir(path):
        return load_dir(path)
    else:
        with open(path) as f:
            content = f.read()
        try:
            return json.loads(content)
        except ValueError:
            return content.strip()

if __name__ == '__main__':
    if sys.argv[1:]:
        dir_name = sys.argv[1]
    else:
        dir_name = os.getcwd()
    yaml.dump(load_dir(dir_name), sys.stdout)