Debian Codegraph @

seedir/folderstructure.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 The primary algorithm for determining the folder structure returned by
4 `seedir.realdir.seedir()` and `seedir.fakedir.FakeDir.seedir()`.
5
6 """
7
8 from abc import ABC, abstractmethod
9 import copy
10 import math
11 import os
12
13 import natsort
14
15 import seedir.printing as printing
16
17 def listdir_fullpath(path):
18 '''Like `os.listdir()`, but returns absolute paths.'''
19 return [os.path.join(path, f) for f in os.listdir(path)]
20
21 class FolderStructureArgs:
22
23 def __init__(self, extend='│ ', space=' ', split='├─', final='└─',
24 filestart='', folderstart='', fileend='', folderend='/',
25 depthlimit=None, itemlimit=None, beyond=None, first=None,
26 sort=True, sort_reverse=False, sort_key=None,
27 include_folders=None, exclude_folders=None,
28 include_files=None, exclude_files=None,
29 regex=False, mask=None, formatter=None,
30 sticky_formatter=False, acceptable_listdir_errors=None,
31 denied_string=' [ACCESS DENIED]'):
32 self.extend = extend
33 self.space = space
34 self.split = split
35 self.final = final
36 self.filestart = filestart
37 self.folderstart = folderstart
38 self.fileend = fileend
39 self.folderend = folderend
40 self.depthlimit = depthlimit
41 self.itemlimit = itemlimit
42 self.beyond = beyond
43 self.first = first
44 self.sort = sort
45 self.sort_reverse = sort_reverse
46 self.sort_key = sort_key
47 self.include_folders = include_folders
48 self.exclude_folders = exclude_folders
49 self.include_files = include_files
50 self.exclude_files = exclude_files
51 self.regex = regex
52 self.mask = mask
53 self.formatter = formatter
54 self.sticky_formatter = sticky_formatter
55 self.acceptable_listdir_errors = acceptable_listdir_errors
56 self.denied_string = denied_string
57
58 def copy(self):
59 return copy.deepcopy(self)
60
61 def update_with_formatter(self, formatter, item):
62 newstyle = formatter(item)
63 if newstyle is None:
64 return
65 for k, v in newstyle.items():
66 setattr(self, k, v)
67
68 class FolderStructure(ABC):
69 '''General class for determining folder strctures. Implements
70 the seedir folder-tree generating algorithm over arbitrary objects.
71
72 **This is an abstract class that cannot be instantiated directly.** It must
73 be subclassed, and the user must imeplement three abstract methods:
74
75 - `getname(self, item)`: Return the string name of a folder or file object.
76 - `isdir(self, item)`: Return a boolean indicating whether an object is
77 a folder (i.e., can be further travesed) or not.
78 - `listdir(self, item)`: For a folder-like object, return its children,
79 such that these same three methods can be called on each child again
80 (recursively).
81
82 Details on each of these functions are provided below. In each case,
83 `item` is a folder-like or file-like object that can be listed in the
84 diagram.
85
86 Seedir provides implementations for string paths (`RealDirStructure`),
87 pathlib objects (`PathibStucture`), and "fakedir" objects (`FakeDirStucture`).
88
89 *Note: Prior to v0.5.0, you could initialize a FolderStructure by passing
90 these three functions as arguments to the constructor. This is now
91 deprecated and will throw an error.*
92 '''
93
94 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
95 # ABSTRACT METHODS WHICH REQUIRE IMPLEMENTATION
96 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
97
98 @abstractmethod
99 def getname(self, item):
100 '''
101 Generate a string name for an item to put in the tree diagram.
102
103 Parameters
104 ----------
105 item : user-specified
106 Folder-like or file-like object.
107
108 Returns
109 -------
110 name : str
111 Name to show in the diagram.
112
113 '''
114 ...
115
116 @abstractmethod
117 def isdir(self, item):
118 '''
119 Returns True if an object is folder-like.
120
121 This function determines whether to treat objects as a folder or a
122 file. Some key differences of note are:
123
124 - Folders **will** be passed to `listdir()` to retrieve their
125 children. Files are instead not passed to this function.
126 - Some arguments are unique to folders or files, e.g.
127 `exclude_folders` and `exclude_files`.
128 - Folders and files are (by default) represented differently
129 in diagrams, with folders usually ending with a slash.
130
131 Parameters
132 ----------
133 item : user-specified
134 Folder-like or file-like object.
135
136 Returns
137 -------
138 result : bool
139 True if item is folder; False if not.
140
141 '''
142 ...
143
144 @abstractmethod
145 def listdir(self, item):
146 '''
147 Return the children of a folder-type object.
148
149 Children should always be more objects which can be passed to
150 `getname()`, `isdir()`, or (in the case of folder-like objects)
151 `listdir()`.
152
153 This function is not called on objects which are not folders,
154 as determined by `isdir()`.
155
156 Parameters
157 ----------
158 item : user-specified
159 Folder-like or file-like object.
160
161 Returns
162 -------
163 children : list
164 List of child objects for further traversal. Can be empty
165 for a folder with no children.
166
167 '''
168 ...
169
170 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
171
172 def __call__(self, folder, style='lines', printout=True, indent=2, uniform=None,
173 anystart=None, anyend=None, depthlimit=None, itemlimit=None,
174 beyond=None, first=None, sort=False, sort_reverse=False,
175 sort_key=None, include_folders=None, exclude_folders=None,
176 include_files=None, exclude_files=None, regex=False, mask=None,
177 formatter=None, sticky_formatter=False,
178 acceptable_listdir_errors=None, denied_string='', **kwargs):
179 '''Call this on a folder object to generate the seedir output
180 for that object.'''
181
182 accept_kwargs = ['extend', 'split', 'space', 'final',
183 'folderstart', 'filestart', 'folderend', 'fileend']
184
185 if any(i not in accept_kwargs for i in kwargs.keys()):
186 bad_kwargs = [i for i in kwargs.keys() if i not in accept_kwargs]
187 raise ValueError(f'kwargs must be any of {accept_kwargs}; '
188 f'unrecognized kwargs: {bad_kwargs}')
189
190 styleargs = printing.get_styleargs(style)
191 printing.format_indent(styleargs, indent=indent)
192
193 if uniform is not None:
194 for arg in ['extend', 'split', 'final', 'space']:
195 styleargs[arg] = uniform
196
197 if anystart is not None:
198 styleargs['folderstart'] = anystart
199 styleargs['filestart'] = anystart
200
201 if anyend is not None:
202 styleargs['folderend'] = anyend
203 styleargs['fileend'] = anyend
204
205 for k in kwargs:
206 if k in styleargs:
207 styleargs[k] = kwargs[k]
208
209 if sort_key is not None or sort_reverse == True:
210 sort = True
211
212 if acceptable_listdir_errors is None:
213 acceptable_listdir_errors = tuple()
214
215 args = FolderStructureArgs(depthlimit=depthlimit,
216 itemlimit=itemlimit,
217 beyond=beyond,
218 first=first,
219 sort=sort,
220 sort_reverse=sort_reverse,
221 sort_key=sort_key,
222 include_folders=include_folders,
223 exclude_folders=exclude_folders,
224 include_files=include_files,
225 exclude_files=exclude_files,
226 regex=regex,
227 mask=mask,
228 formatter=formatter,
229 sticky_formatter=sticky_formatter,
230 acceptable_listdir_errors=acceptable_listdir_errors,
231 denied_string=denied_string,
232 **styleargs)
233
234
235 s = self._folder_structure_recurse(ITEM=folder,
236 FSARGS=args).strip()
237
238 if printout:
239 print(s)
240 else:
241 return s
242
243 def apply_itemlimit(self, items, itemlimit):
244 '''
245 Limit the number of children in a folder.
246
247 Parameters
248 ----------
249 items : list
250 Child items.
251 itemlimit : int, tuple, or None
252 Limit. If int, limits the number of items regardless of if they
253 are folders or file. If a 2-tuple, the first number is treated
254 as a limit on the number of folders and the second number
255 is treated as a limit on the number of files. If None,
256 no limit is applied.
257
258 Returns
259 -------
260 finalitems : list
261 Kept times.
262 rem : list
263 Omitted items.
264
265 '''
266
267 # all items included when None
268 if itemlimit is None:
269 itemlimit = len(items)
270
271 # if int, take the first itemlimit items
272 if isinstance(itemlimit, int):
273 itemlimit = min(itemlimit, len(items))
274 finalitems = items[:itemlimit]
275 rem = items[itemlimit:]
276
277 # if tuple, interpret as limits for folders and files
278 else:
279 finalitems, rem = self._apply_tuple_itemlimit(items, itemlimit)
280
281 return finalitems, rem
282
283 def _apply_tuple_itemlimit(self, items, itemlimit):
284 '''Apply the itemlimit when it is a 2-tuple of
285 (folderlimit, filelimit).'''
286 folderlimit, filelimit = itemlimit
287
288 folderlimit = math.inf if folderlimit is None else folderlimit
289 filelimit = math.inf if filelimit is None else filelimit
290
291 finalitems = []
292 rem = []
293 foldercount = 0
294 filecount = 0
295
296 for item in items:
297 isdir = self.isdir(item)
298
299 if isdir and (foldercount < folderlimit):
300 finalitems.append(item)
301 foldercount += 1
302 elif isdir:
303 rem.append(item)
304 elif not isdir and (filecount < filelimit):
305 finalitems.append(item)
306 filecount += 1
307 else:
308 rem.append(item)
309
310 return finalitems, rem
311
312 def beyond_depth_str(self, items, beyond):
313 '''
314 Generates the text when using the 'beyond'
315 parameter and ther are more items than the itemlimit or contents
316 beyond the depthlimit.
317
318 Parameters
319 ----------
320 beyond : str
321 Style of beyond string to generate. Options are:
322 - 'ellipsis' ('...')
323 - 'content' or 'contents' (the number of files and folders beyond)
324 - a string starting with '_' (everything after the leading
325 underscore will be returned)
326 items : collection of file paths, optional
327 Path items of the items beyond the limit, used when the 'beyond'
328 argeument is 'content' or 'contents'. The default is None.
329
330
331 Returns
332 -------
333 str
334 String indicating what lies beyond
335
336 '''
337 if beyond.lower() == 'ellipsis':
338 return '...'
339 elif beyond.lower() in ['contents','content']:
340 folders = self.count_folders(items)
341 files = self.count_files(items)
342 return '{} folder(s), {} file(s)'.format(folders, files)
343 elif beyond and beyond[0] == '_':
344 return beyond[1:]
345 else:
346 s1 = '"beyond" must be "ellipsis", "content", or '
347 s2 = 'a string starting with "_"'
348 raise ValueError(s1 + s2)
349
350 def count_files(self, items):
351 '''
352 Count the number of files in a collection of paths.
353
354 Parameters
355 ----------
356 paths : list-like
357 Collection of paths.
358
359 Returns
360 -------
361 files : int
362 Count of files.
363
364 '''
365 files = sum([not self.isdir(i) for i in items])
366 return files
367
368 def count_folders(self, items):
369 '''
370 Count the number of folders in a collection of paths.
371
372 Parameters
373 ----------
374 paths : list-like
375 Collection of paths.
376
377 Returns
378 -------
379 files : int
380 Count of folders.
381
382 '''
383 folders = sum([self.isdir(i) for i in items])
384 return folders
385
386 def filter_items(self, listdir, include_folders=None,
387 exclude_folders=None, include_files=None,
388 exclude_files=None, regex=False, mask=None):
389
390 '''
391 Filter for folder and file names in folder structures. Removes or includes
392 items matching filtering strings.
393
394 Note the following priority of arguments:
395 1. Mask (totally overwrites include/exclude)
396 2. Include (saves items from being excluded)
397 3. Exclude
398
399 Parameters
400 ----------
401 listdir : list-like
402 Collection of file/folder items.
403 include_folders : str or list-like, optional
404 Folder names to include. The default is None.
405 exclude_folders : str or list-like, optional
406 Folder names to exclude. The default is None.
407 include_files : str or list-like, optional
408 File names to include. The default is None.
409 exclude_files : str or list-like, optional
410 File names to exclude. The default is None.
411 regex : bool, optional
412 Interpret strings as regular expressions. The default is False.
413 mask : function, optional
414 Function for filtering items. Absolute paths of each individual item
415 are passed to the mask function. If True is returned, the
416 item is kept. The default is None.
417
418 Returns
419 -------
420 keep : list
421 Filtered input.
422
423 '''
424
425 def _should_convert(x):
426 return isinstance(x, str) or x is None
427
428 filtered = []
429 for item in listdir:
430
431 name = self.getname(item)
432
433 if self.isdir(item):
434 inc = [include_folders] if _should_convert(include_folders) else include_folders
435 exc = [exclude_folders] if _should_convert(exclude_folders) else exclude_folders
436 else:
437 inc = [include_files] if _should_convert(include_files) else include_files
438 exc = [exclude_files] if _should_convert(exclude_files) else exclude_files
439
440 # 1. check mask - which trumps include/exclude arguments
441 if mask is not None:
442 if mask(item):
443 filtered.append(item)
444 continue
445
446 # set default keep behavior
447 # items are exluded if inclusion is passed
448 keep = all([i is None for i in inc])
449
450 # 2. apply exclusion
451 for pat in exc:
452 if pat is not None:
453 match = printing.is_match(pattern=pat, string=name, regex=regex)
454 if match:
455 keep = False
456
457 # 3. apply inclusion (trumps exclusion)
458 for pat in inc:
459 if pat is not None:
460 match = printing.is_match(pattern=pat, string=name, regex=regex)
461 if match:
462 keep = True
463
464 if keep:
465 filtered.append(item)
466
467 return filtered
468
469 def _folder_structure_recurse(self, ITEM, FSARGS, DEPTH=0,
470 INDEX=0, INCOMPLETE=None,
471 IS_LASTITEM=False,
472 IS_RAWSTRING=False):
473
474 # initialization
475 OUTPUT = ''
476
477 if INCOMPLETE is None:
478 INCOMPLETE = []
479
480 # set some variables
481 is_rootitem = DEPTH == 0
482 is_lastitem = IS_LASTITEM
483 is_rawstring = IS_RAWSTRING
484
485 # APPLY FORMATTER
486 # # # # # # # # # # # # # #
487 args = FSARGS.copy()
488 next_args = FSARGS
489
490 if not is_rawstring and args.formatter is not None:
491 args.update_with_formatter(args.formatter, ITEM)
492
493 if args.sticky_formatter:
494 next_args = args
495
496 # GET CHILDREN
497 # # # # # # # # # # # # # #
498
499 error_listing = False
500
501 if not is_rawstring and self.isdir(ITEM):
502 try:
503 listdir = self.listdir(ITEM)
504 except args.acceptable_listdir_errors:
505 error_listing = True
506 listdir = None
507 else:
508 listdir = None
509
510 # ADD CURRENT ITEM TO OUTPUT
511 # # # # # # # # # # # # # #
512
513 # create header
514 base_header = self.get_base_header(INCOMPLETE,
515 args.extend,
516 args.space)
517
518 # handle ultimate token in header
519 if is_rootitem:
520 branch = ''
521 elif is_lastitem:
522 branch = args.final
523 else:
524 branch = args.split
525
526 header = base_header + branch
527
528 # start / end tokens
529 if is_rawstring:
530 fkey = 'file'
531 else:
532 fkey = 'folder' if self.isdir(ITEM) else 'file'
533
534 start = f'{fkey}start'
535 end = f'{fkey}end'
536
537 # add current item to string
538 name = self.getname(ITEM) if not is_rawstring else ITEM
539 error_tag = args.denied_string if error_listing else ''
540
541 OUTPUT += (header +
542 getattr(args, start) +
543 name +
544 getattr(args, end) +
545 error_tag +
546 '\n')
547
548 if is_lastitem and INCOMPLETE:
549 INCOMPLETE.remove(DEPTH-1)
550
551 # EXIT IF NOT FOLDER
552 # # # # # # # # # # # # # #
553
554 if listdir is None:
555 return OUTPUT
556
557 # FILTER/SORT CHILDREN
558 # # # # # # # # # # # # #
559
560 current_itemlimit = args.itemlimit
561
562 # handle when depthlimit is reached
563 if isinstance(args.depthlimit, int) and DEPTH >= args.depthlimit:
564 if args.beyond is None:
565 return OUTPUT
566 else:
567 current_itemlimit = 0
568
569 # sort and filter the contents of listdir
570 sortargs = {
571 'first': args.first,
572 'sort_reverse': args.sort_reverse,
573 'sort_key': args.sort_key}
574
575 filterargs = {
576 'include_folders': args.include_folders,
577 'exclude_folders': args.exclude_folders,
578 'include_files' : args.include_files,
579 'exclude_files': args.exclude_files,
580 'mask': args.mask,
581 }
582
583 if args.sort or args.first is not None:
584 listdir = self.sort_dir(listdir, **sortargs)
585
586 if any(arg is not None for arg in filterargs.values()):
587 listdir = self.filter_items(listdir, **filterargs, regex=args.regex)
588
589 # apply itemlimit
590 finalitems, rem = self.apply_itemlimit(listdir, current_itemlimit)
591
592 # append beyond string if being used
593 beyond_added = False
594 if args.beyond is not None:
595 if rem or (DEPTH == args.depthlimit):
596 finalitems += [self.beyond_depth_str(rem, args.beyond)]
597 beyond_added = True
598
599 # RECURSE
600 # # # # # # # # # # # # # #
601
602 if finalitems:
603 INCOMPLETE.append(DEPTH)
604
605 total = len(finalitems)
606
607 for i, x in enumerate(finalitems):
608 last = i == (total - 1)
609 IS_RAWSTRING = (beyond_added and last)
610 OUTPUT += self._folder_structure_recurse(x, DEPTH=DEPTH+1,
611 INCOMPLETE=INCOMPLETE,
612 FSARGS=next_args,
613 INDEX=i,
614 IS_LASTITEM=last,
615 IS_RAWSTRING=IS_RAWSTRING)
616
617
618 # RETURN
619 # # # # # # # # # # # # # #
620 return OUTPUT
621
622 def get_base_header(self, incomplete, extend, space):
623 '''
624 For folder structures, generate the combination of extend and space
625 tokens to prepend to file names when generating folder diagrams.
626
627
628 The string generated here will still be missing the branch token
629 (split or final) as well as any folderstart or filestart tokens.
630 They are added within seedir.seedir().
631
632 For any item included in a folder diagram, the combination of
633 extend and space tokens is based on the depth of the item as well as the
634 parent folders to that item which are not completed. This information
635 is symbolized with the `incomplete` argument. The following illustrates
636 the incomplete arguments passed to this function for an example folder
637 tree:
638
639 ```
640 doc/
641 ├─_static/ [0]
642 │ ├─embedded/ [0, 1]
643 │ │ ├─deep_file [0, 1, 2]
644 │ │ └─very/ [0, 1, 2]
645 │ │ └─deep/ [0, 1, 3]
646 │ │ └─folder/ [0, 1, 4]
647 │ │ └─very_deep_file [0, 1, 5]
648 │ └─less_deep_file [0, 1]
649 └─index.rst [0]
650 ```
651
652 Parameters
653 ----------
654 incomplete : list-like
655 List of integers denoting the depth of incomplete folders at the time
656 of constructing the line for a given item. Zero represents being
657 inside the main folder, with increasing integers meaing increasing
658 depth.
659 extend : str
660 Characters symbolizing the extension of a folder.
661 space : str
662 Characters providing the gap between items and earlier parents.
663
664 Returns
665 -------
666 str
667 Base header string.
668
669 '''
670 if not incomplete:
671 return ''
672
673 base_header = []
674 max_i = max(incomplete)
675 for p in range(max_i):
676 if p in incomplete:
677 base_header.append(extend)
678 else:
679 base_header.append(space)
680 return "".join(base_header)
681
682 def sort_dir(self, items, first=None, sort_reverse=False, sort_key=None):
683 '''
684 Sorting function used to sort contents when producing folder diagrams.
685
686 Parameters
687 ----------
688 items : list-like
689 Collection of folder contents.
690 first : 'files' or 'folders', optional
691 Sort either files or folders first. The default is None.
692 sort_reverse : bool, optional
693 Reverse the sort applied. The default is False.
694 sort_key : function, optional
695 Function to apply to sort the objs by their basename. The function
696 should take a single argument, of the type expected by
697 this FolderStucture.
698
699 Returns
700 -------
701 list
702 Sorted input as a list.
703
704 '''
705 if sort_key is None:
706 key = lambda x : self.getname(x)
707 else:
708 key = lambda x: sort_key(self.getname(x))
709
710 if first in ['folders', 'files']:
711 folders = [p for p in items if self.isdir(p)]
712 files = [p for p in items if not self.isdir(p)]
713 folders = natsort.natsorted(folders, reverse=sort_reverse, key=key)
714 files = natsort.natsorted(files, reverse=sort_reverse, key=key)
715 output = folders + files if first == 'folders' else files + folders
716 elif first is None:
717 output = list(natsort.natsorted(items, reverse=sort_reverse, key=key))
718 else:
719 raise ValueError("`first` must be 'folders', 'files', or None.")
720
721 return output
722
723 class RealDirStructure(FolderStructure):
724 """Make folder structures from string paths."""
725
726 def __init__(self):
727 super().__init__()
728 self.slashes = os.sep + '/' + '//'
729
730 def getname(self, item):
731 return os.path.basename(item.rstrip(self.slashes))
732
733 def isdir(self, item):
734 return os.path.isdir(item)
735
736 def listdir(self, item):
737 return listdir_fullpath(item)
738
739 class PathlibStructure(FolderStructure):
740 """Make folder structures from pathlib objects."""
741
742 def getname(self, item):
743 return item.name
744
745 def isdir(self, item):
746 return item.is_dir()
747
748 def listdir(self, item):
749 return list(item.iterdir())
750
751 class FakeDirStructure(FolderStructure):
752 """Make `seedir.fakedir.FakeDir` folder structures."""
753
754 def getname(self, item):
755 return item.name
756
757 def isdir(self, item):
758 return item.isdir()
759
760 def listdir(self, item):
761 return item.listdir()