ELisp: Walk Directory by Depth 🚀

By Xah Lee. Date: .
(defun xah-count-char (Str Char)
  "Count the number of Char in Str.

Useful for finding the level of a nested dir by counting slash.
Note: you should call `expand-file-name'
 on Path first to canonize path
and
`file-name-as-directory'
to make sure dir name always ends in slash.

Version: 2023-09-14"
  (seq-count (lambda (x) (char-equal x Char)) Str))

(defun xah-walk-dir-depth (DirRoot
                     LevelMin
                     LevelMax
                     Regex &optional
                     IncludeDirs
                     Predicate
                     FollowSymlinks
                     )
  "Return a list of file (or dir) full paths with depth LevelMin to LevelMax.

DirRoot → a directory path.
LevelMin → minimal level. Inclusive. Level 0 is all files in DirRoot.
LevelMax → max level. Inclusive.
Regex → regex to filter file names. (matched against file name, not full path.)
IncludeDirs → include dir in result.
Predicate → same as in `file-name-as-directory'
FollowSymlinks → follow symbolic links.

URL `http://xahlee.info/emacs/emacs/elisp_walk_dir_depth.html'
Version: 2023-09-14"
  (interactive)
  (let ((xroot (file-name-as-directory (expand-file-name DirRoot)))
        xrootDepth xallPaths)
    (setq xrootDepth (xah-count-char xroot ?/)
          xallPaths (directory-files-recursively xroot Regex IncludeDirs Predicate FollowSymlinks))
    (seq-filter
     (lambda (x)
       (let ((xdiff (- (xah-count-char x ?/) xrootDepth)))
         (and (>= xdiff LevelMin) (<= xdiff LevelMax))))
     xallPaths)))