add my deepestdir script
- ID
62bfda2- date
2023-06-25 08:04:50+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
f436660- message
add my deepestdir script- changed files
2 files, 46 additions
Changed files
fs/README.md (1713) → fs/README.md (1942)
diff --git a/fs/README.md b/fs/README.md
index 502921d..2f93e88 100644
--- a/fs/README.md
+++ b/fs/README.md
@@ -23,6 +23,15 @@ These are scripts for manipulating files and folders in my local filesystem.
</dd>
<dt>
+ <a href="https://github.com/alexwlchan/scripts/blob/main/fs/deepestdir">
+ <code>deepestdir [ROOT]</code>
+ </a>
+ </dt>
+ <dd>
+ prints the directory which is the deepest child of the given directory
+ </dd>
+
+ <dt>
<a href="https://github.com/alexwlchan/scripts/blob/main/fs/emptydir">
<code>emptydir</code>
</a>
fs/deepestdir (0) → fs/deepestdir (894)
diff --git a/fs/deepestdir b/fs/deepestdir
new file mode 100755
index 0000000..9301233
--- /dev/null
+++ b/fs/deepestdir
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""
+Usage: deepestdir [<ROOT>]
+
+Prints the path to the deepest directory under the given root. If no root
+is given, the current directory is used. If there are multiple directories
+at the same depth, only one is printed.
+"""
+
+import functools
+import os
+import sys
+
+
+def get_dir_paths_under(root):
+ """Generates the paths to every directory under ``root``."""
+ for dirpath, dirnames, _ in os.walk(root):
+ for d in dirnames:
+ yield os.path.join(dirpath, d)
+
+
+@functools.cache
+def directory_depth(d):
+ """Returns the depth of a directory in the filesystem."""
+ if os.path.dirname(d) == d:
+ return 0
+ else:
+ return 1 + directory_depth(os.path.dirname(d))
+
+
+if __name__ == "__main__":
+ try:
+ root = sys.argv[1]
+ except IndexError:
+ root = "."
+
+ print(max(get_dir_paths_under(root), key=directory_depth))