File: makefiles.py

package info (click to toggle)
python-cogapp 3.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 332 kB
  • sloc: python: 3,081; makefile: 55
file content (36 lines) | stat: -rw-r--r-- 1,117 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
""" Dictionary-to-filetree functions, to create test files for testing.
"""

import os.path

from .whiteutils import reindentBlock


def makeFiles(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(reindentBlock(contents))
        else:
            if not os.path.exists(child):
                os.mkdir(child)
            makeFiles(contents, child)

def removeFiles(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:
            removeFiles(contents, child)
            if not os.listdir(child):
                os.rmdir(child)