All files / owid-grapher/settings findBaseDir.ts

90.32% Statements 28/31
66.67% Branches 4/6
100% Functions 1/1
90.32% Lines 28/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 261x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 2x 2x 2x       1x
import path from "path"
import fs from "fs"
 
/**
 * With our code residing either in some src folder or in the `itsJustJavascript` folder, it's not
 * always straightforward to know where to find a config file like `.env`.
 * Here, we just traverse the directory tree upwards until we find a `package.json` file, which
 * should indicate that we have found the root directory of the `owid-grapher` repo.
 */
export default function findProjectBaseDir(from: string): string | undefined {
    if (!fs.existsSync) return undefined // if fs.existsSync doesn't exist, we're probably running in the browser
 
    let dir = path.dirname(from)
 
    while (dir.length) {
        if (fs.existsSync(path.resolve(dir, "package.json"))) return dir
 
        const parentDir = path.resolve(dir, "..")
        // break if we have reached the file system root
        if (parentDir === dir) break
        else dir = parentDir
    }

    return undefined
}