Debian Codegraph @

brian2/utils/filetools.py

raw
1 """
2 File system tools
3 """
4
5 import os
6
7 __all__ = [
8 "ensure_directory",
9 "ensure_directory_of_file",
10 "in_directory",
11 "copy_directory",
12 ]
13
14
15 def ensure_directory_of_file(f):
16 """
17 Ensures that a directory exists for filename to go in (creates if
18 necessary), and returns the directory path.
19 """
20 d = os.path.dirname(f)
21 if not os.path.exists(d):
22 os.makedirs(d)
23 return d
24
25
26 def ensure_directory(d):
27 """
28 Ensures that a given directory exists (creates it if necessary)
29 """
30 if not os.path.exists(d):
31 os.makedirs(d)
32 return d
33
34
35 class in_directory:
36 """
37 Safely temporarily work in a subdirectory
38
39 Usage::
40
41 with in_directory(directory):
42 ... do stuff here
43
44 Guarantees that the code in the with block will be executed in directory,
45 and that after the block is completed we return to the original directory.
46 """
47
48 def __init__(self, new_dir):
49 self.orig_dir = os.getcwd()
50 self.new_dir = new_dir
51
52 def __enter__(self):
53 os.chdir(self.new_dir)
54
55 def __exit__(self, *exc_info):
56 os.chdir(self.orig_dir)
57
58
59 def copy_directory(source, target):
60 """
61 Copies directory source to target.
62 """
63 relnames = []
64 sourcebase = os.path.normpath(source) + os.path.sep
65 for root, _, filenames in os.walk(source):
66 for filename in filenames:
67 fullname = os.path.normpath(os.path.join(root, filename))
68 relname = fullname.replace(sourcebase, "")
69 relnames.append(relname)
70 tgtname = os.path.join(target, relname)
71 ensure_directory_of_file(tgtname)
72 with open(fullname) as f:
73 contents = f.read()
74 if os.path.exists(tgtname):
75 with open(tgtname) as f:
76 if f.read() == contents:
77 continue
78 with open(tgtname, "w") as f:
79 f.write(contents)
80 return relnames