Path.searchFileUp

Search file by name in current directory and parent directories. * Usually, this could be used to find project config, * when current directory is somewhere inside project. * * If no file with specified name found, then return null path. * * Params: * file_name = Name of file to search * Returns: * Path to searched file, if such file was found. * Otherwise return null Path.

  1. Path searchFileUp(string file_name)
  2. Path searchFileUp(Path search_path)
    struct Path
    version(Posix)
    const
    searchFileUp

Examples

Example of searching configuration file, when you are somewhere inside project.

import dshould;
Path root = createTempPath();
scope(exit) root.remove();

// Save current directory
auto cdir = std.file.getcwd;
scope(exit) std.file.chdir(cdir);

// Create directory structure
root.join("dir1", "dir2", "dir3").mkdir(true);
root.join("dir1", "my-conf.conf").writeFile("hello!");
root.join("dir1", "dir4", "dir8").mkdir(true);
root.join("dir1", "dir4", "my-conf.conf").writeFile("Hi!");
root.join("dir1", "dir5", "dir6", "dir7").mkdir(true);

// Change current working directory to dir7
root.join("dir1", "dir5", "dir6", "dir7").chdir;

// Find config file. It sould be dir1/my-conf.conf
Path.current.searchFileUp("my-conf.conf").toString.should.equal(
    root.join("dir1", "my-conf.conf").toAbsolute.toString);

// Try to get config, related to "dir8"
root.join("dir1", "dir4", "dir8").searchFileUp(
    "my-conf.conf").should.equal(
        root.join("dir1", "dir4", "my-conf.conf"));

// One more test
root.join("dir1", "dir2", "dir3").searchFileUp(
    Path("dir4", "my-conf.conf")).should.equal(
        root.join("dir1", "dir4", "my-conf.conf"));
root.join("dir1", "dir2", "dir3").searchFileUp(
    "my-conf.conf").should.equal(root.join("dir1", "my-conf.conf"));

Meta