-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.js
60 lines (47 loc) · 1.45 KB
/
file.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* External dependencies
*/
const { existsSync, readdirSync, statSync } = require( 'fs' );
const path = require( 'path' );
/**
* Internal dependencies
*/
const { getPackagePath } = require( './package' );
const fromProjectRoot = ( fileName ) =>
path.join( path.dirname( getPackagePath() ), fileName );
const hasProjectFile = ( fileName ) =>
existsSync( fromProjectRoot( fileName ) );
const fromConfigRoot = ( fileName ) =>
path.join( path.dirname( __dirname ), 'config', fileName );
const fromScriptsRoot = ( scriptName ) =>
path.join( path.dirname( __dirname ), 'scripts', `${ scriptName }.js` );
const hasScriptFile = ( scriptName ) =>
existsSync( fromScriptsRoot( scriptName ) );
const getScripts = () =>
readdirSync( path.join( path.dirname( __dirname ), 'scripts' ) )
.filter( ( f ) => path.extname( f ) === '.js' )
.map( ( f ) => path.basename( f, '.js' ) );
const mapAsync = async function( data, cb ) {
for( let i in data ) {
data[i] = await cb( data[i], i, data );
}
return data;
}
const walkDirectory = async (dir, cb) => {
cb = cb || ( (f) => f );
let data = readdirSync(dir)
.map( ( f ) => path.join( dir, f ) );
data = await mapAsync( data, async ( f ) => statSync( f ).isDirectory() ? await walkDirectory( f ) : f );
data = data.flat();
data = await mapAsync( data, cb );
return data;
}
module.exports = {
fromProjectRoot,
fromConfigRoot,
fromScriptsRoot,
getScripts,
hasProjectFile,
hasScriptFile,
walkDirectory,
};