-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPowerWalk.py
executable file
·2779 lines (2384 loc) · 111 KB
/
PowerWalk.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# PowerWalk: More capable version os Python's os.walk.
# 2018-04-21: `PowerWalk.py` split out of my `countTags.py`.
#
#pylint: disable=W0212,W0603
#
import sys
import os
import argparse
import re
import random
import urllib
import stat
from collections import namedtuple, defaultdict
from os.path import getatime, getctime, getmtime, getsize, splitext
from enum import Enum
from shutil import copyfile
from subprocess import check_output, CalledProcessError
from typing import Dict, Any, Union, List # , Callable
# Libraries for particular file "formats":
import codecs
import io
#from versionStatus import getGitStatus # gitStatus
assert sys.version_info[0] >= 3
verbose = 0 # Also set by PowerWalk.setOptions("verbose")
stats = defaultdict(int)
def warning(lvl:int, msg:str):
if (verbose>=lvl): sys.stderr.write("%s\n" % (msg))
# try:
# import zip
# except ImportError:
# warning(0, "Cannot import module 'zip'.")
try:
import gzip
except ImportError:
warning(0, "Cannot import module 'gzip'.")
try:
import tarfile
except ImportError:
warning(0, "Cannot import module 'tarfile'.")
# try:
# import uu
# except ImportError:
# warning(0, "Cannot import module 'uu'.")
# try:
# import bz2
# except ImportError:
# warning(0, "Cannot import module 'bz2'.")
# try:
# import zlib
# except ImportError:
# warning(0, "Cannot import module 'zlib'.") # supports gzip
# try:
# import zipfile
# except ImportError:
# warning(0, "Cannot import module 'zipfile'.")
__metadata__ = {
"title" : "PowerWalk",
"description" : "Like os.walk, but with many features of *nix 'find', etc.",
"rightsHolder" : "Steven J. DeRose",
"creator" : "http://viaf.org/viaf/50334488",
"type" : "http://purl.org/dc/dcmitype/Software",
"language" : "Python 3.7",
"created" : "2018-04-21",
"modified" : "2023-12-01",
"publisher" : "http://github.com/sderose",
"license" : "https://creativecommons.org/licenses/by-sa/3.0/"
}
__version__ = __metadata__["modified"]
descr = """
=Description=
PowerWalk is similar to Python's built-in `os.walk()`, but offers many
additional features, especially for file selection. In that respect it is
more similar to the *nix `find` command, but can be used either as a shell
command or as an API.
It has a simple iterator that returns a triple for each item,
containing a path, an (optional) open file handle (for non-containers), and a flag
that says whether this triple represents a container OPEN (such as starting a new
directory or tar file), an actual LEAF item, or a container CLOSE.
PowerWalk can also:
* skip returning items for OPEN and CLOSE of containers;
* return all paths in absolute form;
* open and/or close leaf files for you;
* open several kinds of compressed and container formats (such as `tar`),
* include or exclude by extensions, name patterns, path patterns, permissions, dates, etc.;
* exclude hidden or backup items, or by filesystem type or `file` matches;
* sort the items of each directory in various orders;
* random-sample only a % of eligible items;
* raise Exceptions instead of returning items for OPEN and CLOSE.
==Usage as a command==
If run on its own, `PowerWalk` displays the paths of selected
files under the specified
directory(s), or the current directory if none are specified (with `-r`
you must specify "*", sorry).
The default output format is pretty much like 'ls'. Thus, a recursive list
comes out with a heading for each directory, like this:
subDir1 file1 subdir2 file2
./subDir1:
file1.1 file1.2...
./subDir2:
file2.1 file2.2...
Slightly unlike "ls", you can get recursion via "-r" or "--recursive"
as well as "-R". With "ls", "-r" gets reverse sorting; in PowerWalk get
that with "--reverseSort" (or abbreviations such as "--rev"), or various
other sorts with "--sort [what]".
To get a flat list of absolute paths (such as to feed to another command via "``",
in *nix you'd probably switch to "find". Here you can do:
PowerWalk -R --flat
would give:
[TODO: Add sample output]
To get all items quoted, use "--quote".
To avoid separate lines for directories, add "--type f"
Several special options apply in that case:
* `--copyTo [path]` -- Copy the chosen files to this directory. This flattens
whatever arrangement they come from -- all the leafs end up together.
See also
`--serialize`, which supports multiple files with the same name,
by appending numbers.
* `--exec` "[...{}...]\\;" -- Run a given command on each selected item,
much like `find --exec`. Output from the runs is printed unless
you specify `--quiet`.
* `--fileTypeFlag` -- Append a flag-character like "ls -F".
* `--serialize` -- put a serial number on each file with `--copyTo`
(use `--serializeFormat` to set the format (default "_%04d")).
===Command output format===
* `--oformat` [x] -- formats the list as 'plain', 'json', 'html',
or 'sexp' (LISP s-expressions).
Setting this to other than "plain" (the default), overrides specific
delimiter options described below.
* `--openQuote "x"` and `--closeQuote "y"` -- set delimiters to be put
before and after each name (typically both would be set to '"' or "'").
`--quote` may be used as shorthand to set both to "'", or
`--no-quote` to set both to "" (nothing). These options
are overridden by `--oformat` settings that demand certain quoting,
such as json, html, and sexp.
* `--anonymousClose` -- if set, do not print the name of directories or
other containers as they close.
* `--openDirString` and `--closeDirString` -- Display these around
the contents of directories and other containers (after their name').
For examle, "{" and "}". Default: "" and "".
* `--iString [s]` -- Repeat this string to create indentation.
Default: " ".
* `--itemSep` -- Put this in to separate items (e.g., a comma).
===General options available in command or API use===
* Our chief options, for file '''selection''':
Note: "include" and "exclude" in option names can be abbreviated to
just "i" and "e", and a hyphen may be used instead of camel-case for
these options.
** `--includeNames` and `--excludeNames` are
like grep `-include` and `-exclude`, but take full regexes to match against (not globs).
''Note'': matches may occur anywhere within the name (including the extension).
To require a match to the complete name, start the regex with "^" and end it
with "$".
** `-include-dirs` and `-exclude-dirs`are
like grep (and also available as `--includeDirs` and `--excludeDirs`),
but take full regexes to match against.
** `--includeExtensions` and `--excludeExtensions` match file extensions
(without the ".") against full regexes. In particular, the "|" operator
is supported for "or". For example: `--ie "(py|pl|pm|cc)" works.
** `--includeFileInfos` and `--excludeFileInfos` match
characteristics reported by the *nix `file` command.
For example, this makes it easy to get Python files whether they have a `.py`
extension of not.
** `--backups` includes backup files, hidden files, etc.
** There is no `--dirOnly` option, but to get only directories, just use
"--type d".
** `--followLinks` makes PowerWalk treat *nix links if various ways.
The values are defined by Enum "PWDisp" (for "disposition"):
PWDisp.IGNORE: Ignore the link
PWDisp.RETURN: Return the link itself
PWDisp.FOLLOW: Resolve the link to its destination (if possible),
and return that.
** `--followWeblocs` makes PowerWalk follow Mac .webloc files,
which contain a wrapped-up URL, and fetch the referenced document.
** `--recursive` or `-r` (which you'll often want) makes `PowerWalk` descend
into sub-directories (but not tar or other container files -- for which
there are separate options). If directories are specified directly, rathern
than just being reached, the wil be recursed into in any case. Not sure
if this is best or not.
See "Known bugs and limitations" for more information.
** `--minDepth` and `maxDepth` constrain what
directory or container depth limits to return files from.
** `--type [t]` is similar to the same-name option in `find`, except that
you can give more than one type-letter in the argument. It lets you choose
one or more of: "b" (block special), "c" (character special), "d" (directory),
"f" (regular file), "l" (symbolic link), "p" (FIFO), "s" (socket).
* Our two options, for '''selection''' and '''container''' files:
** `--containers` can be set in order to return events not just for
files, but also for the OPEN and CLOSE of directories (as well as tar
or other container files if those are to be opened).
** options allow automatic opening of zip, gzip, uuencode, and other
container files (not all the envisioned ones are supported yet, however).
One that can have internal filesystems (tar, dmg, etc) can be treated
as if they were just directories.
* Our three options, for '''selection''', '''containers''', and '''reading''':
** `--open` will cause files to be opened automatically, and the handle
passed back, while `--close` automatically closes them when you request
the next event.
** what encoding to open the file with (`--encoding`, default utf-8)
** the file `--mode` (read or write, binary, etc) to apply.
* Amongst our options:
** `--sort` enables sorting found files into various orders
(see under "Other Options" below for details).
** `--sampleFactor` lets you random-sample only some of the files
** `--ignorables` adds events for ignorable leafs (with a special type field)
** `--missing` adds events for nonexistent or unopenable files
** `--errorEvents` adds events for errors such as unreadable files, etc.
==Usage from code==
PowerWalk can be used as an iterator/generator. To just get a lot of
files, each passed back with its full path and an open file handle, do this:
from PowerWalk import PowerWalk, PWType
pw = PowerWalk("myDir1", recursive=True, open=True, close=True)
maxDepth = 0
for path, fh, what in pw.traverse():
if (what != PWType.LEAF): continue
nrecs = len(fh.readlines)
print("%6d lines in %s" % (nrecs, path))
`what` is a `PWType` Enum, one of:
PWType.OPEN -- Issued when a container (tar, directory, etc.) opens.
PWType.LEAF -- Issued when a file-like item is returned.
PWType.IGNORE -- Issued (only if requested), for items ignored.
PWType.CLOSE -- Issued when a container (tar, directory, etc.) closes.
PWType.MISSING -- Issued when a file cannot be found (or opened).
You can pass a list of paths as the first argument if desired.
Or you can pass one or a list of paths to `pw.traverse()`, which will use
them instead of the one(s) set on the constructor (if any).
You can ignore the OPEN and CLOSE events for directories (as shown here), or
turn off the `containers` option to have them not be generated at all.
The following example prints an
outline of the file directory subtree of the current directory.
The 'open' and 'close' options (both default to False), open each leaf
file for you, passing the handle back in `fh` (otherwise, `fh` is always
passed back as None), and close it on the next call to `traverse()`:
depth = 0
pw = PowerWalk(args.files, recursive=True, containers=True, open=True, close=True)
pw.setOption("includeExtensions", "txt")
for path, fh, what in pw.traverse():
if (what == PWType.OPEN):
print(" " * depth + ">>> Starting container %s" % (path))
depth += 1
elif (what == PWType.CLOSE):
depth -= 1
print(" " * depth + "<<< Ending %s" % (path))
else:
print(" " * depth + srcFile)
doOneFile(srcFile)
If you'd rather not hear about directory boundaries at all, do:
pw = PowerWalk("myDir", recursive=True, containers=False)
for itemInfo in pw.traverse():
path, fh, _what = itemInfo
nrecs = len(list(fh.readlines()))
print("%6d lines in %s" % (nrecs, path))
Or you can have an exception thrown on directory start/end
(some might say that's more Pythonic):
pw = PowerWalk("myDir", recursive=True, exceptions=True)
while True:
try:
path, fh, what = pw.traverse():
nrecs = len(list(fh.readlines()))
print("%6d lines in %s" % (nrecs, path))
except ItemOpening:
print("\n\n*** Starting directory")
except ItemClosing:
print("\n\n*** Ending directory")
except Finished:
break
Files and containers
that are filtered out do not get returned by default, but you can get
a PWType.IGNORE event (or an ItemIgnorable exception)
by setting the `ignorables` option.
''Note'': If you exercise options to traverse down into containers like
tar files, there may be no "path" per se for each individual item. In that case,
the returned path is that of the container, and you'll be given an open
file handle (whether or not you requested them for regular files).
The package also supplies a few useful independent tests and methods:
* isBackup(path) -- .bak, #foo#, Backup 3 of foo, etc.
* isHidden(path) -- Initial dot.
* isGenerated(path) -- extensions like .py, .o, etc.
* getGitStatus(path) -- (used to be here, now moved to ''versionStatus.py'').
=Methods=
The main method is `traverse()`, which unfortunately comes last in the
alphabetical list below.
==__init__(self, topLevelItems=None, options:Dict=None)==
Create a PowerWalk instance, which can traverse all the specified
items. If `topLevelItems` is None, the current directory is used;
if it is a list, all the named files and/or directories are used;
otherwise, it should be a string path to one named file or directory.
`options` is a dict of option name:value pairs. For example, to
traverse all the subdirectories of the specified items (if any),
pass `options` containing (at least) "recursive":True.
Options can also be set later using `setOption` (see below).
==addOptionsToArgparse(parser, prefix="", singletons=True)==
Add PowerWalk's options to a Python `argparse` instance.
If `prefix` is specified, it
is prefixed to each name (after the hyphens) to avoid name conflicts.
If `singletons` is True, this will include single-character synonyms.
Currently that's just `-r` for `--recursive`.
==getOption(self, name)==
Return the value of an available option (see ''setOption'').
==isBackup(path) [static]==
Test whether the given file's name indicates it is a backup, spare copy,
duplicate, or similar file. This method knows
quite a few naming conventions, but surely not all (for example, OS conventions
such as "backup of" presumably localize). For example, filenames that:
* start or end with tilde or pound-sign
* have extension "bak" or "bck"
* match r"^(backup|copy) (\\(?\\d+\\)? )?of"
* match r"\\b(backup|copy|bak)\\b" (but in these cases a warning is
issued unless ''--quiet'' is in effect).
* Mac OS X "Duplicate" does `foo.txt` -> `foo copy.txt` -> `foo copy 2.txt`
* emacs backups append "~" or "~\\d+~" to the filename
For relevant emacs settings, see
[https://stackoverflow.com/questions/151945]).
* emacs auto-save files put "#" at start and end of filename (but
are usually deleted when you exit).
==isHidden(path) [static]==
Returns whether the file is hidden (for the moment, this just means
that the name starts with "."; Windows and Mac invisible files should
be added).
==isStreamable(obj)==
Returns true if the obj is of one of the known streamable classes.
==getStats(self, writer=sys.stderr)==
Return a printable string listing various statistics, or
get individual stats from the PowerWalk object (they are actually kept
in a dict in a `TraversalState` object: `pw.travState.stats[name]`.
n = pw.getStat("regular")
gets you the total number of regular (non-dir, non-tar, non-ignored....) items
that have been returned so far.
The statistics include the number of files of each of these kinds:
* backup: apparent backup files
* directory
* gzip
* hiddenDir: directories that were skipped
* hiddenFile: files that were skipped
* regular
* tar
* tarSubdir: subdirectories inside tar files
The statistics also include:
* nodesTried: Total number of files examined. This
includes files that are filtered out, but not the descendants of directories,
tar files, or other containers that are themselves filtered out.
* containersOpened: Total number of directories, tar files, and other
containers that are actually opened.
* leafs: Files (not directories or containers) examined.
* ignored: Total items ignored (see below for finer details).
* errors: Files that could not be examined or opened, for
example due to not existing.
* maxDepthReached: How deep the deepest branch of the traversal went.
and the number of files that were skipped for various
reasons (if a file has several reasons to be skipped, only the one that
was checked first is counted):
* ignoredBackups: Due to being an apparent backup file.
* ignoredByExclExtensions: The file extension was excluded.
* ignoredByExclNames: The file name was excluded.
* ignoredByExclPaths: The file path was excluded.
* ignoredByInclExtensions: The file extension was included.
* ignoredByInclNames: The file name was included.
* ignoredByInclPaths: The file path was included.
* ignoredByMinDepth: Files found at too shallow nesting depth.
* ignoredHiddens: Due to having a dot-initial name.
* ignoredSamples: Due to `--sampleFactor`.
=======
==setOption(self, name, value)==
Change the value of an available option. Options can also
be set on the constructor via like-named keyword options, or en masse
using ` addOptionsToArgparse()` and `applyOptionsFromArgparse()`.
''Note'': There are a few more options that are not part of
the PowerWalk class, but are available when this script is run standalone.
They are described in the full list of options at the end of this help.
===File selection options===
''Note'': Regexes given for these options (where applicable), do not
automatically have "^" and "$" added. They match if they match anywhere
in the string. You can of course add one or both of those metacharacters
explicitly to the option value.
* "backups": Include `.bak` and similar files? Default: False.
* "excludeExtensions": Regex for item extensions not to allow. Default: "".
See also ''includeExtensions''. As with `grep` and many other
tools, exclusions override inclusions if both apply to the same file.
The "or" operator ("|") is allowed in the regex, which is an easy
way to exclude (or include) multiple extensions.
* "excludeFileInfos": Regex for `file` command results not to allow. Default: "".
See also ''includeFileInfos''.
* "excludeNames": Regex for item basenames not to allow. Default: "".
This matches against the names ''without'' any extension.
See also ''includeNames''.
* "excludePaths": Regex for paths not to allow. Default: "".
See also ''includePaths''.
* "hidden": Include hidden (.-initial) files '''and''' directories.
This option differs from most other file selection options, in that it
affects directories. This is to address things like excluding `.git` and the
many config directories commonly placed in home directories.
Default: False (that is, hidden items are ignored). Items under
ignored directories are '''entirely''' skipped -- their descendants are not
traversed, examined, or counted.
* "includeExtensions": Regex for (only) item extensions to allow. Default: "".
See also ''excludeExtensions''.
* "includeFileInfos": Regex to match what the *nix `file` command (q.v.) says
about the file. For example, some versions of `file` return descriptions like:
** POSIX shell script text executable, ASCII text
** directory
** MacOS Alias file
** ASCII text, with very long lines, with no line terminators
** XML 1.0 document text, ASCII text
** Python script text executable, UTF-8 Unicode text, with very long lines,
with CRLF, CR, LF line terminators, with escape sequences, with overstriking
** Debian binary package (format 2.0), with control.tar.gz, data compression xz
* "includeNames": Regex for (only) item basenames to allow. Default: "".
This matches against the names ''without'' any extension.
See also ''excludeNames''.
===Container and similar options===
* "followLinks": How to treat *nix symbolic
links: IGNORE, RETURN, or FOLLOW.
This does not include Mac "aliases", Windows "shortcuts", weblocs, etc.
* "followWeblocs": How to treat MacOS .webloc files (which basically just
encapsulate a URL): IGNORE, RETURN, or FOLLOW. For FOLLOW, the file will
be fetched, saved in the directory specified by the `--tempFileDir` option,
and returned as if it had been local.
* "openGzip": If True (the default), `gzip` files are opened as if they were
directories, and the individual items within them are returned.
* "openTar": If True (the default), `tar` files are opened as containers
(optionally generating PWType.OPEN and PWType.CLOSE events),
and the individual items within them are returned.
===Reading options===
* `close`: When the next item is requested, close the handle to the prior
one (only makes sense if `open` is also specified).
* `encoding`: Use this character encoding for input. Default: `utf-8`
* `mode`: What `mode` to pass to `codecs.open` (when the `open`
options is in effect. Default: `rb`.
* `open`: When a non-ignorable leaf is reached, open it and return the handle
as the second item in the returned tuple (which is otherwise None).
''Note'': For items that do not have a normal path, such as files embedded in
container such as tar or zip files, a handle to read them is always returned,
regardless of how the `open` option is set.
===Other options===
* `absolute`: Always map returned paths to absolute form.
* `containers` (default True): If True,
then open and close events are generated
for each container (such as a directory, gzip, or tar file) that is entered.
The third member of the returned tuple (`what`) is PWType.OPEN and
PWType.CLOSE, respectively.
* `dirsSeparate`: "dirs": sort directories before files;
"files": sort files before directories; "mix": leave them intermixed (default).
* `exceptions` (default False): If True, then containers (and ignorable
files (if `ignorables` is also set) are signaled by raising exceptions
rather than returning regular events. The exception types are
ItemOpening, ItemClosing, and ItemIgnorable.
* `ignorables` (default False): If True, then events are generated
even for items (containers and leaves) that are filtered out -- such as
hidden files or directories, etc. Such events will have `what`
returned as PWType.IGNORE.
* `maxDepth` (default 0 (unlimited)): Do not recurse deeper than this.
* `maxFiles` (default 0 (unlimited)): Stop after returning this many
files (events for ignorable
items do not count).
* `maxSize`
* `minDepth`
* `minSize`
* `notify`: Display a message as each new file starts, or is rejected. Default: False
* `recursive` (default False): Traverse through subdirectories?
* `reverseSort`: Sort in opposite order.
* `sampleFactor` (default: 100.0): Include only this % of the eligible files.
If set to a value above 0.0 and below 100.0, each leaf item that would have
been returned, has only this % change of actually being returned.
Others are reclassified as ignorable. The result will only
amount to approximately the requested percentage.
* `sort`: Sort the items in each directory in the specified way
(see also `--reverseSort` and `--dirsSeparate`).
Default: "none" (just use whatever `os.listdir` returns). Other choices:
** `name`: sort by filename
** `iname`: sort by filename, ignoring case.
** `atime`: file access time
** `ctime`: file creation time
** `mtime`: file modification time
** `size`: File length in bytes
** `ext`: Extension as returned by `os.path.splitext`
==traverse(self)==
Generate a sequence of chosen files (and if requested, pseudo-files,
such as items
from a zip, tar, or other container). Each iteration returns a tuple of
(path, fh), where `fh` is a readable. If the `open` option is in effect,
then regular files are opened by `codecs.open()`.
Otherwise fh is returned as None/
For items within tar, gzip, or other supported archive types, the readable
interface from the corresponding package is returned (regardless of whether
`open` is set).
Ignored items (such as backups if the `backups` option is not
set) are quietly skipped unless the `ignorables` options is set.
Containers such as directories and archive files generate start and end
events with the appropriate path, but the file handle is returned as None,
and the `what` is PWType.OPEN or PWType.CLOSE, respectively.
These events can be suppressed entirely by setting the `containers` option
to False.
=Known bugs and limitations=
* --excludeExtensions doesn't work.
* If you specify -r --type f, it fails to recurse.
* If you don't specify -r, it won't even list a directory that's specified
at the very top level. Currently, I've hacked it so that directories that
are specified directly, at the top level, are always recursed into
regardless of the setting of `--recursive`. I'm not certain what the ideal
behavior is:
** `ls` (unless you set `-d`) lists content for all directories specified directly.
** `ls -d -r` seems to not recurse at all.
** `ls *" lists all the files, ''then'' all the directories with their files.
* Default indented list unindents some files, and/or fails to display
directory events.
* `--exec` is still experimental, and related `find` options like `--execdir`
are not there at all.
* The script will warn if it can't find all the file-format libraries
installed (for tar, gzip, etc.),
but it will work fine as long as you don't specifically need the missing ones.
* For command-line use, there are options for whether/how to quote filenames.
But escaping the specified quote character(s) is rudimentary.
Specifically, it messes up multi-character quotation marks,
and it can only backslash.
* I've used this almost exclusively for reading (for example, picking
out just the desired files from an NLP corpus like OANC or MASC). Writing
is not yet thoroughly tested. I imagine writing doesn't work well for container
files (tar, gzip, etc.).
* Statistics of the current run as well as the current
nesting depth of the traversal (in `.depth`) are separated into a
`TraversalState` object. A reference to that object is
kept directly in the PowerWalk object instance as `PowerWalk.travState`.
So if you try to run two traversals from the same PowerWalk instance, you may
have problems accessing them via PowerWalk. However, PowerWalk
itself doesn't use it, so it should be ok. It's really only stored there
so command-line usage can display statistics at the end.
That won't work if you modify it to run a second
`PowerWalk.traverse()` before printing statistics that way. If you create two
separate PowerWalk instances in such cases, you should be fine.
* You can only specify one regex for each of the include/exclude options
that take regexes. These options do not apply to directories (ideally, they
should be separately settable for directories and files (and maybe other containers).
* The protection against circular links is unfinished.
=To do=
==Most wanted==
* Switch invokers to use parser.parse_known_args() instead of having to add
all these and copy them back.
* At top level, if it's a dir then issue an open event for it, and
make sure we get all it's children. *******
* Option to not report dirs (probably just apply `--type` f to main.
* Protect against circular links.
* Be able to accept/return Path objects.
* Add move/link/cat similar to `--copyTo`, and support setting
xattr to say where copied from.
* Support additional compression methods.
* Make a cleaner design for the various output format punctuation.
* Plain indented ls doesn't indent first dir name?
==Output options==
* Replace `--absolute` with a choice of normalized, real, rel, or abs?
* Enhance `--serialize` to support pulling in ancestor dir names,
like `renameFiles`. Perhaps, port and integrate `renameFiles`?
* Add `ls`-like and `stat`-like (cf PowerStat.py) displays?
Integrate PowerStat for output formatting.
* Displayed lines for open/close can't be entirely omitted via `--oformat`.
* Option to write directory outline in HTML.
* Rsync-like option: but just use system cp, and only if newer/differentSize....
* With --copy or --sync, construct isomorphic tree instead of copying all to
a single target (limit to one input dir?).
* way to colorize files by variuos criteria (say, by using the `file` command
to differentiate Perl vs. Python)
* Change --count to be like grep --count.
* Add -f to do ls -f effect.
==Filter / file selection options==
* Possibly, way to exclude a dir but then override to include certain subs?
* Consolidate filter options to be more like rsync?
--filter [rel][what] /pattern/
rel ::= include|exclude|+|-|<=>|
what ::= name|path|ext|info|
| cre|mod|acc|inodeCre
* Add option to return *only* dirs (or containers?)
* Option to block traversal into .apps, .dmg, etc.
* Option to specify a file like .gitignore or .dockerignore, specifying
file patterns to exclude (or maybe to specify options in general)?
* Perhaps add --name, --iname, --path, --ipath that match globs instead of
regexes, for `find` compatibility?
See discussion of Python `fnmatch` in
[https://stackoverflow.com/questions/27726545/], or pathlib, or PurePAth.match().
* Add `--files-without-match` and `--files-with-matches` like `grep`.
* permissions -- see `passesPerm()` below.
* owner and group ids (and none), inum -- cf `PowerStat.py`
* file-flags like for `find -flags`, `chflags`, 'ls -F'; or circled chars?
* Mac fs metadata (kmdItem... and all that). See my `macFinderInfo`.
* Option to not cross device or filesystem bounds (see `find -x`)
* distinguish maxfiles tried vs. succeeded
* Dates and times (options have been added, but don't do anything yet)
-amin n: modified n minutes ago (rounded up)
-atime n[smhdw] modified n (default days) ago. Can do `-1h30m`.
-anewer
(likewise with -c... for ctime, -m... for mtime, -B... inode creation)
-newer [file]: if newer mod than [file
-newerXY [file]]: if newer [aBcm] than [file]'s [aBcM].
* depth
* Ones that require a comparison type:
** atime, ctime, mtime, mindepth, cf Bmin [aBcm]?(newer|time|min)
** depth
** newer/old cre/mod/acc time vs. specified file
** date, age, and file size (chars, bytes, blocks, kmgtp), file count.
*** including MIME "Date:" for email files
* Is under git or other version-control (and maybe, is committed/pushed?)
See getGitStatus(). Not yet integrated.
* Add specific support for .gitignore and cvs equivalent.
What do various *nix utilities do for <=> tests in options?
* empty
* exec(dir)
* group/nogroup, user/nouser/uname/uid/
* -print0
* "i" prefix for specific tests
* -xattr, -xattrname (and xattr k op v)
* negation and maybe booleans?
* --files-with-match, --files-without-match (repeatable?)
* Review `rsync` for useful selection options (say, git-exclude, cvs-exclude?)
==Other options==
* Make --include* --exclude* repeatable. Should they mean union or intersection?
* Option to sniff encoding rather than set globally?
* Limit max/min/total size of files
* Support Mac aliases, bookmarks, and webloc files.
See my `resolveLinks` attempt, and [https://pypi.org/project/mac_alias/].
See [https://stackoverflow.com/questions/48862093]
(how-to-read-change-and-write-macos-file-alias-from-python),
[http://mac-alias.readthedocs.io/en/latest] and
[https://docs.python.org/2/library/macostools.html].
* Support URLs?
* Sampling of every nth file, first n from each directory, etc.
==Interface==
* Make a way for the caller to find out what kind of container they're in.
Maybe just pass back the container handle? Or they can poke at the path.
* Synchronize with `find` option and/or names where appropriate:
** -L for --followlinks (`find` used to use -follow)
** -s for `-sort name`
** -d (depth-first)? -depth nq
** -x (don't cross device boundaries) = -mount = -xdev
** -acl?
** -wholename for -path
* Offer warning if no eligible files found in a dir? (cf `find -empty`).
* Possibly a stat-like "%" option for output? See `FileInfo` class.
=Related commands=
`find` + `-exec` does a really nice job of finding things.
PowerWalk is mainly intended to be easier to use
from Python code, especially for people (like corpus linguists) who work with
tons of sample files in complicated directory and container structures.
[https://github.com/sderose/FileManagement/lss],
[https://github.com/sderose/FileManagement/findIdenticalFiles].
[https://github.com/sderose/FileManagement/lsoutline] produces a file listing
similar to what PowerWalk produces
when run from the command line. But you can do fancier selection here (that
script may be upgraded to just use PowerWalk underneath).
=References=
See [../FileSelectionOptionsOfNixCommands.md] for a survey of what different
*nix command provide for file-selection, sorting, format support, etc.
=History=
* 2006-06-07: `countTags.py` written by Steven J. DeRose, with some similar options.
* 2018-04-21: `PowerWalk.py` split out of `countTags.py`.
* 2020-06-10: New layout. Static methods.
* 2020-08-28ff: Add exception-based directory/error event handling. Lint.
* 2020-09-01: Add `namedtuple` PWFrame as what to return. Add Enum
`PWType` for what kind of thing is being returned. Reorganize options
into categories in help and where listed in code. Add `--exceptions`
and several new filtering options, type-check them.
Refactor event generation, item stack, and statistics into TraversalState class.
* 2020-09-15: Fix several bugs in filtering, improve reporting and
option-setting. Add `--includeFileInfos` and `--excludeFileInfos`.
* 2020-10-06: Fix `--includeNames`, make it and `--excludeName` use extension.
Add `--copyTo` and `--serialize`.
* 2020-10-09: Add `--exex`.
* 2020-10-14: Improve how topLevelItems are passed and defaulted.
Clean up `errorEvents` options vs. `errors` statistic.
* 2020-10-20f: Add `--type` similar to *nix `find`. Fix depth counting.
* 2020-11-24: Add `--no-recursive`. Make exceptions subclass of a cover type.
Add `--reverseSort` and clean up sorting. Make top-level dirs always recurse.
* 2021-01-11: Fix quote escaping bug.
* 2021-03-09: Add `--serializeFormat`, and file-time options (latter are not
operational yet).
* 2021-04-09: Sync competing changes. Add `--dirsSeparate`.
* 2021-04-19: Hook up `--perm` to start testing.
Filter by git status. More option re. symlinks, start Mac .webloc support.
Improve doc, typehints, etc. Track inodes of directories to try to protect
against circular symlinks.
* 2022-02-14: Normalize quotes. Add --fileType.
* 2022-03-23: Improve output format quoting options.
* 2022-07-05: Start breaking out a cleaner listing i/f via classes ItemFmt, Lister...
* 2023-11-27: Refactor main, OutputFormatter. Drop ItemFmt.
Rename --filetype to --fileTypeFlag and alias -F. Add alias -R for recursive.
* 2023-12-01: Let --type and --gitStatus take multiple letters.
=Rights=
Copyright 2006, 2018 by Steven J. DeRose.
This work is licensed under a Creative Commons
Attribution-Share Alike 3.0 Unported License. For further information on
this license, see [http://creativecommons.org/licenses/by-sa/3.0].
For the most recent version, see [http://www.derose.net/steve/utilities] or
[https://github.com/sderose].
=Options=
"""
###############################################################################
# A bunch of classes for readable stuff. There has to be an easier way....
# This list may need to be extended.
# See https://docs.python.org/3/library/io.html
#
def isStreamable(x) -> bool:
return isinstance(x, (
io.TextIOWrapper, # subclass of IOBase
io.BufferedReader, # subclass of IOBase
io.BufferedWriter, # subclass of IOBase
codecs.StreamReaderWriter, # KNOPE
tarfile.TarFile, # KNOPE
gzip.GzipFile, # subclass of IOBase
io.StringIO, # subclass of IOBase
#
# UUencode
# bz2
# zlib # like gzip
# zipfile
#
# DMG (.dmg, .mg, .smi
# UDIF,
# NDIF,
# SPARSE,
# IMG (raw disk image, need file system on top)
# HTML with links, for scraping?
)
)
###############################################################################
# The "exceptions" option signals directory start/end by raising exceptions.
# Seems to me cleaner than passing a "magic" event type back.
#
# There is no exception corresponding to sucessfully returning a
# readable/writable leaf item, because that's the unexceptional case.
#
class ItemException(Exception):
pass
class ItemOpening(ItemException):
pass
class ItemClosing(ItemException):
pass
class ItemIgnorable(ItemException):
pass
class ItemError(ItemException):
pass
class ItemMissing(ItemError):
pass
class Finished(ItemException):
pass
###############################################################################
#
class PWType(Enum):
"""These are the types of events that are stored as the third item in
PWFrame objects (see next section), which are kept on the TraversalState
stack during active traversals.
"""
OPEN = 1 # The beginning of a directory, tar file, etc.
CLOSE = 2 # The end of a directory, tar file, etc.
IGNORE = 3 # Notification of a filtered-out object
LEAF = 4 # An actual readable/writable object
ERROR = -1 # Generic error
MISSING = -2 # Specific error, item not found
class PWDisp(Enum):
"""Choices of what to do with links, such as *ix symlinks, Mac aliases,
Mac .weblocs, etc.
"""
IGNORE = 0
RETURN = 1
FOLLOW = 2
###############################################################################
# PWFrame bundles the stuff you need to know in each entry on the "travState"
# stack, which tracks the state of the traversal.
#
# .path is the absolute path to the file. file-like items within containers
# like tar files do not have their own paths, so this may be None or
# the container path plus an artificial suffix.
# .fh is any streamable such as a file handle. This is None unless:
# a: the item is inside a container, so has no actual "path", or
# b: the "open" option has been set.
# .container is PWType, which tells whether this is a container opening or
# closing, an ignored file event (if requested), an error, or a legit file.
# .inode is the inode number. This is kept because symblinks can make
# circles. Yes, it happened to me. Thanks, Valve.
#
PWFrame = namedtuple("PWFrame", [ "path", "fh", "what", "inode" ])
def isPWFrameOK(ts:PWFrame) -> bool:
if (not isinstance(ts.path, str)):
warning(0, "Bad PWFrame.path: %s." % (type(ts.path)))
return False
if (ts.fh is not None and not isStreamable(ts.fh)):
warning(0, "Bad PWFrame.fh: %s." % (ts.fh or "[None]"))
return False
if (not isinstance(ts.what, PWType)):
warning(0, "Bad PWFrame.what: %s." % (ts.what))
return False
if (not isinstance(ts.inode, int)):
warning(0, "Bad PWFrame.inode: %s." % (ts.inode))
return False
return True