Coverage for src / file_tree / parse_tree.py: 89%

168 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-02-27 12:12 +0000

1"""Parse a string representation of a FileTree.""" 

2 

3import os.path as op 

4import re 

5import sys 

6from contextlib import contextmanager 

7from glob import glob 

8from pathlib import Path 

9from typing import Dict, List, Optional, Tuple, Union 

10from warnings import warn 

11 

12from .file_tree import FileTree 

13from .template import MISSING 

14 

15if sys.version_info > (3, 10): 

16 from importlib import metadata as importlib_metadata 

17else: 

18 import importlib_metadata 

19 

20# searching for a file-tree 

21 

22"""List of directories to look for FileTrees 

23""" 

24tree_directories = ["."] 

25 

26available_subtrees: Dict[str, Union[FileTree, str, Path]] = {} 

27 

28scanned_plugins = set() 

29 

30 

31@contextmanager 

32def extra_tree_dirs(extra_dirs): 

33 """Temporarily insert ``extra_dirs`` to the beginning of :attr:`tree_directories`. 

34 

35 :arg extra_dirs: Sequence of additional tree file directories to search. 

36 """ 

37 global tree_directories 

38 

39 old_tree_directories = list(tree_directories) 

40 

41 tree_directories = list(extra_dirs) + list(tree_directories) 

42 

43 try: 

44 yield 

45 finally: 

46 tree_directories = old_tree_directories 

47 

48 

49def scan_plugins(): 

50 """Scan plugins for filetrees.""" 

51 for ep in importlib_metadata.entry_points(group="file_tree.trees"): 

52 if ep.module in scanned_plugins: 

53 continue 

54 plugin = ep.load() 

55 plugin() 

56 scanned_plugins.add(ep.module) 

57 

58 

59def search_tree(name: str) -> Union[Path, str, FileTree]: 

60 """ 

61 Search for the file defining the specific tree. 

62 

63 Iteratively searches through the directories in ``tree_directories`` till a file named ${name}.tree is found. 

64 If not found in ``tree_directories`` the filetrees in installed python packages will be searched. 

65 

66 :param name: Name of the tree 

67 :return: string containing the filetree definition 

68 """ 

69 for directory in tree_directories: 

70 filename = op.join(directory, name) 

71 if not filename.endswith(".tree"): 

72 filename = filename + ".tree" 

73 if op.exists(filename): 

74 return Path(filename) 

75 

76 scan_plugins() 

77 

78 for ext in (".tree", ""): 

79 if name + ext in available_subtrees: 

80 return available_subtrees[name + ext] 

81 

82 raise ValueError("No file tree found for %s" % name) 

83 

84 

85def list_all_trees() -> List[str]: 

86 """Generate a list of available sub-trees. 

87 

88 Lists trees available in ``tree_directories`` (default just the current directory) and in installed file-tree plugins (e.g., `file-tree-fsl`). 

89 """ 

90 scan_plugins() 

91 trees = list(available_subtrees.keys()) 

92 for directory in tree_directories: 

93 trees.extend(op.basename(fn) for fn in glob(op.join(directory, "*.tree"))) 

94 return trees 

95 

96 

97# reading the file-tree 

98 

99 

100def read_file_tree_text(lines: List[str], top_level: Union[str, str]) -> FileTree: 

101 """Parse the provided lines to read a FileTree. 

102 

103 See :func:`add_line_to_tree` for how individual lines are parsed 

104 

105 Args: 

106 lines (List[str]): Individual lines read from a file-tree file 

107 top_level (str): top-level template 

108 

109 Returns: 

110 FileTree: tree read from the file 

111 """ 

112 tree = FileTree.empty(top_level) 

113 current: List[Tuple[int, str]] = [] 

114 to_link: List[List[str]] = [] 

115 

116 if detect_indentation_type(lines) == "mixed": 

117 warn( 

118 "Indentation in the file-tree file uses both tabs and spaces. This may lead to unexpected behavior. Please use only one type of indentation." 

119 ) 

120 

121 for line in lines: 

122 current = add_line_to_tree(tree, line, current, to_link) 

123 for keys in to_link: 

124 tree.placeholders.link(*keys) 

125 return tree 

126 

127 

128def add_line_to_tree( 

129 tree: FileTree, 

130 line: str, 

131 current: List[Tuple[int, str]], 

132 to_link: List[List[str]], 

133) -> List[Tuple[int, Optional[str]]]: 

134 """Add template or sub-tree defined on this file. 

135 

136 There are 5 options for the line: 

137 

138 1. Empty lines or those containing only comments (start with #) do nothing. 

139 2. Templates have the form " <unique part> (<short name>)" and are added as a new template (note that the <short name> is optional). 

140 3. Placeholder values have the form "<key> = <value>" and are stored as placeholder values in the tree. 

141 4. Sub-trees have the form " -><tree name> [<placeholder>=<value>,...] (<short name>)" and are added as a new sub-tree 

142 5. Linkages between placeholder values are indicated by "&LINK <placeholder>,..." 

143 

144 The parent directory of the new template or sub-tree is determined by the amount of white space. 

145 

146 Args: 

147 tree: tree containing all templates/sub-trees read so far (will be updated in place with new template or sub-tree). 

148 line: current line from the file-tree definition. 

149 current: sequence of the possible parent directories and their indentation. 

150 to_link: continuously updated list of which placeholders to link after reading tree. 

151 

152 Raises: 

153 ValueError: raised for a variety of formatting errors. 

154 

155 Returns: 

156 New sequence of the possible parent directories after reading the line 

157 """ 

158 stripped = line.split("#")[0].strip() 

159 if len(stripped) == 0: 

160 return current 

161 nspaces = line.index(stripped) 

162 parent = get_parent(nspaces, current) 

163 new_current = [(n, template) for n, template in current if n < nspaces] 

164 

165 if stripped[:2] == "->": 

166 sub_tree, short_names = read_subtree_line(stripped) 

167 tree.add_subtree(sub_tree, short_names, parent) 

168 new_current.append((nspaces, None)) 

169 elif "=" in stripped: 

170 key, value = [s.strip() for s in stripped.split("=")] 

171 if value.strip() == "<MISSING>": 

172 value = MISSING 

173 if "," in value: 

174 value = [ 

175 MISSING if v.strip() == "<MISSING>" else v.strip() 

176 for v in value.split(",") 

177 ] 

178 tree.update(inplace=True, **{key: value}) 

179 elif stripped.startswith("&LINK"): 

180 keys = [k.strip() for k in stripped[5:].split(",")] 

181 to_link.append(keys) 

182 else: 

183 if stripped[0] == "!": 

184 if nspaces != 0: 

185 raise ValueError( 

186 f"Defining a new top-level with '!' is only available at the top-level, but the line '{stripped}' is indented" 

187 ) 

188 stripped = stripped[1:] 

189 real_parent = None 

190 else: 

191 real_parent = parent 

192 unique_part, short_names = read_line(stripped) 

193 if short_names is not None and "" in short_names: 

194 short_names.remove("") 

195 template = tree.add_template(unique_part, short_names, real_parent) 

196 new_current.append((nspaces, template)) 

197 return new_current 

198 

199 

200def detect_indentation_type(lines: List[str]) -> str: 

201 """Detect the type of indentation used in the file. 

202 

203 Args: 

204 lines (List[str]): Lines from the file-tree definition 

205 

206 Returns: 

207 str: "tabs" if tabs are used, "spaces" if spaces are used, or "mixed" if there is a mix of both. 

208 """ 

209 tabs = False 

210 spaces = False 

211 for line in lines: 

212 stripped = line.split("#")[0].strip() 

213 if len(stripped) == 0: 

214 continue 

215 start = line[: line.index(stripped)] 

216 if "\t" in start: 

217 tabs = True 

218 if " " in start: 

219 spaces = True 

220 if tabs and spaces: 

221 return "mixed" 

222 elif tabs: 

223 return "tabs" 

224 elif spaces: 

225 return "spaces" 

226 else: 

227 return "no indentation" 

228 

229 

230def get_parent(nspaces: int, current: List[Tuple[int, str]]) -> str: 

231 """Determine the parent template based on the amount of whitespace. 

232 

233 Args: 

234 nspaces (int): amount of whitespace before the new line 

235 current (List[Tuple[int, str]]): sequence of possible parent directories and their indentation 

236 

237 Raises: 

238 ValueError: raised of parent is a sub-tree rather than a template 

239 ValueError: raise if number of spaces does not match any existing directory 

240 

241 Returns: 

242 str: empty string if the parent is the top-level directory; template short name otherwise 

243 """ 

244 if len(current) == 0: 

245 return "" 

246 nspaces_max = current[-1][0] 

247 if nspaces > nspaces_max: 

248 if current[-1][1] is None: 

249 raise ValueError( 

250 "Current line seems to be the child of a sub-tree, which is not supported." 

251 ) 

252 return current[-1][1] 

253 

254 for idx, (nspaces_template, _) in enumerate(current): 

255 if nspaces_template == nspaces: 

256 if idx == 0: 

257 return "" 

258 else: 

259 return current[idx - 1][1] 

260 raise ValueError( 

261 "Number of spaces of current line does not match any previous lines." 

262 ) 

263 

264 

265def check_forbidden_characters(text, characters, text_type): 

266 """ 

267 Check the text for forbidden characters. 

268 

269 Raises ValueError if one is found. 

270 

271 :param text: string with the text 

272 :param characters: sequence of forbidden characters 

273 :param text_type: type of the text to raise in error message 

274 """ 

275 bad = [character for character in characters if character in text] 

276 if len(bad) > 0: 

277 raise ValueError( 

278 'Invalid character(s) "{}" in {}: {}'.format("".join(bad), text_type, text) 

279 ) 

280 

281 

282def read_line(line: str) -> Tuple[Union[FileTree, str], List[Optional[str]]]: 

283 """ 

284 Parse line from the tree file. 

285 

286 :param line: input line from a ``*.tree`` file 

287 :return: Tuple with: 

288 

289 - unique part of the filename 

290 - short name of the file (None if not provided) 

291 """ 

292 if line.strip()[:1] == "->": 

293 return read_subtree_line(line) 

294 match = re.match(r"^(\s*)(\S*)\s*\((\S*)\)\s*$", line) 

295 if match is not None: 

296 gr = match.groups() 

297 check_forbidden_characters(gr[1], r'<>"|', "file or directory name") 

298 if "," in gr[2]: 

299 short_names = [ 

300 name.strip() for name in gr[2].split(",") if len(name.strip()) > 0 

301 ] 

302 else: 

303 short_names = [gr[2].strip()] 

304 return gr[1], short_names 

305 match = re.match(r"^(\s*)(\S*)\s*$", line) 

306 if match is not None: 

307 gr = match.groups() 

308 check_forbidden_characters(gr[1], r'<>"|', "file or directory name") 

309 return gr[1], None 

310 raise ValueError("Unrecognized line %s" % line) 

311 

312 

313def read_subtree_line(line: str) -> Tuple[FileTree, List[Optional[str]]]: 

314 """ 

315 Parse the line defining a sub_tree. 

316 

317 :param line: input line from a ``*.tree`` file 

318 :param template: containing template 

319 :return: Tuple with 

320 

321 - sub_tree 

322 - short name of the sub_tree (None if not provided) 

323 """ 

324 match = re.match(r"^(\s*)->\s*(\S*)(.*)\((\S*)\)", line) 

325 short_names: List[Optional[str]] 

326 if match is None: 

327 match = re.match(r"^(\s*)->\s*(\S*)(.*)", line) 

328 if match is None: 

329 raise ValueError( 

330 "Sub-tree line could not be parsed: {}".format(line.strip()) 

331 ) 

332 _, type_name, variables_str = match.groups() 

333 short_names = [None] 

334 else: 

335 _, type_name, variables_str, full_short_name = match.groups() 

336 check_forbidden_characters(full_short_name, r"(){}/", "sub-tree name") 

337 if "," in full_short_name: 

338 short_names = [ 

339 name.strip() 

340 for name in full_short_name.split(",") 

341 if len(name.strip()) > 0 

342 ] 

343 else: 

344 short_names = [full_short_name] 

345 

346 check_forbidden_characters(type_name, r'<>:"/\|?*', "filename of sub-tree") 

347 

348 variables = {} 

349 if len(variables_str.strip()) != 0: 

350 for single_variable in variables_str.split(","): 

351 key, value = single_variable.split("=") 

352 variables[key.strip()] = value.strip() 

353 

354 sub_tree = FileTree.read(type_name, **variables) 

355 return sub_tree, short_names