From 8bf83c198d9863ae309a429ef40d42b8d19f06bb Mon Sep 17 00:00:00 2001 From: Martin Sekera Date: Wed, 3 Aug 2022 21:48:24 +0200 Subject: [PATCH] new command: leaf-dirs --- bin/leaf-dirs | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100755 bin/leaf-dirs diff --git a/bin/leaf-dirs b/bin/leaf-dirs new file mode 100755 index 0000000..90332f0 --- /dev/null +++ b/bin/leaf-dirs @@ -0,0 +1,41 @@ +#! /usr/bin/env python3 +# encoding: utf-8 + +import argparse +import os +import pathlib +import random +import shlex + +def list_leaf_dirs(root, follow): + for path, subdirs, _ in os.walk(root, followlinks=follow): + if not subdirs: + yield path + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Lists all leaf subdirectories (those not containing any more subdirectories) below PATH.") + parser.add_argument(dest="PATH", type=pathlib.Path, nargs="*", default=[pathlib.Path()], help="paths to list leaf subdirs of") + parser.add_argument("-q", "--quote", dest="quote", action="store_const", const=True, default=False, help="quote lines of output (for easier shell processing)") + parser.add_argument("-f", "--follow", dest="follow", action="store_const", const=True, default=False, help="follow symlinks") + parser.add_argument("-n", "--null", dest="null", action="store_const", const=True, default=False, help="use null separators instead of newlines") + parser.add_argument("-s", "--shuffle", dest="shuffle", action="store_const", const=True, default=False, help="randomize directory order") + args = parser.parse_args() + + dirs = [] + + for d in args.PATH: + dirs.extend(list_leaf_dirs(d, args.follow)) + + outdirs = [] + + if args.quote: + for d in dirs: + outdirs.append(shlex.quote(d)) + else: + outdirs = dirs + + if args.shuffle: + random.shuffle(outdirs) + + sep = "\0" if args.null else "\n" + print(sep.join(outdirs))