Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" Dictionary-to-filetree functions, to create test files for testing. 

2 http://nedbatchelder.com/code/cog 

3 

4 Copyright 2004-2019, Ned Batchelder. 

5""" 

6 

7from __future__ import absolute_import 

8 

9import os.path 

10 

11from .backward import string_types, bytes_types 

12from .whiteutils import reindentBlock 

13 

14__all__ = ['makeFiles', 'removeFiles'] 

15 

16def makeFiles(d, basedir='.', bytes=False): 

17 """ Create files from the dictionary `d`, in the directory named by `basedir`. 

18 If `bytes` is true, then treat bytestrings as bytes, else as text. 

19 """ 

20 for name, contents in d.items(): 

21 child = os.path.join(basedir, name) 

22 if isinstance(contents, string_types): 

23 mode = 'w' 

24 if bytes and isinstance(contents, bytes_types): 

25 mode += "b" 

26 f = open(child, mode) 

27 contents = reindentBlock(contents) 

28 f.write(contents) 

29 f.close() 

30 else: 

31 if not os.path.exists(child): 

32 os.mkdir(child) 

33 makeFiles(contents, child) 

34 

35def removeFiles(d, basedir='.'): 

36 """ Remove the files created by makeFiles. 

37 Directories are removed if they are empty. 

38 """ 

39 for name, contents in d.items(): 

40 child = os.path.join(basedir, name) 

41 if isinstance(contents, string_types): 

42 os.remove(child) 

43 else: 

44 removeFiles(contents, child) 

45 if not os.listdir(child): 

46 os.rmdir(child)