| 1 |
|
| 2 |
""" |
| 3 |
Code for creating and editing "fake directories" within the `seedir` package; |
| 4 |
i.e. Python folder tree objects. This module can be used |
| 5 |
to make example folder tree diagrams, read folder tree strings, or convert |
| 6 |
abstract folder trees into real directories on a computer. |
| 7 |
""" |
| 8 |
|
| 9 |
__pdoc__ = {'get_random_int': False, |
| 10 |
'recursive_add_fakes': False} |
| 11 |
|
| 12 |
import os |
| 13 |
import string |
| 14 |
import re |
| 15 |
|
| 16 |
import random |
| 17 |
|
| 18 |
from seedir.errors import FakedirError |
| 19 |
from seedir.folderstructure import FakeDirStructure, RealDirStructure |
| 20 |
from seedir.folderstructure import listdir_fullpath |
| 21 |
|
| 22 |
from seedir.printing import words |
| 23 |
|
| 24 |
class FakeItem: |
| 25 |
'''Parent class for representing fake folders and files.''' |
| 26 |
def __init__(self, name, parent=None): |
| 27 |
''' |
| 28 |
Initialize the fake diretory or file object. |
| 29 |
|
| 30 |
Parameters |
| 31 |
---------- |
| 32 |
name : str |
| 33 |
Name for the folder or file. |
| 34 |
parent : seedir.fakedir.FakeDir or None, optional |
| 35 |
Parent of `self`. The default is `None`, meaning the object will |
| 36 |
be the "root" of the directory. |
| 37 |
|
| 38 |
Returns |
| 39 |
------- |
| 40 |
None. |
| 41 |
|
| 42 |
''' |
| 43 |
self.name = name |
| 44 |
self._parent = None |
| 45 |
self.parent = parent |
| 46 |
self.depth = 0 |
| 47 |
self.set_depth() |
| 48 |
|
| 49 |
@property |
| 50 |
def parent(self): |
| 51 |
''' |
| 52 |
Getter for the `parent` attribute. |
| 53 |
|
| 54 |
Returns |
| 55 |
------- |
| 56 |
seedir.fakedir.FakeDir |
| 57 |
The parent folder of the object. |
| 58 |
|
| 59 |
''' |
| 60 |
return self._parent |
| 61 |
|
| 62 |
@parent.setter |
| 63 |
def parent(self, other): |
| 64 |
''' |
| 65 |
Setter for the `parent` attribute. |
| 66 |
|
| 67 |
When a new parent is assigned for an object, this method |
| 68 |
verifies that the other object is `seedir.fakedir.FakeDir`, and that the other |
| 69 |
objects children do not contain a fake item with the same name. |
| 70 |
|
| 71 |
If those conditions are met, `self` is removed from the children |
| 72 |
of its current parent, and its parent attribute is reassigned. |
| 73 |
Depths are also reset. |
| 74 |
|
| 75 |
Parameters |
| 76 |
---------- |
| 77 |
other : seedir.fakedir.FakeDir |
| 78 |
Fake directory to become the new `parent` for self. |
| 79 |
|
| 80 |
Raises |
| 81 |
------ |
| 82 |
TypeError |
| 83 |
other is not a `seedir.fakedir.Fakedir`. |
| 84 |
|
| 85 |
FakedirError |
| 86 |
Name collision: `self.name` is in the child names of other. |
| 87 |
|
| 88 |
|
| 89 |
Returns |
| 90 |
------- |
| 91 |
None. |
| 92 |
|
| 93 |
''' |
| 94 |
if other: |
| 95 |
if not isinstance(other, FakeDir): |
| 96 |
raise TypeError('other parameter must be instance of FakeDir') |
| 97 |
if self.name in other.get_child_names(): |
| 98 |
raise FakedirError('FakeDirs must have unique file/folder names') |
| 99 |
other._children.append(self) |
| 100 |
if self.parent is not None: |
| 101 |
self.parent._children.remove(self) |
| 102 |
self._parent = other |
| 103 |
self.set_depth() |
| 104 |
if isinstance(self, FakeDir): |
| 105 |
self.set_child_depths() |
| 106 |
|
| 107 |
def get_path(self): |
| 108 |
'''Return a "path" string of self, from the head `seedir.fakedir.FakeDir` |
| 109 |
(which has `parent == None`). |
| 110 |
|
| 111 |
``` |
| 112 |
>>> import seedir as sd |
| 113 |
>>> f = sd.randomdir(seed=5) # create a random FakeDir |
| 114 |
>>> f |
| 115 |
MyFakeDir/ |
| 116 |
├─senor.txt |
| 117 |
├─verb.txt |
| 118 |
├─takeoff.txt |
| 119 |
├─monastic/ |
| 120 |
│ ├─paddy.txt |
| 121 |
│ ├─ewe.txt |
| 122 |
│ ├─advantage.txt |
| 123 |
│ ├─hooves/ |
| 124 |
│ └─registrar/ |
| 125 |
└─zag/ |
| 126 |
├─thematic.txt |
| 127 |
├─inelastic.txt |
| 128 |
├─fierce.txt |
| 129 |
├─gout/ |
| 130 |
└─stein/ |
| 131 |
├─vector.txt |
| 132 |
├─sora.txt |
| 133 |
└─proviso.txt |
| 134 |
|
| 135 |
>>> x = sd.FakeDir('newfolder', parent=f['zag/stein']) |
| 136 |
>>> x.get_path() |
| 137 |
'MyFakeDir/zag/stein/newfolder' |
| 138 |
|
| 139 |
``` |
| 140 |
|
| 141 |
''' |
| 142 |
parents = [self.name] |
| 143 |
on = self |
| 144 |
while on.parent is not None: |
| 145 |
on = on.parent |
| 146 |
parents.append(on.name) |
| 147 |
return '/'.join(parents[::-1]) |
| 148 |
|
| 149 |
def set_depth(self): |
| 150 |
'''Set the depth attribute of `self`, based on the depth of parent. |
| 151 |
Automatically called when setting new parents.''' |
| 152 |
if self.parent is None: |
| 153 |
self.depth = 0 |
| 154 |
else: |
| 155 |
self.depth = self.parent.depth + 1 |
| 156 |
|
| 157 |
def isfile(self): |
| 158 |
"""Returns `True` if instance is a `seedir.fakedir.FakeFile` object""" |
| 159 |
return isinstance(self, FakeFile) |
| 160 |
|
| 161 |
def isdir(self): |
| 162 |
"""Returns True if instance is a `seedir.fakedir.FakeDir` object""" |
| 163 |
return isinstance(self, FakeDir) |
| 164 |
|
| 165 |
def siblings(self): |
| 166 |
"""Returns all the other children of `self.parent`.""" |
| 167 |
if self.parent is None: |
| 168 |
return [] |
| 169 |
else: |
| 170 |
return [f for f in self.parent.listdir() if f is not self] |
| 171 |
|
| 172 |
class FakeFile(FakeItem): |
| 173 |
'''Class to represent files in `seedir.fakedir.FakeDir` objects. |
| 174 |
|
| 175 |
Files in a `seedir.fakedir.FakeDir` have this type. |
| 176 |
|
| 177 |
``` |
| 178 |
>>> import seedir as sd |
| 179 |
>>> f = sd.randomdir(seed=5) # create a random FakeDir |
| 180 |
>>> f |
| 181 |
MyFakeDir/ |
| 182 |
├─senor.txt |
| 183 |
├─verb.txt |
| 184 |
├─takeoff.txt |
| 185 |
├─monastic/ |
| 186 |
│ ├─paddy.txt |
| 187 |
│ ├─ewe.txt |
| 188 |
│ ├─advantage.txt |
| 189 |
│ ├─hooves/ |
| 190 |
│ └─registrar/ |
| 191 |
└─zag/ |
| 192 |
├─thematic.txt |
| 193 |
├─inelastic.txt |
| 194 |
├─fierce.txt |
| 195 |
├─gout/ |
| 196 |
└─stein/ |
| 197 |
├─vector.txt |
| 198 |
├─sora.txt |
| 199 |
└─proviso.txt |
| 200 |
|
| 201 |
>>> f['senor.txt'] |
| 202 |
FakeFile(MyFakeDir/senor.txt) |
| 203 |
|
| 204 |
``` |
| 205 |
|
| 206 |
''' |
| 207 |
def __init__(self, name, parent=None): |
| 208 |
'''Same as `seedir.fakedir.FakeItem` initialization, but adds |
| 209 |
`filename` and `extension` attributes. |
| 210 |
''' |
| 211 |
super().__init__(name, parent) |
| 212 |
self.filename, self.extension = os.path.splitext(self.name) |
| 213 |
|
| 214 |
def __str__(self): |
| 215 |
return 'FakeFile({})'.format(self.get_path()) |
| 216 |
|
| 217 |
def __repr__(self): |
| 218 |
return 'FakeFile({})'.format(self.get_path()) |
| 219 |
|
| 220 |
class FakeDir(FakeItem): |
| 221 |
'''Class to represent fake folders. Can be used to create |
| 222 |
custom folder tree diagrams. See `seedir.fakedir.fakedir()` for converting |
| 223 |
a real directory into a FakeDir, `seedir.fakedir.fakedir_fromstring()` for |
| 224 |
converting a text folder diagram into a `FakeDir`, and `seedir.fakedir.randomdir()` |
| 225 |
for creating a random one. |
| 226 |
|
| 227 |
To make a `FakeDir` from scratch, use this class: |
| 228 |
|
| 229 |
``` |
| 230 |
>>> import seedir as sd |
| 231 |
>>> x = sd.FakeDir('myfakedir') |
| 232 |
>>> x.seedir() |
| 233 |
myfakedir/ |
| 234 |
|
| 235 |
``` |
| 236 |
|
| 237 |
There are various ways to add to it: |
| 238 |
|
| 239 |
``` |
| 240 |
# using methods; the created items are returned |
| 241 |
>>> x.create_file(['__init__.py', 'main.py', 'styles.txt']) |
| 242 |
[FakeFile(myfakedir/__init__.py), FakeFile(myfakedir/main.py), FakeFile(myfakedir/styles.txt)] |
| 243 |
>>> x.create_folder('docs') |
| 244 |
docs/ |
| 245 |
|
| 246 |
# initializing new objects and setting the parent |
| 247 |
>>> y = sd.FakeDir('resources', parent=x) |
| 248 |
|
| 249 |
# changing the parent of existing objects |
| 250 |
>>> z = sd.FakeDir('images') |
| 251 |
>>> z.parent = y |
| 252 |
|
| 253 |
>>> for n in ['a', 'b', 'c']: |
| 254 |
... z.create_file(n + '.png') |
| 255 |
FakeFile(myfakedir/resources/images/a.png) |
| 256 |
FakeFile(myfakedir/resources/images/b.png) |
| 257 |
FakeFile(myfakedir/resources/images/c.png) |
| 258 |
|
| 259 |
>>> x.seedir(sort=True, first='folders') |
| 260 |
myfakedir/ |
| 261 |
├─docs/ |
| 262 |
├─resources/ |
| 263 |
│ └─images/ |
| 264 |
│ ├─a.png |
| 265 |
│ ├─b.png |
| 266 |
│ └─c.png |
| 267 |
├─__init__.py |
| 268 |
├─main.py |
| 269 |
└─styles.txt |
| 270 |
|
| 271 |
``` |
| 272 |
|
| 273 |
You can index with path-like strings: |
| 274 |
|
| 275 |
``` |
| 276 |
>>> x['resources/images/a.png'] |
| 277 |
FakeFile(myfakedir/resources/images/a.png) |
| 278 |
|
| 279 |
``` |
| 280 |
|
| 281 |
''' |
| 282 |
def __init__(self, name, parent=None): |
| 283 |
'''Same as `seedir.fakedir.FakeItem` initialization, but adds |
| 284 |
the `_children` attribute for keeping track of items inside the fake dir. |
| 285 |
''' |
| 286 |
|
| 287 |
self._children = [] |
| 288 |
super().__init__(name, parent) |
| 289 |
|
| 290 |
def __str__(self): |
| 291 |
'''String conversion of `FakeDir`''' |
| 292 |
return 'FakeDir({})'.format(self.get_path()) |
| 293 |
|
| 294 |
def __repr__(self): |
| 295 |
'''Representation of `FakeDir` (shown as a folder diagram).''' |
| 296 |
return self.seedir(printout=False) |
| 297 |
|
| 298 |
def __getitem__(self, path): |
| 299 |
"""Use path-like strings to index `FakeDir` objects.""" |
| 300 |
if not isinstance(path, str): |
| 301 |
raise TypeError("Can only index FakeDir with int or str, " |
| 302 |
"not {}".format(type(path))) |
| 303 |
paths = path.split('/') |
| 304 |
current = self |
| 305 |
for p in paths: |
| 306 |
for f in current._children: |
| 307 |
if p == f.name: |
| 308 |
current = f |
| 309 |
break |
| 310 |
else: |
| 311 |
raise(FakedirError('Path "{}" not found through {}'.format(path, self))) |
| 312 |
return current |
| 313 |
|
| 314 |
def create_folder(self, name): |
| 315 |
""" |
| 316 |
Create a new folder (`seedir.fakedir.FakeDir`) as a child. |
| 317 |
|
| 318 |
``` |
| 319 |
>>> import seedir as sd |
| 320 |
>>> x = sd.FakeDir('Test') |
| 321 |
>>> x.create_folder("new_folder") |
| 322 |
new_folder/ |
| 323 |
>>> x.seedir() |
| 324 |
Test/ |
| 325 |
└─new_folder/ |
| 326 |
|
| 327 |
``` |
| 328 |
|
| 329 |
Parameters |
| 330 |
---------- |
| 331 |
name : str |
| 332 |
Name of the new folder. Can also be a collection of names to create |
| 333 |
multiple folders. |
| 334 |
|
| 335 |
Returns |
| 336 |
------- |
| 337 |
FakeDir or list |
| 338 |
The new object or objects (as a list) are returned. |
| 339 |
|
| 340 |
""" |
| 341 |
if isinstance(name, str): |
| 342 |
return FakeDir(name, parent=self) |
| 343 |
else: |
| 344 |
return [FakeDir(s, parent=self) for s in name] |
| 345 |
|
| 346 |
def create_file(self, name): |
| 347 |
""" |
| 348 |
Create a new file (`seedir.fakedir.FakeFile`) as a child. |
| 349 |
|
| 350 |
``` |
| 351 |
>>> import seedir as sd |
| 352 |
>>> x = sd.FakeDir('Test') |
| 353 |
>>> x.create_file("new_file.txt") |
| 354 |
FakeFile(Test/new_file.txt) |
| 355 |
>>> x.seedir() |
| 356 |
Test/ |
| 357 |
└─new_file.txt |
| 358 |
|
| 359 |
``` |
| 360 |
|
| 361 |
Parameters |
| 362 |
---------- |
| 363 |
name : str |
| 364 |
Name of the new file. Can also be a collection of names to create |
| 365 |
multiple files. |
| 366 |
|
| 367 |
Returns |
| 368 |
------- |
| 369 |
FakeFile or list |
| 370 |
The new object or objects (as a list) are returned. |
| 371 |
|
| 372 |
""" |
| 373 |
if isinstance(name, str): |
| 374 |
return FakeFile(name, parent=self) |
| 375 |
else: |
| 376 |
return [FakeFile(s, parent=self) for s in name] |
| 377 |
|
| 378 |
def copy(self): |
| 379 |
''' |
| 380 |
Generate a totally unlinked copy object. The root of the new FakeDir |
| 381 |
will be a copy of this folder (and all its subfolders). Calling this |
| 382 |
method does not alter self at all. |
| 383 |
|
| 384 |
Returns |
| 385 |
------- |
| 386 |
seedir.fakedir.FakeDir |
| 387 |
A copy FakeDir. |
| 388 |
|
| 389 |
''' |
| 390 |
def recurse_build(f, other): |
| 391 |
'''Recursive helper for building the new copy.''' |
| 392 |
if f.isfile(): |
| 393 |
new = FakeFile(name=f.name, parent=other) |
| 394 |
elif f.isdir(): |
| 395 |
new = FakeDir(name=f.name, parent=other) |
| 396 |
for child in f.listdir(): |
| 397 |
recurse_build(child, other=new) |
| 398 |
return new |
| 399 |
|
| 400 |
return recurse_build(self, other=None) |
| 401 |
|
| 402 |
|
| 403 |
def delete(self, child): |
| 404 |
''' |
| 405 |
Delete items from a `seedir.fakedir.FakeDir`. |
| 406 |
|
| 407 |
``` |
| 408 |
>>> import seedir as sd |
| 409 |
>>> r = sd.randomdir(seed=5) |
| 410 |
>>> r |
| 411 |
MyFakeDir/ |
| 412 |
├─senor.txt |
| 413 |
├─verb.txt |
| 414 |
├─takeoff.txt |
| 415 |
├─monastic/ |
| 416 |
│ ├─paddy.txt |
| 417 |
│ ├─ewe.txt |
| 418 |
│ ├─advantage.txt |
| 419 |
│ ├─hooves/ |
| 420 |
│ └─registrar/ |
| 421 |
└─zag/ |
| 422 |
├─thematic.txt |
| 423 |
├─inelastic.txt |
| 424 |
├─fierce.txt |
| 425 |
├─gout/ |
| 426 |
└─stein/ |
| 427 |
├─vector.txt |
| 428 |
├─sora.txt |
| 429 |
└─proviso.txt |
| 430 |
|
| 431 |
>>> r['zag'].delete(['thematic.txt', 'inelastic.txt']) # delete with string names |
| 432 |
>>> r.delete(r['monastic']) # delete with objects |
| 433 |
>>> r |
| 434 |
MyFakeDir/ |
| 435 |
├─senor.txt |
| 436 |
├─verb.txt |
| 437 |
├─takeoff.txt |
| 438 |
└─zag/ |
| 439 |
├─fierce.txt |
| 440 |
├─gout/ |
| 441 |
└─stein/ |
| 442 |
├─vector.txt |
| 443 |
├─sora.txt |
| 444 |
└─proviso.txt |
| 445 |
|
| 446 |
``` |
| 447 |
|
| 448 |
Parameters |
| 449 |
---------- |
| 450 |
child : str, FakeDir, FakeFile or list-like |
| 451 |
Child or children to remove. Can be a string name, actual |
| 452 |
`seedir.fakedir.FakeDir` / `seedir.fakedir.FakeFile` object, |
| 453 |
or a collection of names or items. |
| 454 |
|
| 455 |
Raises |
| 456 |
------ |
| 457 |
FakedirError |
| 458 |
No item found to delete. |
| 459 |
|
| 460 |
Returns |
| 461 |
------- |
| 462 |
None. |
| 463 |
|
| 464 |
''' |
| 465 |
target = None |
| 466 |
if type(child) in [FakeDir, FakeFile]: |
| 467 |
target = child.name |
| 468 |
elif isinstance(child, str): |
| 469 |
target = child |
| 470 |
if target is not None: |
| 471 |
try: |
| 472 |
to_del = next(f for f in self._children if f.name == target) |
| 473 |
to_del.parent = None |
| 474 |
except StopIteration: |
| 475 |
raise FakedirError('{} has no child with name "{}"'.format(self, target)) |
| 476 |
else: |
| 477 |
child_copy = [c for c in child] |
| 478 |
for c in child_copy: |
| 479 |
target = None |
| 480 |
if type(c) in [FakeDir, FakeFile]: |
| 481 |
target = c.name |
| 482 |
elif isinstance(c, str): |
| 483 |
target = c |
| 484 |
if target is not None: |
| 485 |
try: |
| 486 |
to_del = next(f for f in self._children if |
| 487 |
f.name == target) |
| 488 |
to_del.parent = None |
| 489 |
except StopIteration: |
| 490 |
raise FakedirError('{} has no child with name "{}"'.format(self, target)) |
| 491 |
|
| 492 |
def get_child_names(self): |
| 493 |
'''Return a list of child names. |
| 494 |
|
| 495 |
``` |
| 496 |
>>> import seedir as sd |
| 497 |
>>> r = sd.randomdir(seed=5) |
| 498 |
>>> r |
| 499 |
MyFakeDir/ |
| 500 |
├─senor.txt |
| 501 |
├─verb.txt |
| 502 |
├─takeoff.txt |
| 503 |
├─monastic/ |
| 504 |
│ ├─paddy.txt |
| 505 |
│ ├─ewe.txt |
| 506 |
│ ├─advantage.txt |
| 507 |
│ ├─hooves/ |
| 508 |
│ └─registrar/ |
| 509 |
└─zag/ |
| 510 |
├─thematic.txt |
| 511 |
├─inelastic.txt |
| 512 |
├─fierce.txt |
| 513 |
├─gout/ |
| 514 |
└─stein/ |
| 515 |
├─vector.txt |
| 516 |
├─sora.txt |
| 517 |
└─proviso.txt |
| 518 |
|
| 519 |
>>> r.get_child_names() |
| 520 |
['senor.txt', 'verb.txt', 'takeoff.txt', 'monastic', 'zag'] |
| 521 |
|
| 522 |
``` |
| 523 |
|
| 524 |
''' |
| 525 |
return [c.name for c in self._children] |
| 526 |
|
| 527 |
def listdir(self): |
| 528 |
'''Return the list of `seedir.fakedir.FakeFile` and `seedir.fakedir.FakeDir` |
| 529 |
objects that are children of `self` (like `os.listdir`). |
| 530 |
|
| 531 |
``` |
| 532 |
>>> import seedir as sd |
| 533 |
>>> r = sd.randomdir(seed=1) |
| 534 |
>>> r |
| 535 |
MyFakeDir/ |
| 536 |
├─churchmen.txt |
| 537 |
└─exposure/ |
| 538 |
|
| 539 |
>>> print([str(i) for i in r.listdir()]) |
| 540 |
['FakeFile(MyFakeDir/churchmen.txt)', 'FakeDir(MyFakeDir/exposure)'] |
| 541 |
|
| 542 |
``` |
| 543 |
''' |
| 544 |
return self._children |
| 545 |
|
| 546 |
def realize(self, path=None): |
| 547 |
''' |
| 548 |
Convert a fake file tree into a real one by creating a folder at a |
| 549 |
given path, and populating it with files and sub-directories. |
| 550 |
|
| 551 |
All files will be empty. |
| 552 |
|
| 553 |
``` |
| 554 |
import os |
| 555 |
|
| 556 |
import seedir as sd |
| 557 |
|
| 558 |
r = sd.randomdir(seed=1) |
| 559 |
# MyFakeDir/ |
| 560 |
# ├─churchmen.txt |
| 561 |
# └─exposure/ |
| 562 |
|
| 563 |
r.realize() |
| 564 |
os.path.isdir('MyFakeDir/exposure') |
| 565 |
# True |
| 566 |
``` |
| 567 |
|
| 568 |
Parameters |
| 569 |
---------- |
| 570 |
path : str, optional |
| 571 |
System path where to create the folder. The default is `None`, |
| 572 |
in which the current working directory is used. |
| 573 |
|
| 574 |
Returns |
| 575 |
------- |
| 576 |
None. |
| 577 |
|
| 578 |
''' |
| 579 |
def create(f, root): |
| 580 |
fpath = f.get_path() |
| 581 |
joined = os.path.join(root, fpath) |
| 582 |
if isinstance(f, FakeDir): |
| 583 |
os.mkdir(joined) |
| 584 |
elif isinstance(f, FakeFile): |
| 585 |
with open(joined, 'w'): pass; |
| 586 |
if path is None: |
| 587 |
path = os.getcwd() |
| 588 |
self.walk_apply(create, root=path) |
| 589 |
|
| 590 |
def seedir(self, style='lines', printout=True, indent=2, uniform=None, |
| 591 |
anystart=None, anyend=None, depthlimit=None, itemlimit=None, |
| 592 |
beyond=None, first=None, sort=False, sort_reverse=False, sort_key=None, |
| 593 |
include_folders=None, exclude_folders=None, include_files=None, |
| 594 |
exclude_files=None, regex=False, mask=None, |
| 595 |
formatter=None, sticky_formatter=False, |
| 596 |
acceptable_listdir_errors=None, denied_string=' [ACCESS DENIED]', **kwargs): |
| 597 |
''' |
| 598 |
|
| 599 |
Create a folder tree diagram for `self`. `seedir.fakedir.FakeDir` version of |
| 600 |
`seedir.realdir.seedir()` (see its documentation for examples). |
| 601 |
|
| 602 |
Parameters |
| 603 |
---------- |
| 604 |
style : 'lines', 'dash', 'arrow', 'spaces', 'plus', or 'emoji', optional |
| 605 |
Style to use. The default is `'lines'`. A style determines the set |
| 606 |
of characters ("tokens") used to represent the base structure of |
| 607 |
the directory (e.g. which items belong to which folders, when items |
| 608 |
are the last member of a folder, etc.). The actual tokens being used |
| 609 |
by each style can be viewed with `seedir.printing.get_styleargs()`. |
| 610 |
printout : bool, optional |
| 611 |
Print the folder structure in the console. The default is `True`. When |
| 612 |
`False`, the folder diagram is returned as a string. |
| 613 |
indent : int (>= 0), optional |
| 614 |
Number of spaces separating items from their parent folder. |
| 615 |
The default is `2`. |
| 616 |
uniform : str or None, optional |
| 617 |
Characters to use for all tokens when creating the tree diagram. |
| 618 |
The default is `None`. When not `None`, the extend, space, split, and |
| 619 |
final tokens are replaced with `uniform` (the `'spaces'` style is |
| 620 |
essentially `uniform = ' '`). |
| 621 |
anystart : str or None, optional |
| 622 |
Characters to append before any item (i.e. folder or file). The |
| 623 |
default is `None`. Specific starts for folders and files can be |
| 624 |
specified (see `**kwargs`). |
| 625 |
anyend : str or None, optional |
| 626 |
Characters to append after any item (i.e. folder or file). The |
| 627 |
default is `None`. Specific ends for folders and files can be |
| 628 |
specified (see `**kwargs`). |
| 629 |
depthlimit : int or None, optional |
| 630 |
Limit the depth of folders to traverse. Folders at the `depthlimit` are |
| 631 |
included, but their contents are not shown (with the exception of the |
| 632 |
beyond parameter being specified). The default is `None`, which can |
| 633 |
cause exceptionally long runtimes for deep or extensive directories. |
| 634 |
itemlimit : int or None, optional |
| 635 |
Limit the number of items in a directory to show. Items beyond the |
| 636 |
`itemlimit` can be expressed using the `beyond` parameter. The files and |
| 637 |
folders left out are determined by the sorting parameters |
| 638 |
(`sort`, `sort_reverse`, `sort_key`). The default is `None`. |
| 639 |
beyond : str ('ellipsis', 'content' or a string starting with an underscore) or None, optional |
| 640 |
String to indicate directory contents beyond the `itemlimit` or the |
| 641 |
`depthlimit`. The default is `None`. Options are: `'ellipsis'` (`'...'`), |
| 642 |
`'content'` or `'contents'` (the number of files and folders beyond), or |
| 643 |
a string starting with `'_'` (everything after the leading underscore |
| 644 |
will be returned) |
| 645 |
first : 'files', 'folders', or None, optional |
| 646 |
Sort the directory so that either files or folders appear first. |
| 647 |
The default is `None`. |
| 648 |
sort : bool, optional |
| 649 |
Sort the directory. With no other specifications, the sort will be a |
| 650 |
simple alphabetical sort of the item names, but this can be altered |
| 651 |
with the `first`, `sort_reverse`, and `sort_key parameters`. |
| 652 |
The default is `False`. |
| 653 |
sort_reverse : bool, optional |
| 654 |
Reverse the sorting determined by `sort` or `sort_key`. |
| 655 |
The default is `False`. |
| 656 |
sort_key : function, optional |
| 657 |
Key to use for sorting file or folder names, akin to the `key` parameter |
| 658 |
of the builtin `sorted()` or `list.sort()`. The function should take a |
| 659 |
string as an argument. The default is `None`. |
| 660 |
include_folders, exclude_folders, include_files, exclude_files : str, list-like, or None, optional |
| 661 |
Folder / file names to include or exclude. The default is `None`. By |
| 662 |
default, these are interpreted literally. Pass `regex=True` for |
| 663 |
using regular expressions. |
| 664 |
regex : bool, optional |
| 665 |
Interpret the strings of include/exclude file/folder arguments as |
| 666 |
regular expressions. The default is `False`. |
| 667 |
mask : function, optional |
| 668 |
Function for filtering items. Each individual item object |
| 669 |
is passed to the mask function. If `True` is returned, the |
| 670 |
item is kept. The default is `None`. |
| 671 |
formatter : function, optional |
| 672 |
Function for customizing the directory printing logic and style |
| 673 |
based on specific folders & files. When passed, the formatter |
| 674 |
is called on each item in the file tree, and the current arguments |
| 675 |
are updated based what is returned. |
| 676 |
|
| 677 |
The formatter function should accept a FakeItem as a |
| 678 |
single argument (either relative or absolute, depending on what is passed |
| 679 |
to the `path` argument), and it should return either a dictionary or None. |
| 680 |
The dictionary should have names of arguments as keys and their respective |
| 681 |
setting as values. |
| 682 |
|
| 683 |
The following options can meaningfully be toggled by passing a formatter |
| 684 |
function: `depthlimit`, `itemlimit`, `beyond`, `first`, `sort`, `sort_reverse`, |
| 685 |
`sort_key`, `include_folders`, `regex`, `mask`, as well as any seedir token |
| 686 |
keywords (`extend`, `space`, `split`, `final`, `folderstart`, `filestart`, |
| 687 |
`folderend`, `fileend`). |
| 688 |
|
| 689 |
Note that in version 0.3.0, formatter could only be used to update |
| 690 |
the style tokens. It can now be used to udpate those as well as the other |
| 691 |
arguments listed above. |
| 692 |
|
| 693 |
If None is returned by formatter, the tokens will be set by `style`. |
| 694 |
|
| 695 |
Note that items exlcuded by the inclusion/exclusion arguments (or the |
| 696 |
`mask`) *will not* be seen by formatter. Similarly, any folder tree |
| 697 |
entries created by the `beyond` argument *will not* be seen by formatter. |
| 698 |
|
| 699 |
sticky_formatter : bool, optional |
| 700 |
When True, updates to argumnts made by the `formatter` (see above) |
| 701 |
will be permanent. Thus, if arguments are updated when the `formatter` |
| 702 |
is called on a folder, its children will (recursively) inherit |
| 703 |
those new arguments. |
| 704 |
|
| 705 |
acceptable_listdir_errors : Exception, tuple, or None |
| 706 |
|
| 707 |
**New in v0.5.0** |
| 708 |
|
| 709 |
Set errors which, when raised when listing the contents of a folder, |
| 710 |
do not halt traversal. This parameter was added to allow |
| 711 |
folders to be skipped when a `PermissionError` is raised. For folders |
| 712 |
which raise an acceptable error, an additional string is added to their |
| 713 |
entry in the diagram (see `denied_string`). |
| 714 |
|
| 715 |
Providing one Exception causes only that type of Exception to be ignored. |
| 716 |
Multiple Exception types can be handled by passing mutple Exceptions |
| 717 |
as a tuple. Pass `None` to not allow any Exceptions (in this case, |
| 718 |
an error is raised). |
| 719 |
|
| 720 |
Exception types which are not provided will still be raised. |
| 721 |
|
| 722 |
This parameter is mostly meaningless for FakeDir objects, except |
| 723 |
for testing purposes. |
| 724 |
|
| 725 |
denied_string : str |
| 726 |
|
| 727 |
**New in v0.5.0** |
| 728 |
|
| 729 |
String tag to signify that a folder was not able to be traversed |
| 730 |
due to one of the `acceptable_listdir_errors` being raised. This |
| 731 |
is a string added after the folder name (and `folderend`) strings. |
| 732 |
The default is `" [ACCESS DENIED]"`. |
| 733 |
|
| 734 |
**kwargs : str |
| 735 |
Specific tokens to use for creating the file tree diagram. The tokens |
| 736 |
use by each builtin style can be seen with `seedir.printing.get_styleargs()`. |
| 737 |
Valid options are `extend` (characters to show the extension of a directory |
| 738 |
while its children are traversed), `space` (character to provide the |
| 739 |
correct indentation of an item when some of its parent / grandparent |
| 740 |
directories are completely traversed), `split` (characters to show a |
| 741 |
folder or file within a directory, with more items following), |
| 742 |
`final` (characters to show a folder or file within a directory, |
| 743 |
with no more items following), `folderstart` (characters to prepend |
| 744 |
before any folder), `filestart` (characters to preppend before any |
| 745 |
file), `folderend` (characters to append after any folder), and |
| 746 |
`fileend` (characters to append after any file). The following shows |
| 747 |
the default tokens for the `'lines'` style: |
| 748 |
|
| 749 |
>>> import seedir as sd |
| 750 |
>>> sd.get_styleargs('lines') |
| 751 |
{'split': '├─', 'extend': '│ ', 'space': ' ', 'final': '└─', 'folderstart': '', 'filestart': '', 'folderend': '/', 'fileend': ''} |
| 752 |
|
| 753 |
All default style tokens are 2 character strings, except for |
| 754 |
the file/folder start/end tokens. Style tokens from `**kwargs` are not |
| 755 |
affected by the indent parameter. The `uniform`, `anystart`, and |
| 756 |
`anyend` parameters can be used to affect multiple style tokens. |
| 757 |
|
| 758 |
Notes |
| 759 |
------- |
| 760 |
|
| 761 |
The parameter `slash` was deprecated in 0.5.0. Pass `folderend` as |
| 762 |
an additional keyword argument instead. |
| 763 |
|
| 764 |
Returns |
| 765 |
------- |
| 766 |
s (str) or None |
| 767 |
The tree diagram (as a string) or None if prinout = True, in which |
| 768 |
case the tree diagram is printed in the console. |
| 769 |
|
| 770 |
''' |
| 771 |
|
| 772 |
|
| 773 |
args = dict(style=style, |
| 774 |
printout=printout, |
| 775 |
indent=indent, |
| 776 |
uniform=uniform, |
| 777 |
anystart=anystart, |
| 778 |
anyend=anyend, |
| 779 |
depthlimit=depthlimit, |
| 780 |
itemlimit=itemlimit, |
| 781 |
beyond=beyond, |
| 782 |
first=first, |
| 783 |
sort=sort, |
| 784 |
sort_reverse=sort_reverse, |
| 785 |
sort_key=sort_key, |
| 786 |
include_folders=include_folders, |
| 787 |
exclude_folders=exclude_folders, |
| 788 |
include_files=include_files, |
| 789 |
exclude_files=exclude_files, |
| 790 |
regex=regex, |
| 791 |
mask=mask, |
| 792 |
formatter=formatter, |
| 793 |
sticky_formatter=sticky_formatter, |
| 794 |
acceptable_listdir_errors=acceptable_listdir_errors, |
| 795 |
denied_string=denied_string, |
| 796 |
**kwargs) |
| 797 |
|
| 798 |
FDS = FakeDirStructure() |
| 799 |
return FDS(self, **args) |
| 800 |
|
| 801 |
def set_child_depths(self): |
| 802 |
'''Recursively set depths of `self` and its children. |
| 803 |
Called automatically when a new `parent` is assigned.''' |
| 804 |
def apply_setdepth(FD): |
| 805 |
FD.set_depth() |
| 806 |
self.walk_apply(apply_setdepth) |
| 807 |
|
| 808 |
def trim(self, depthlimit): |
| 809 |
""" |
| 810 |
Remove items beyond the `depthlimit`. |
| 811 |
|
| 812 |
``` |
| 813 |
>>> import seedir as sd |
| 814 |
>>> r = sd.randomdir(seed=456) |
| 815 |
>>> r |
| 816 |
MyFakeDir/ |
| 817 |
├─Vogel.txt |
| 818 |
├─monkish.txt |
| 819 |
├─jowly.txt |
| 820 |
├─scrooge/ |
| 821 |
│ ├─light.txt |
| 822 |
│ ├─reliquary.txt |
| 823 |
│ ├─sandal/ |
| 824 |
│ ├─paycheck/ |
| 825 |
│ │ ├─electrophoresis.txt |
| 826 |
│ │ └─Pyongyang/ |
| 827 |
│ └─patrimonial/ |
| 828 |
├─Uganda/ |
| 829 |
└─pedantic/ |
| 830 |
└─cataclysmic.txt |
| 831 |
|
| 832 |
>>> r.trim(1) |
| 833 |
>>> r |
| 834 |
MyFakeDir/ |
| 835 |
├─Vogel.txt |
| 836 |
├─monkish.txt |
| 837 |
├─jowly.txt |
| 838 |
├─scrooge/ |
| 839 |
├─Uganda/ |
| 840 |
└─pedantic/ |
| 841 |
|
| 842 |
``` |
| 843 |
|
| 844 |
|
| 845 |
Parameters |
| 846 |
---------- |
| 847 |
depthlimit : non-negative int |
| 848 |
Files beyond this depth will be cut. The root has depth `0`. |
| 849 |
|
| 850 |
Raises |
| 851 |
------ |
| 852 |
ValueError |
| 853 |
`depthlimit` is not a non-negative int |
| 854 |
|
| 855 |
Returns |
| 856 |
------- |
| 857 |
None. |
| 858 |
|
| 859 |
""" |
| 860 |
depthlimit = int(depthlimit) |
| 861 |
if depthlimit < 0: |
| 862 |
raise ValueError('depthlimit must be non-negative int') |
| 863 |
depthlimit += self.depth |
| 864 |
def trim_apply(f, depthlimit): |
| 865 |
if depthlimit is not None and f.depth == depthlimit: |
| 866 |
if isinstance(f, FakeDir): |
| 867 |
f.delete(f.listdir()) |
| 868 |
if depthlimit == self.depth: |
| 869 |
self.delete(self.listdir()) |
| 870 |
else: |
| 871 |
self.walk_apply(trim_apply, depthlimit=depthlimit) |
| 872 |
|
| 873 |
def walk_apply(self, foo, *args, **kwargs): |
| 874 |
""" |
| 875 |
Recursively apply a function the children of self (and so on) |
| 876 |
|
| 877 |
``` |
| 878 |
>>> import seedir as sd |
| 879 |
>>> r = sd.randomdir(seed=5) |
| 880 |
>>> r |
| 881 |
MyFakeDir/ |
| 882 |
├─senor.txt |
| 883 |
├─verb.txt |
| 884 |
├─takeoff.txt |
| 885 |
├─monastic/ |
| 886 |
│ ├─paddy.txt |
| 887 |
│ ├─ewe.txt |
| 888 |
│ ├─advantage.txt |
| 889 |
│ ├─hooves/ |
| 890 |
│ └─registrar/ |
| 891 |
└─zag/ |
| 892 |
├─thematic.txt |
| 893 |
├─inelastic.txt |
| 894 |
├─fierce.txt |
| 895 |
├─gout/ |
| 896 |
└─stein/ |
| 897 |
├─vector.txt |
| 898 |
├─sora.txt |
| 899 |
└─proviso.txt |
| 900 |
|
| 901 |
>>> def replace_txt(f): |
| 902 |
... f.name = f.name.replace('txt', 'pdf') |
| 903 |
|
| 904 |
>>> r.walk_apply(replace_txt) |
| 905 |
>>> r |
| 906 |
MyFakeDir/ |
| 907 |
├─senor.pdf |
| 908 |
├─verb.pdf |
| 909 |
├─takeoff.pdf |
| 910 |
├─monastic/ |
| 911 |
│ ├─paddy.pdf |
| 912 |
│ ├─ewe.pdf |
| 913 |
│ ├─advantage.pdf |
| 914 |
│ ├─hooves/ |
| 915 |
│ └─registrar/ |
| 916 |
└─zag/ |
| 917 |
├─thematic.pdf |
| 918 |
├─inelastic.pdf |
| 919 |
├─fierce.pdf |
| 920 |
├─gout/ |
| 921 |
└─stein/ |
| 922 |
├─vector.pdf |
| 923 |
├─sora.pdf |
| 924 |
└─proviso.pdf |
| 925 |
|
| 926 |
``` |
| 927 |
|
| 928 |
Parameters |
| 929 |
---------- |
| 930 |
foo : function |
| 931 |
Function to apply. |
| 932 |
*args : |
| 933 |
Additional positional arguments for `foo`. |
| 934 |
**kwargs : |
| 935 |
Additional keyword arguments for `foo`. |
| 936 |
|
| 937 |
Returns |
| 938 |
------- |
| 939 |
None. |
| 940 |
|
| 941 |
""" |
| 942 |
foo(self, *args, **kwargs) |
| 943 |
for f in self._children: |
| 944 |
if isinstance(f, FakeDir): |
| 945 |
f.walk_apply(foo, *args, **kwargs) |
| 946 |
else: |
| 947 |
foo(f, *args, **kwargs) |
| 948 |
|
| 949 |
def get_random_int(collection, seed=None): |
| 950 |
''' |
| 951 |
Helper function for selecting a random integer, used by seedir.populate(). |
| 952 |
|
| 953 |
Parameters |
| 954 |
---------- |
| 955 |
collection : list-like |
| 956 |
Collection of integers to select from. |
| 957 |
seed : int or float, optional |
| 958 |
Random seed. The default is None. |
| 959 |
|
| 960 |
Raises |
| 961 |
------ |
| 962 |
TypeError |
| 963 |
Non-integer found. |
| 964 |
|
| 965 |
Returns |
| 966 |
------- |
| 967 |
r : int |
| 968 |
Randomly chosen int from collection. |
| 969 |
|
| 970 |
''' |
| 971 |
r = random.Random(seed).choice(collection) |
| 972 |
if not isinstance(r, int): |
| 973 |
raise TypeError('non int found') |
| 974 |
return r |
| 975 |
|
| 976 |
def populate(fakedir, depth=3, folders=2, files=2, stopchance=.5, seed=None, |
| 977 |
extensions=['txt']): |
| 978 |
''' |
| 979 |
Function for populating `seedir.fakedir.FakeDir` objects with random files and folders. |
| 980 |
Used by `seedir.fakedir.randomdir()`. Random dictionary names are chosen |
| 981 |
for file and folder names. |
| 982 |
|
| 983 |
Parameters |
| 984 |
---------- |
| 985 |
fakedir : seedir.fakedir.FakeDir |
| 986 |
Fake directory to populate. |
| 987 |
depth : int, optional |
| 988 |
Maximum depth to create folders and files. The default is `3`. |
| 989 |
folders : int or collection of integers, optional |
| 990 |
Parameter for setting the number of folders per directory. |
| 991 |
The default is `2`. If `int`, represents the number of folders |
| 992 |
per directory. If collection of integers, a random value will be |
| 993 |
chosen from the collection each time a directory is popualted. |
| 994 |
files : int or collection of integers, optional, optional |
| 995 |
Same as the folders parameter, but for files. |
| 996 |
stopchance : float between 0 and 1, optional |
| 997 |
Chance that an added folder will not be populated. The default is `.5`. |
| 998 |
seed : int or float, optional |
| 999 |
Random seed. The default is `None`. |
| 1000 |
extensions : list-likie, optional |
| 1001 |
Collection of extensions to randomly select from for files. The |
| 1002 |
default is `['txt']`. Leading period can be included or omitted. |
| 1003 |
|
| 1004 |
Raises |
| 1005 |
------ |
| 1006 |
ValueError |
| 1007 |
Issue selecting int from folders or files. |
| 1008 |
|
| 1009 |
Returns |
| 1010 |
------- |
| 1011 |
None, input is modified in place. |
| 1012 |
|
| 1013 |
''' |
| 1014 |
random.seed(seed) |
| 1015 |
if not isinstance(folders, int): |
| 1016 |
try: |
| 1017 |
fold_num = get_random_int(folders, seed=seed) |
| 1018 |
except: |
| 1019 |
raise ValueError('folders must be an int or collection of int') |
| 1020 |
else: |
| 1021 |
fold_num = folders |
| 1022 |
if not isinstance(files, int): |
| 1023 |
try: |
| 1024 |
file_num = get_random_int(files, seed=seed) |
| 1025 |
except: |
| 1026 |
raise ValueError('files must be an int or collection of int') |
| 1027 |
else: |
| 1028 |
file_num = files |
| 1029 |
for i in range(file_num): |
| 1030 |
name = random.choice(words) + random.choice(extensions) |
| 1031 |
while name in [f.name for f in fakedir._children]: |
| 1032 |
name = random.choice(words) + random.choice(extensions) |
| 1033 |
fakedir.create_file(name) |
| 1034 |
for i in range(fold_num): |
| 1035 |
name = random.choice(words) |
| 1036 |
while name in [f.name for f in fakedir._children]: |
| 1037 |
name = random.choice(words) |
| 1038 |
fakedir.create_folder(name) |
| 1039 |
for f in fakedir._children: |
| 1040 |
if isinstance(f, FakeDir): |
| 1041 |
if f.depth <= depth and random.uniform(0, 1) > stopchance: |
| 1042 |
if seed is not None: |
| 1043 |
seed += random.random() |
| 1044 |
populate(f, depth=depth, folders=folders, files=files, |
| 1045 |
seed=seed, stopchance=stopchance, |
| 1046 |
extensions=extensions) |
| 1047 |
|
| 1048 |
def randomdir(depth=2, files=range(1,4), folders=range(0,4), |
| 1049 |
stopchance=.5, seed=None, name='MyFakeDir', extensions=['txt']): |
| 1050 |
''' |
| 1051 |
Create a randomized `seedir.fakedir.FakeDir`, initialized with random |
| 1052 |
dictionary words. |
| 1053 |
|
| 1054 |
``` |
| 1055 |
>>> import seedir as sd |
| 1056 |
>>> sd.randomdir(seed=7) |
| 1057 |
MyFakeDir/ |
| 1058 |
├─Hardin.txt |
| 1059 |
├─Kathleen.txt |
| 1060 |
├─berserk/ |
| 1061 |
└─pineapple/ |
| 1062 |
├─visceral.txt |
| 1063 |
├─gestural.txt |
| 1064 |
├─plenty.txt |
| 1065 |
├─discoid/ |
| 1066 |
│ ├─eclat.txt |
| 1067 |
│ └─milord/ |
| 1068 |
├─Offenbach/ |
| 1069 |
│ ├─Trianon.txt |
| 1070 |
│ ├─Monday.txt |
| 1071 |
│ ├─ditty.txt |
| 1072 |
│ ├─peddle/ |
| 1073 |
│ ├─delta/ |
| 1074 |
│ └─irredentism/ |
| 1075 |
└─Perseus/ |
| 1076 |
├─hothouse.txt |
| 1077 |
├─clock.txt |
| 1078 |
├─covetous/ |
| 1079 |
└─Ekstrom/ |
| 1080 |
|
| 1081 |
``` |
| 1082 |
|
| 1083 |
Parameters |
| 1084 |
---------- |
| 1085 |
depth : int, optional |
| 1086 |
Maximum depth to create folders and files. The default is `3`. |
| 1087 |
folders : int or collection of integers, optional |
| 1088 |
Parameter for setting the number of folders per directory. |
| 1089 |
The default is `range(1,4)`. If `int`, represents the number of folders |
| 1090 |
per directory. If collection of integers, a random value will be |
| 1091 |
chosen from the collection each time a directory is popualted. |
| 1092 |
files : int or collection of integers, optional, optional |
| 1093 |
Same as the `folders` parameter, but for files. The default |
| 1094 |
is `range(0,4)`. |
| 1095 |
stopchance : float between 0 and 1, optional |
| 1096 |
Chance that an added folder will not be populated. The default is `.5`. |
| 1097 |
seed : int or float, optional |
| 1098 |
Random seed. The default is `None`. |
| 1099 |
extensions : list-likie, optional |
| 1100 |
Collection of extensions to randomly select from for files. The |
| 1101 |
default is `['txt']`. Leading period can be included or omitted. |
| 1102 |
|
| 1103 |
Returns |
| 1104 |
------- |
| 1105 |
top : seedir.fakedir.FakeDir |
| 1106 |
Fake directory. |
| 1107 |
|
| 1108 |
''' |
| 1109 |
top = FakeDir(name) |
| 1110 |
new_ex = [] |
| 1111 |
for x in extensions: |
| 1112 |
if x[0] != '.': |
| 1113 |
new_ex.append('.' + x) |
| 1114 |
else: |
| 1115 |
new_ex.append(x) |
| 1116 |
populate(top, depth, folders, files, seed=seed, stopchance=stopchance, |
| 1117 |
extensions=new_ex) |
| 1118 |
return top |
| 1119 |
|
| 1120 |
def recursive_add_fakes(path, parent, depth=0, depthlimit=None, |
| 1121 |
itemlimit=None, first=None, sort=False, |
| 1122 |
sort_reverse=False, sort_key=None, |
| 1123 |
include_folders=None, exclude_folders=None, |
| 1124 |
include_files=None, exclude_files=None, |
| 1125 |
mask=None, regex=False): |
| 1126 |
''' |
| 1127 |
Recursive helper function for seedir.fakedir(), for creating a |
| 1128 |
fake folder tree from a real one. |
| 1129 |
|
| 1130 |
Parameters |
| 1131 |
---------- |
| 1132 |
path : str |
| 1133 |
System path of a folder. |
| 1134 |
parent : seedir.fakedir.FakeDir |
| 1135 |
Fake directory to add items to. |
| 1136 |
depth : int, optional |
| 1137 |
Tracker for depth of folders traversed. The default is 0. |
| 1138 |
depthlimit : int, optional |
| 1139 |
Limit on the depth of folders to traverse. The default is None. |
| 1140 |
itemlimit : int, optional |
| 1141 |
Limit on the number of items to include per directory. |
| 1142 |
The default is None. |
| 1143 |
first : 'folders' or 'files', optional |
| 1144 |
Sort to have folders or files appear first. The default is None. |
| 1145 |
sort : bool, optional |
| 1146 |
Apply a sort to items in each directory. The default is False. |
| 1147 |
sort_reverse : bool, optional |
| 1148 |
Reverse the sort. The default is False. |
| 1149 |
sort_key : function, optional |
| 1150 |
Key function for sorting item names. The default is None. |
| 1151 |
include_folders, exclude_folders, include_files, exclude_files : str, list-like, or None, optional |
| 1152 |
Folder / file names to include or exclude. The default is None. |
| 1153 |
mask : function, optional |
| 1154 |
Function for filtering items. Absolute paths of each individual item |
| 1155 |
are passed to the mask function. If True is returned, the |
| 1156 |
item is kept. The default is None. |
| 1157 |
regex : bool, optional |
| 1158 |
Interpret include/exclude folder/file arguments as regular |
| 1159 |
expressions. The default is False. |
| 1160 |
|
| 1161 |
Returns |
| 1162 |
------- |
| 1163 |
None. |
| 1164 |
|
| 1165 |
''' |
| 1166 |
RDS = RealDirStructure() |
| 1167 |
if depthlimit is not None and depth >= depthlimit: |
| 1168 |
return |
| 1169 |
depth +=1 |
| 1170 |
listdir = listdir_fullpath(path) |
| 1171 |
if sort or first is not None: |
| 1172 |
listdir = RDS.sort_dir(listdir, first=first, |
| 1173 |
sort_reverse=sort_reverse, sort_key=sort_key) |
| 1174 |
if any(arg is not None for arg in [ |
| 1175 |
include_folders, |
| 1176 |
exclude_folders, |
| 1177 |
include_files, |
| 1178 |
exclude_files, |
| 1179 |
mask]): |
| 1180 |
listdir = RDS.filter_items(listdir, |
| 1181 |
include_folders=include_folders, |
| 1182 |
exclude_folders=exclude_folders, |
| 1183 |
include_files=include_files, |
| 1184 |
exclude_files=exclude_files, |
| 1185 |
regex=regex, |
| 1186 |
mask=mask) |
| 1187 |
for i, f in enumerate(listdir): |
| 1188 |
name = os.path.basename(f) |
| 1189 |
if i == itemlimit: |
| 1190 |
break |
| 1191 |
if os.path.isdir(f): |
| 1192 |
new = FakeDir(name=name, parent=parent) |
| 1193 |
recursive_add_fakes(path=f, parent=new, depth=depth, |
| 1194 |
depthlimit=depthlimit, |
| 1195 |
itemlimit=itemlimit, |
| 1196 |
include_folders=include_folders, |
| 1197 |
exclude_folders=exclude_folders, |
| 1198 |
include_files=include_files, |
| 1199 |
exclude_files=exclude_files, |
| 1200 |
mask=mask, regex=regex) |
| 1201 |
else: |
| 1202 |
new = FakeFile(name=name, parent=parent) |
| 1203 |
|
| 1204 |
def fakedir(path, depthlimit=None, itemlimit=None, first=None, |
| 1205 |
sort=False, sort_reverse=False, sort_key=None, |
| 1206 |
include_folders=None, exclude_folders=None, include_files=None, |
| 1207 |
exclude_files=None, mask=None, regex=True): |
| 1208 |
''' |
| 1209 |
Function for creating a `seedir.fakedir.FakeDir` (representation of a directory) |
| 1210 |
from a real system directory. Rather than immediately representing |
| 1211 |
a directory as a string (`seedir.realdir.seedir()`), this function can be used |
| 1212 |
to create an editable representation of the directory, or to join one or |
| 1213 |
more directories. |
| 1214 |
|
| 1215 |
``` |
| 1216 |
>>> import seedir as sd |
| 1217 |
>>> f = sd.fakedir('.', depthlimit=0) |
| 1218 |
>>> type(f) |
| 1219 |
<class 'seedir.fakedir.FakeDir'> |
| 1220 |
|
| 1221 |
``` |
| 1222 |
|
| 1223 |
Parameters |
| 1224 |
---------- |
| 1225 |
path : str |
| 1226 |
System path of a directory. |
| 1227 |
depthlimit : int, optional |
| 1228 |
Limit on the depth of directories to traverse. Folders at the depth |
| 1229 |
limit will be included, but their contents will not be. |
| 1230 |
The default is `None`. |
| 1231 |
itemlimit : int, optional |
| 1232 |
Limit on the number of items to include per directory. |
| 1233 |
The default is `None`, meaning all items will be added. The priority |
| 1234 |
of items is determined by `os.listdir()`, unless sorting arguments |
| 1235 |
are passed. |
| 1236 |
first : 'folders' or 'files', optional |
| 1237 |
Sort to show folders or files first. The default is `None`. |
| 1238 |
sort : bool, optional |
| 1239 |
Apply a (name) sort on each directory. The default is `False`. |
| 1240 |
sort_reverse : bool, optional |
| 1241 |
Reverse the sort. The default is `False`. |
| 1242 |
sort_key : function, optional |
| 1243 |
Key function for sorting the file names. The default is `None`. |
| 1244 |
include_folders, exclude_folders, include_files, exclude_files : str, list-like, or None, optional |
| 1245 |
Folder / file names to include or exclude. The default is `None`. |
| 1246 |
mask : function, optional |
| 1247 |
Function for filtering items. Absolute paths of each individual item |
| 1248 |
are passed to the mask function. If `True` is returned, the |
| 1249 |
item is kept. The default is `None`. |
| 1250 |
regex : bool, optional |
| 1251 |
Interpret include/exclude folder/file arguments as regular |
| 1252 |
expressions. The default is `False`. |
| 1253 |
|
| 1254 |
Raises |
| 1255 |
------ |
| 1256 |
FakedirError |
| 1257 |
path does not point to a directory. |
| 1258 |
|
| 1259 |
Returns |
| 1260 |
------- |
| 1261 |
output : seedir.fakedir.FakeDir |
| 1262 |
Fake directory matching the path. |
| 1263 |
|
| 1264 |
''' |
| 1265 |
if not os.path.isdir(path): |
| 1266 |
raise FakedirError('path must be a directory') |
| 1267 |
output = FakeDir(os.path.basename(path)) |
| 1268 |
recursive_add_fakes(path, parent=output, depthlimit=depthlimit, |
| 1269 |
itemlimit=itemlimit, |
| 1270 |
first=first, |
| 1271 |
sort=sort, |
| 1272 |
sort_reverse=sort_reverse, |
| 1273 |
sort_key=sort_key, |
| 1274 |
include_folders=include_folders, |
| 1275 |
exclude_folders=exclude_folders, |
| 1276 |
include_files=include_files, |
| 1277 |
exclude_files=exclude_files, |
| 1278 |
mask=mask, regex=regex) |
| 1279 |
return output |
| 1280 |
|
| 1281 |
def fakedir_fromstring(s, start_chars=None, name_chars=None, |
| 1282 |
header_regex=None, name_regex=None, |
| 1283 |
supername='FakeDir', parse_comments=True): |
| 1284 |
''' |
| 1285 |
Convert a string folder tree diagram into a `seedir.fakedir.FakeDir`. |
| 1286 |
This can be used to read in external representations of folder structures, |
| 1287 |
edit them, and recreate them in a new location. |
| 1288 |
|
| 1289 |
This function has mostly been tested with examples from Stack Overflow |
| 1290 |
and other Python learning sites (as well as output from `seedir.realdir.seedir()`). |
| 1291 |
There are surely cases which will causes errors or unexpected results. |
| 1292 |
|
| 1293 |
``` |
| 1294 |
>>> import seedir as sd |
| 1295 |
>>> s = """doc/ |
| 1296 |
... ├─_static/ |
| 1297 |
... │ ├─embedded/ |
| 1298 |
... │ │ ├─deep_file |
| 1299 |
... │ │ └─very/ |
| 1300 |
... │ │ └─deep/ |
| 1301 |
... │ │ └─folder/ |
| 1302 |
... │ │ └─very_deep_file |
| 1303 |
... │ └─less_deep_file |
| 1304 |
... ├─about.rst |
| 1305 |
... ├─conf.py |
| 1306 |
... └─index.rst""" |
| 1307 |
|
| 1308 |
>>> f = sd.fakedir_fromstring(s) # now can be edited or restyled |
| 1309 |
>>> f.seedir(style='spaces') |
| 1310 |
doc/ |
| 1311 |
_static/ |
| 1312 |
embedded/ |
| 1313 |
deep_file |
| 1314 |
very/ |
| 1315 |
deep/ |
| 1316 |
folder/ |
| 1317 |
very_deep_file |
| 1318 |
less_deep_file |
| 1319 |
about.rst |
| 1320 |
conf.py |
| 1321 |
index.rst |
| 1322 |
|
| 1323 |
``` |
| 1324 |
|
| 1325 |
|
| 1326 |
Parameters |
| 1327 |
---------- |
| 1328 |
s : str |
| 1329 |
String representation a folder tree. |
| 1330 |
start_chars : str, optional |
| 1331 |
A string of characters which will be searched for as the start |
| 1332 |
of a folder or file name. The default is `None`, in which case the |
| 1333 |
characters are all letters, numbers, and punctuation marks except |
| 1334 |
for `/:?"*<>|` or `+=-`. |
| 1335 |
name_chars : str, optional |
| 1336 |
A string of characters which will be searched for as being part |
| 1337 |
of a file or folder name. The default is `None`, in which case the |
| 1338 |
characters are all letters, numbers, punctuation marks except |
| 1339 |
for `/:?"*<>|,` and spaces. |
| 1340 |
header_regex : str, optional |
| 1341 |
Regular expression to match the "header" of each line, i.e. the |
| 1342 |
structural characters of the folder diagram. The default is `None`. |
| 1343 |
If passed, the `start_chars` argument will be ignored. This and |
| 1344 |
`name_regex` are intended to provide functionality for parsing |
| 1345 |
specific or unusual cases. |
| 1346 |
name_regex : str, optional |
| 1347 |
Regular expression to match all the folder or file names. |
| 1348 |
The default is `None`. |
| 1349 |
If passed, the `start_chars` argument will be ignored. |
| 1350 |
supername : str, optional |
| 1351 |
Name to give the head directory if one cannot be found. |
| 1352 |
The default is `'FakeDir'`. This can happen when there is no clear |
| 1353 |
head directory in the string. |
| 1354 |
parse_comments : bool, optional |
| 1355 |
Try to parse and remove Python comments (following `#`). |
| 1356 |
The default is `True`. |
| 1357 |
|
| 1358 |
Returns |
| 1359 |
------- |
| 1360 |
seedir.fakedir.FakeDir |
| 1361 |
Fake directory corresponding to the input string. |
| 1362 |
|
| 1363 |
''' |
| 1364 |
|
| 1365 |
|
| 1366 |
slashes = ['/', '\\', os.sep] |
| 1367 |
joinedslashes = ''.join(slashes) |
| 1368 |
|
| 1369 |
|
| 1370 |
keyboard_chars = (string.ascii_letters + string.digits |
| 1371 |
+ string.punctuation) |
| 1372 |
filtered = "".join([c for c in keyboard_chars if c not in '/:?"*<>|']) |
| 1373 |
if start_chars is None: |
| 1374 |
start_chars = "".join([c for c in filtered if c not in '+=-']) |
| 1375 |
if name_chars is None: |
| 1376 |
name_chars = filtered + ' ' + '-' |
| 1377 |
|
| 1378 |
if header_regex is None: |
| 1379 |
header_regex = '.*?(?=[{}])'.format(start_chars) |
| 1380 |
|
| 1381 |
custom_name_regex = True |
| 1382 |
if name_regex is None: |
| 1383 |
name_regex = '[{}]*[/\\\\]*'.format(name_chars) |
| 1384 |
custom_name_regex = False |
| 1385 |
|
| 1386 |
|
| 1387 |
byline = s.split('\n') |
| 1388 |
|
| 1389 |
|
| 1390 |
names = [] |
| 1391 |
depths = [] |
| 1392 |
|
| 1393 |
|
| 1394 |
for line in byline: |
| 1395 |
|
| 1396 |
|
| 1397 |
if not line: |
| 1398 |
continue |
| 1399 |
|
| 1400 |
|
| 1401 |
header = re.match(header_regex, line) |
| 1402 |
if header is None: |
| 1403 |
continue |
| 1404 |
else: |
| 1405 |
header = header.group() |
| 1406 |
depth = len(header) |
| 1407 |
|
| 1408 |
|
| 1409 |
search_str = line if custom_name_regex else line[depth:] |
| 1410 |
name = re.match(name_regex, search_str) |
| 1411 |
if name is None: |
| 1412 |
continue |
| 1413 |
else: |
| 1414 |
name = name.group() |
| 1415 |
|
| 1416 |
|
| 1417 |
if '#' in name and parse_comments: |
| 1418 |
name = re.match('.*?(?=#)', name).group().strip() |
| 1419 |
if not name: |
| 1420 |
continue |
| 1421 |
|
| 1422 |
|
| 1423 |
names.append(name) |
| 1424 |
depths.append(depth) |
| 1425 |
|
| 1426 |
|
| 1427 |
fakeitems = [] |
| 1428 |
superparent = None |
| 1429 |
min_depth = min(depths) |
| 1430 |
|
| 1431 |
|
| 1432 |
|
| 1433 |
|
| 1434 |
|
| 1435 |
if len([d for d in depths if d == min_depth]) > 1: |
| 1436 |
superparent = FakeDir(supername) |
| 1437 |
|
| 1438 |
|
| 1439 |
min_depth_index1 = depths.index(min_depth) |
| 1440 |
if any(i > min_depth for i in depths[:min_depth_index1]): |
| 1441 |
superparent = FakeDir(supername) |
| 1442 |
|
| 1443 |
|
| 1444 |
for i, (name, depth) in enumerate(zip(names, depths)): |
| 1445 |
|
| 1446 |
|
| 1447 |
|
| 1448 |
|
| 1449 |
is_folder = False |
| 1450 |
if name.strip()[-1] in slashes: |
| 1451 |
is_folder = True |
| 1452 |
if i < len(names) - 1: |
| 1453 |
if depths[i + 1] > depth: |
| 1454 |
is_folder = True |
| 1455 |
FakeConstructor = FakeDir if is_folder else FakeFile |
| 1456 |
|
| 1457 |
|
| 1458 |
fmt_name = name.rstrip(joinedslashes) |
| 1459 |
|
| 1460 |
|
| 1461 |
|
| 1462 |
if depth == min_depth: |
| 1463 |
item = FakeConstructor(name=fmt_name, parent=superparent) |
| 1464 |
fakeitems.append(item) |
| 1465 |
|
| 1466 |
|
| 1467 |
else: |
| 1468 |
|
| 1469 |
|
| 1470 |
preceding_depths = depths[:i] |
| 1471 |
shallower = [d for d in preceding_depths if d < depth] |
| 1472 |
|
| 1473 |
|
| 1474 |
|
| 1475 |
|
| 1476 |
if shallower: |
| 1477 |
max_shallower = max([d for d in preceding_depths if d < depth]) |
| 1478 |
parent_index = max(idx for idx, val in enumerate(preceding_depths) if val == max_shallower) |
| 1479 |
parent = fakeitems[parent_index] |
| 1480 |
|
| 1481 |
|
| 1482 |
|
| 1483 |
|
| 1484 |
else: |
| 1485 |
parent = superparent |
| 1486 |
|
| 1487 |
|
| 1488 |
item = FakeConstructor(name=fmt_name, parent=parent) |
| 1489 |
fakeitems.append(item) |
| 1490 |
|
| 1491 |
|
| 1492 |
|
| 1493 |
if superparent is not None: |
| 1494 |
return superparent |
| 1495 |
else: |
| 1496 |
idx = depths.index(min_depth) |
| 1497 |
return fakeitems[idx] |
| 1498 |
|