File: makefiles.py

package info (click to toggle)
python-cogapp 3.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 388 kB
  • sloc: python: 3,449; makefile: 79
file content (37 lines) | stat: -rw-r--r-- 1,114 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"""Dictionary-to-filetree functions, to create test files for testing."""

import os.path

from .whiteutils import reindent_block


def make_files(d, basedir="."):
    """Create files from the dictionary `d` in the directory named by `basedir`."""
    for name, contents in d.items():
        child = os.path.join(basedir, name)
        if isinstance(contents, (bytes, str)):
            mode = "w"
            if isinstance(contents, bytes):
                mode += "b"
            with open(child, mode) as f:
                f.write(reindent_block(contents))
        else:
            if not os.path.exists(child):
                os.mkdir(child)
            make_files(contents, child)


def remove_files(d, basedir="."):
    """Remove the files created by `makeFiles`.

    Directories are removed if they are empty.

    """
    for name, contents in d.items():
        child = os.path.join(basedir, name)
        if isinstance(contents, (bytes, str)):
            os.remove(child)
        else:
            remove_files(contents, child)
            if not os.listdir(child):
                os.rmdir(child)