Debian Codegraph @

seedir/realdir.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Note: this module fails doctesting
4
5 """
6 This module provides code for producing folder structure strings for directories.
7 Currently, the only tool here is `seedir()`, the primary function of the
8 package `seedir`. This returns or prints the folder structure for a given path.
9 The main algorithm for determining the folder structure string is within the
10 <code>seedir.folderstructure.FolderStructure</code> class.
11 """
12
13 import os
14 import pathlib
15
16 from seedir.folderstructure import PathlibStructure, RealDirStructure
17
18 def _parse_path(path):
19 '''Helper function added to parse the input to `seedir.realdir.seedir()`.
20 Detects strings (paths) or pathlib objects.'''
21
22 if isinstance(path, str):
23 path = os.path.abspath(os.path.expanduser(path))
24 elif isinstance(path, pathlib.Path):
25 path = path.expanduser().resolve()
26 else:
27 raise TypeError(f"Can only parse str or pathlib.Path, not {type(path)}.")
28
29 return path
30
31 def seedir(path=None, style='lines', printout=True, indent=2, uniform=None,
32 anystart=None, anyend=None, depthlimit=None, itemlimit=None,
33 beyond=None, first=None, sort=False, sort_reverse=False,
34 sort_key=None, include_folders=None, exclude_folders=None,
35 include_files=None, exclude_files=None, regex=False, mask=None,
36 formatter=None, sticky_formatter=False,
37 acceptable_listdir_errors=PermissionError,
38 denied_string=' [ACCESS DENIED]', **kwargs):
39 '''
40
41 Primary function of the seedir package: generate folder trees for
42 computer directories.
43
44 ## EXAMPLES
45
46 ```
47 >>> import seedir as sd
48
49 ```
50
51 Make a basic tree diagram:
52
53 ```
54 >>> c = 'path/to/doc'
55 >>> sd.seedir(c)
56 doc/
57 ├─_static/
58 │ ├─embedded/
59 │ │ ├─deep_file
60 │ │ └─very/
61 │ │ └─deep/
62 │ │ └─folder/
63 │ │ └─very_deep_file
64 │ └─less_deep_file
65 ├─about.rst
66 ├─conf.py
67 └─index.rst
68
69 ```
70
71 Select different styles for the tree:
72
73 ```
74 >>> sd.seedir(c, style='dash')
75 doc/
76 |-_static/
77 | |-embedded/
78 | | |-deep_file
79 | | |-very/
80 | | |-deep/
81 | | |-folder/
82 | | |-very_deep_file
83 | |-less_deep_file
84 |-about.rst
85 |-conf.py
86 |-index.rst
87
88 ```
89
90 Sort the folder contents, separting folders and files:
91
92 ```
93 >>> sd.seedir(c, sort=True, first='files')
94 doc/
95 ├─about.rst
96 ├─conf.py
97 ├─index.rst
98 └─_static/
99 ├─less_deep_file
100 └─embedded/
101 ├─deep_file
102 └─very/
103 └─deep/
104 └─folder/
105 └─very_deep_file
106
107 ```
108
109 Limit the folder depth or items included:
110
111 ```
112 >>> sd.seedir(c, depthlimit=2, itemlimit=1)
113 doc/
114 ├─_static/
115 │ ├─embedded/
116 │ └─less_deep_file
117 └─about.rst
118
119 ```
120
121 Include or exclude specific items (with or without regular expressions):
122
123 ```
124 >>> sd.seedir(c, exclude_folders='_static')
125 doc/
126 ├─about.rst
127 ├─conf.py
128 └─index.rst
129
130 ```
131
132 Parameters
133 ----------
134 path : str, pathlib.Path, or None, optional
135 System path of a directory. If None, current working directory is
136 used. The path can be either a string path or a pathlib object.
137 In both cases, the path is converted to an absolute path, and the
138 tilde (~) is expanded.
139 style : 'lines', 'dash', 'arrow', 'spaces', 'plus', or 'emoji', optional
140 Style to use. The default is `'lines'`. A style determines the set
141 of characters ("tokens") used to represent the base structure of
142 the directory (e.g. which items belong to which folders, when items
143 are the last member of a folder, etc.). The actual tokens being used
144 by each style can be viewed with `seedir.printing.get_styleargs()`.
145 printout : bool, optional
146 Print the folder structure in the console. The default is `True`. When
147 `False`, the folder diagram is returned as a string.
148 indent : int (>= 0), optional
149 Number of spaces separating items from their parent folder.
150 The default is `2`.
151 uniform : str or None, optional
152 Characters to use for all tokens when creating the tree diagram.
153 The default is `None`. When not `None`, the extend, space, split, and
154 final tokens are replaced with `uniform` (the `'spaces'` style is
155 essentially `uniform = ' '`).
156 anystart : str or None, optional
157 Characters to prepend before any item (i.e. folder or file). The
158 default is `None`. Specific starts for folders and files can be
159 specified (see `**kwargs`).
160 anyend : str or None, optional
161 Characters to append after any item (i.e. folder or file). The
162 default is `None`. Specific ends for folders and files can be
163 specified (see `**kwargs`).
164 depthlimit : int or None, optional
165 Limit the depth of folders to traverse. Folders at the `depthlimit` are
166 included, but their contents are not shown (with the exception of the
167 beyond parameter being specified). The default is `None`, which can
168 cause exceptionally long runtimes for deep or extensive directories.
169 itemlimit : int or None, optional
170 Limit the number of items in a directory to show. Items beyond the
171 `itemlimit` can be expressed using the `beyond` parameter. The files and
172 folders left out are determined by the sorting parameters
173 (`sort`, `sort_reverse`, `sort_key`). The default is `None`.
174 beyond : str ('ellipsis', 'content' or a string starting with an underscore) or None, optional
175 String to indicate directory contents beyond the `itemlimit` or the
176 `depthlimit`. The default is `None`. Options are: `'ellipsis'` (`'...'`),
177 `'content'` or `'contents'` (the number of files and folders beyond), or
178 a string starting with `'_'` (everything after the leading underscore
179 will be returned)
180 first : 'files', 'folders', or None, optional
181 Sort the directory so that either files or folders appear first.
182 The default is `None`.
183 sort : bool, optional
184 Sort the directory. With no other specifications, the sort will be a
185 simple alphabetical sort of the item names, but this can be altered
186 with the `first`, `sort_reverse`, and `sort_key parameters`.
187 The default is `False`.
188 sort_reverse : bool, optional
189 Reverse the sorting determined by `sort` or `sort_key`.
190 The default is `False`.
191 sort_key : function, optional
192 Key to use for sorting file or folder names, akin to the `key` parameter
193 of the builtin `sorted()` or `list.sort()`. The function should take a
194 string as an argument. The default is `None`.
195 include_folders, exclude_folders, include_files, exclude_files : str, list-like, or None, optional
196 Folder / file names to include or exclude. The default is `None`. By
197 default, these are interpreted literally. Pass `regex=True` for
198 using regular expressions.
199 regex : bool, optional
200 Interpret the strings of include/exclude file/folder arguments as
201 regular expressions. The default is `False`.
202 mask : function, optional
203 Function for filtering items. Absolute paths of each individual item
204 are passed to the `mask` function. If `True` is returned, the
205 item is kept. The default is `None`. The type of the object
206 passed to `mask` corresponds with that passed as input:
207 `str` or `pathlib.Path`.
208 formatter : function, optional
209 Function for customizing the directory printing logic and style
210 based on specific folders & files. When passed, the formatter
211 is called on each item in the file tree, and the current arguments
212 are updated based what is returned.
213
214 The formatter function should accept a system path as a
215 single argument (either relative or absolute, depending on what is passed
216 to the `path` argument), and it should return either a dictionary or None.
217 The dictionary should have names of arguments as keys and their respective
218 setting as values.
219
220 The following options can meaningfully be toggled by passing a formatter
221 function: `depthlimit`, `itemlimit`, `beyond`, `first`, `sort`, `sort_reverse`,
222 `sort_key`, `include_folders`, `regex`, `mask`, as well as any seedir token
223 keywords (`extend`, `space`, `split`, `final`, `folderstart`, `filestart`,
224 `folderend`, `fileend`).
225
226 Note that in version 0.3.0, formatter could only be used to update
227 the style tokens. It can now be used to udpate those as well as the other
228 arguments listed above.
229
230 If None is returned by formatter, the tokens will be set by `style`.
231
232 Note that items exlcuded by the inclusion/exclusion arguments (or the
233 `mask`) *will not* be seen by formatter. Similarly, any folder tree
234 entries created by the `beyond` argument *will not* be seen by formatter.
235
236 The type of the object passed to `formatter` corresponds with that
237 passed as input: `str` or `pathlib.Path`.
238
239 sticky_formatter : bool, optional
240 When True, updates to argumnts made by the `formatter` (see above)
241 will be permanent. Thus, if arguments are updated when the `formatter`
242 is called on a folder, its children will (recursively) inherit
243 those new arguments.
244 acceptable_listdir_errors : Exception, tuple, or None
245
246 **New in v0.5.0**
247
248 Set errors which, when raised when listing the contents of a folder,
249 do not halt traversal. This parameter was added to allow
250 folders to be skipped when a `PermissionError` is raised. For folders
251 which raise an acceptable error, an additional string is added to their
252 entry in the diagram (see `denied_string`).
253
254 Providing one Exception causes only that type of Exception to be ignored.
255 Multiple Exception types can be handled by passing mutple Exceptions
256 as a tuple. Pass `None` to not allow any Exceptions (in this case,
257 an error is raised).
258
259 Exception types which are not provided will still be raised.
260
261 The default is `PermissionError`, which will skip folders
262 for which the caller does not have permissions to access.
263
264 denied_string : str
265
266 String tag to signify that a folder was not able to be traversed
267 due to one of the `acceptable_listdir_errors` being raised. This
268 is a string added after the folder name (and `folderend`) strings.
269 The default is `" [ACCESS DENIED]"`.
270
271 **kwargs : str
272 Specific tokens to use for creating the file tree diagram. The tokens
273 use by each builtin style can be seen with `seedir.printing.get_styleargs()`.
274 Valid options are `extend` (characters to show the extension of a directory
275 while its children are traversed), `space` (character to provide the
276 correct indentation of an item when some of its parent / grandparent
277 directories are completely traversed), `split` (characters to show a
278 folder or file within a directory, with more items following),
279 `final` (characters to show a folder or file within a directory,
280 with no more items following), `folderstart` (characters to prepend
281 before any folder), `filestart` (characters to preppend before any
282 file), `folderend` (characters to append after any folder), and
283 `fileend` (characters to append after any file). The following shows
284 the default tokens for the `'lines'` style:
285
286 >>> import seedir as sd
287 >>> sd.get_styleargs('lines')
288 {'split': '├─', 'extend': '│ ', 'space': ' ', 'final': '└─', 'folderstart': '', 'filestart': '', 'folderend': '/', 'fileend': ''}
289
290 All default style tokens are 2 character strings, except for
291 the file/folder start/end tokens. Style tokens from `**kwargs` are not
292 affected by the indent parameter. The `uniform`, `anystart`, and
293 `anyend` parameters can be used to affect multiple style tokens.
294
295 Notes
296 -------
297
298 The parameter `slash` was deprecated in 0.5.0. Pass `folderend` as
299 an additional keyword argument instead.
300
301 Returns
302 -------
303 s (str) or None
304 The tree diagram (as a string) or `None` if `prinout = True`, in which
305 case the tree diagram is printed in the console.
306
307 '''
308
309 if path is None:
310 path = os.getcwd()
311
312 path = _parse_path(path)
313
314 # call
315 args = dict(style=style,
316 printout=printout,
317 indent=indent,
318 uniform=uniform,
319 anystart=anystart,
320 anyend=anyend,
321 depthlimit=depthlimit,
322 itemlimit=itemlimit,
323 beyond=beyond,
324 first=first,
325 sort=sort,
326 sort_reverse=sort_reverse,
327 sort_key=sort_key,
328 include_folders=include_folders,
329 exclude_folders=exclude_folders,
330 include_files=include_files,
331 exclude_files=exclude_files,
332 regex=regex,
333 mask=mask,
334 formatter=formatter,
335 sticky_formatter=sticky_formatter,
336 acceptable_listdir_errors=acceptable_listdir_errors,
337 denied_string=denied_string,
338 **kwargs)
339
340 structure = PathlibStructure() if isinstance(path, pathlib.Path) else RealDirStructure()
341
342 return structure(path, **args)