Here's a different way of doing this.
I define a function that produces the list of all the directories in the
current directory hierarchy.
(defun file-name-directory-nesting-helper (name previous-name accumulator)
(if (string= name previous-name)
accumulator ; stop when names stop changing (at the top)
(directory-file-name (file-name-directory name))
(cons name accumulator))))
(defun file-name-directory-nesting (name)
(file-name-directory-nesting-helper (expand-file-name name) "" ()))
An example is in order:
;; => ("/" "/foo" "/foo/bar" "/foo/bar/baz" "/foo/bar/baz/quux" "/foo/bar/baz/quux/foo.el")
Now I can add advice to
hack-dir-local-variables to make it
"pretend" that we're visiting a file at the very top of the tree,
apply directory-local settings, then step one level down, apply
settings again, and so on.
(defun hack-dir-local-variables-chained-advice (orig)
"Apply dir-local settings from the whole directory hierarchy,
from the top down."
(let ((original-buffer-file-name (buffer-file-name))
(nesting (file-name-directory-nesting (or (buffer-file-name)
(dolist (name nesting)
;; make it look like we're in a directory higher up in the
;; hierarchy; note that the file we're "visiting" does not
;; have to exist
(setq buffer-file-name (expand-file-name "ignored" name))
(setq buffer-file-name original-buffer-file-name))))
(advice-add 'hack-dir-local-variables :around