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.

  1. Nullable!Path searchFileUp(string file_name)
    struct Path
    version(Posix)
    @safe const
    Nullable!Path
    searchFileUp
    (
    in string file_name
    )
  2. Nullable!Path searchFileUp(Path search_path)

Parameters

file_name string

Name of file to search

Return Value

Type: Nullable!Path

Path to searched file, if such file was found. Otherwise return null Path.

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
auto p1 = Path.current.searchFileUp("my-conf.conf");
p1.isNull.should.be(false);
p1.get.toString.should.equal(
    root.join("dir1", "my-conf.conf").toAbsolute.toString);

// Try to get config, related to "dir8"
auto p2 = root.join("dir1", "dir4", "dir8").searchFileUp(
    "my-conf.conf");
p2.isNull.should.be(false);
p2.get.should.equal(
        root.join("dir1", "dir4", "my-conf.conf"));

// Test searching for some path (instead of simple file/string)
auto p3 = root.join("dir1", "dir2", "dir3").searchFileUp(
    Path("dir4", "my-conf.conf"));
p3.isNull.should.be(false);
p3.get.should.equal(
        root.join("dir1", "dir4", "my-conf.conf"));

// One more test
auto p4 = root.join("dir1", "dir2", "dir3").searchFileUp(
    "my-conf.conf");
p4.isNull.should.be(false);
p4.get.should.equal(root.join("dir1", "my-conf.conf"));

// Try to find up some unexisting file
auto p5 = root.join("dir1", "dir2", "dir3").searchFileUp(
    "i-am-not-exist.conf");
p5.isNull.should.be(true);

import core.exception: AssertError;
p5.get.should.throwA!AssertError;

Meta