/
paths.py
254 lines (190 loc) · 6.58 KB
/
paths.py
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""
Utility functions for loading andes stock test cases
"""
import os
import tempfile
import pathlib
import logging
logger = logging.getLogger(__name__)
class DisplayablePath:
display_filename_prefix_middle = '├──'
display_filename_prefix_last = '└──'
display_parent_prefix_middle = ' '
display_parent_prefix_last = '│ '
def __init__(self, path, parent_path, is_last):
self.path = pathlib.Path(str(path))
self.parent = parent_path
self.is_last = is_last
if self.parent:
self.depth = self.parent.depth + 1
else:
self.depth = 0
@property
def displayname(self):
if self.path.is_dir():
return self.path.name + '/'
return self.path.name
@classmethod
def make_tree(cls, root, parent=None, is_last=False, criteria=None):
root = pathlib.Path(str(root))
criteria = criteria or cls._default_criteria
displayable_root = cls(root, parent, is_last)
yield displayable_root
children = sorted(list(path
for path in root.iterdir()
if criteria(path)),
key=lambda s: str(s).lower())
count = 1
for path in children:
is_last = count == len(children)
if path.is_dir():
yield from cls.make_tree(path,
parent=displayable_root,
is_last=is_last,
criteria=criteria)
else:
yield cls(path, displayable_root, is_last)
count += 1
@classmethod
def _default_criteria(cls, path):
return True
def displayable(self):
if self.parent is None:
return self.displayname
_filename_prefix = (self.display_filename_prefix_last
if self.is_last
else self.display_filename_prefix_middle)
parts = ['{!s} {!s}'.format(_filename_prefix,
self.displayname)]
parent = self.parent
while parent and parent.parent is not None:
parts.append(self.display_parent_prefix_middle
if parent.is_last
else self.display_parent_prefix_last)
parent = parent.parent
return ''.join(reversed(parts))
def andes_root():
"""
Return the root path to the andes source code.
"""
dir_name = os.path.dirname(os.path.abspath(__file__))
return os.path.normpath(os.path.join(dir_name, '..'))
def cases_root():
"""
Return the root path to the stock cases
"""
dir_name = os.path.dirname(os.path.abspath(__file__))
return os.path.normpath(os.path.join(dir_name, '..', 'cases'))
def tests_root():
"""Return the root path to the stock cases"""
dir_name = os.path.dirname(os.path.abspath(__file__))
return os.path.normpath(os.path.join(dir_name, '..', '..', 'tests'))
def get_case(rpath, check=True):
"""
Return the path to a stock case for a given path relative to ``andes/cases``.
To list all cases, use ``andes.list_cases()``.
Parameters
----------
check : bool
True to check if file exists
Examples
--------
To get the path to the case `kundur_full.xlsx` under folder `kundur`, do ::
andes.get_case('kundur/kundur_full.xlsx')
"""
case_path = os.path.join(cases_root(), rpath)
case_path = os.path.normpath(case_path)
if check is True and (not os.path.isfile(case_path)):
raise FileNotFoundError(f'"{rpath}" is not a valid relative path to a stock case.')
return case_path
def list_cases(rpath='.', no_print=False):
"""
List stock cases under a given folder relative to ``andes/cases``
"""
case_path = os.path.join(cases_root(), rpath)
case_path = os.path.normpath(case_path)
tree = DisplayablePath.make_tree(pathlib.Path(case_path))
out = []
for path in tree:
out.append(path.displayable())
out = '\n'.join(out)
if no_print is False:
print(out)
else:
return out
def get_config_path(file_name='andes.rc'):
"""
Return the path of the config file to be loaded.
Search Priority: 1. current directory; 2. home directory.
Parameters
----------
file_name : str, optional
Config file name with the default as ``andes.rc``.
Returns
-------
Config path in string if found; None otherwise.
"""
conf_path = None
home_dir = os.path.expanduser('~')
# test ./andes.conf
if os.path.isfile(file_name):
conf_path = file_name
# test ~/andes.conf
elif os.path.isfile(os.path.join(home_dir, '.andes', file_name)):
conf_path = os.path.join(home_dir, '.andes', file_name)
return conf_path
def get_pycode_path(pycode_path=None, mkdir=False):
"""
Get the path to the ``pycode`` folder.
"""
if pycode_path is None:
pycode_path = os.path.join(get_dot_andes_path(), 'pycode')
if mkdir is True:
os.makedirs(pycode_path, exist_ok=True)
return pycode_path
def get_pkl_path():
"""
Get the path to the picked/dilled function calls.
Returns
-------
str
Path to the calls.pkl file
"""
pkl_name = 'calls.pkl'
andes_path = get_dot_andes_path()
if not os.path.exists(andes_path):
os.makedirs(andes_path)
pkl_path = os.path.join(andes_path, pkl_name)
return pkl_path
def get_dot_andes_path():
"""
Return the path to ``<HomeDir>/.andes``
"""
return os.path.join(str(pathlib.Path.home()), '.andes')
def get_log_dir():
"""
Get the directory for log file.
The default is ``<tempdir>/andes``, where ``<tempdir>`` is provided by ``tempfile.gettempdir()``.
Returns
-------
str
The path to the temporary logging directory
"""
tempdir = os.path.join(tempfile.gettempdir(), 'andes')
if not os.path.exists(tempdir):
os.mkdir(tempdir)
path = tempfile.mkdtemp(prefix='andes-', dir=tempdir)
return path
def confirm_overwrite(outfile, overwrite=None):
try:
if os.path.isfile(outfile):
if overwrite is None:
choice = input(f'File "{outfile}" already exist. Overwrite? [y/N]').lower()
if len(choice) == 0 or choice[0] != 'y':
logger.warning(f'File "{outfile}" not overwritten.')
return False
elif overwrite is False:
return False
except TypeError:
pass
return True