Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Walk up the directory tree

Tags:

elisp

The file tree is as follwing:

- foo
  - lorem
    - ipsum <-
  - baz <-
- bar
- baz

The currently visited file is ipsum. Now I want to find the first baz and the directory it is in. How do I walk up the tree from ipsum in elisp?

like image 257
Reactormonk Avatar asked Dec 30 '12 22:12

Reactormonk


People also ask

What is a directory walk?

walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). root : Prints out directories only from what you specified.

How do I walk a directory in Python?

To traverse the directory in Python, use the os. walk() function. The os. walk() function accepts four arguments and returns 3-tuple, including dirpath, dirnames, and filenames.

What is topdown in os walk?

topdown − If optional argument topdown is True or not specified, directories are scanned from top-down. If topdown is set to False, directories are scanned from bottom-up. onerror − This can show error to continue with the walk, or raise the exception to abort the walk.

What is the folder tree called?

A directory structure/system/tree is simply a layout of directories on your computer.


Video Answer


2 Answers

You want locate-dominating-file.

like image 139
Stefan Avatar answered Oct 07 '22 17:10

Stefan


(defun parent-directory (dir)
  (unless (equal "/" dir)
    (file-name-directory (directory-file-name dir))))

(defun find-file-in-heirarchy (current-dir fname)
  "Search for a file named FNAME upwards through the directory hierarchy, starting from CURRENT-DIR" 
  (let ((file (concat current-dir fname))
        (parent (parent-directory (expand-file-name current-dir))))
    (if (file-exists-p file)
        file
      (when parent
        (find-file-in-heirarchy parent fname)))))

If the result is not nil, you can extract the file's directory using file-name-directory, like so:

(let ((file (find-file-in-heirarchy (buffer-file-name) "baz")))
  (when file
    (file-name-directory file)))
like image 31
Chris Barrett Avatar answered Oct 07 '22 16:10

Chris Barrett