UNPKG

1.5 kBJavaScriptView Raw
1'use strict';
2
3const fs = require('fs');
4const nodePathModule = require('path');
5
6function getStatForPath(path, indiscriminateOfSymlinks) {
7 /* istanbul ignore next: No symlinks in this package, so we won't test this for now */
8 const statMethodName = indiscriminateOfSymlinks ? 'statSync' : 'lstatSync';
9 const stat = Object.assign(fs[statMethodName](path), { path: path });
10
11 return {
12 path: stat.path,
13 symlink: stat.isSymbolicLink()
14 ? nodePathModule.resolve(nodePathModule.dirname(stat.path), fs.readlinkSync(stat.path))
15 : false,
16 file: stat.isFile(),
17 directory: stat.isDirectory(),
18 size: stat.size,
19 accessed: stat.atime,
20 modified: stat.mtime,
21 changed: stat.ctime,
22 created: stat.birthtime
23 };
24}
25
26function getAllStatsInPath(dir, indiscriminateOfSymlinks) {
27 return fs
28 .readdirSync(dir)
29 .map(file => nodePathModule.resolve(dir, file))
30 .map(path => {
31 try {
32 return getStatForPath(path, indiscriminateOfSymlinks);
33 } catch (_error) {
34 // Do nothing
35 }
36 })
37 .filter(result => !!result);
38}
39
40module.exports = function getParentDirectoryContainingFileSync(cwd, configFileName) {
41 const rootDir = nodePathModule.parse(cwd).root;
42 const pathHasConfigFile = getAllStatsInPath(cwd, false).some(
43 stat => stat.file && nodePathModule.basename(stat.path) === configFileName
44 );
45
46 // @TODO: This needs more testing
47 return pathHasConfigFile
48 ? cwd
49 : cwd === rootDir
50 ? null
51 : getParentDirectoryContainingFileSync(nodePathModule.dirname(cwd), configFileName);
52};