1import os 2 3 4from setuptools.extern.six import binary_type 5import pkg_resources.py31compat 6 7 8def build_files(file_defs, prefix=""): 9 """ 10 Build a set of files/directories, as described by the file_defs dictionary. 11 12 Each key/value pair in the dictionary is interpreted as a filename/contents 13 pair. If the contents value is a dictionary, a directory is created, and the 14 dictionary interpreted as the files within it, recursively. 15 16 For example: 17 18 {"README.txt": "A README file", 19 "foo": { 20 "__init__.py": "", 21 "bar": { 22 "__init__.py": "", 23 }, 24 "baz.py": "# Some code", 25 } 26 } 27 """ 28 for name, contents in file_defs.items(): 29 full_name = os.path.join(prefix, name) 30 if isinstance(contents, dict): 31 pkg_resources.py31compat.makedirs(full_name, exist_ok=True) 32 build_files(contents, prefix=full_name) 33 else: 34 if isinstance(contents, binary_type): 35 with open(full_name, 'wb') as f: 36 f.write(contents) 37 else: 38 with open(full_name, 'w') as f: 39 f.write(contents) 40