2525import path from 'path' ;
2626import fs from 'fs' ;
2727import _ from 'lodash' ;
28- import glob from 'glob ' ;
28+ import { fdir } from 'fdir ' ;
2929
30+ const pathsMatch = ( target ) => {
31+ const targetLower = target . toLowerCase ( ) ;
32+
33+ return ( p ) => {
34+ const pLower = p . toLowerCase ( ) ;
35+ return pLower === targetLower ||
36+ pLower . slice ( 0 , pLower . lastIndexOf ( '.' ) ) === targetLower ;
37+ } ;
38+ } ;
3039/**
3140 * Find file and returns its content if file exists.
3241 *
@@ -37,49 +46,27 @@ import glob from 'glob';
3746 */
3847export function readFile ( dir , cwd , names ) {
3948 const inputs = _ . castArray ( names ) ;
49+ // eslint-disable-next-line new-cap
50+ const finder = new fdir ( ) ;
4051
4152 for ( let i = 0 ; i < inputs . length ; ++ i ) {
42- const input = generatePattern ( inputs [ i ] ) ;
53+ const input = inputs [ i ] ;
4354 const absolutePath = path . join ( dir , input ) ;
4455 const relativeToCwd = path . relative ( cwd , absolutePath ) ;
4556
46- const findings = glob . sync ( relativeToCwd , { cwd } ) ;
47- for ( let j = 0 ; j < findings . length ; ++ j ) {
48- const file = path . join ( cwd , findings [ j ] ) ;
49- if ( isFile ( file ) ) {
50- return fs . readFileSync ( file , 'utf-8' ) ;
51- }
52- }
53- }
54-
55- return null ;
56- }
57-
58- /**
59- * Check that given file exists, and is a real file.
60- *
61- * @param {string } file File path.
62- * @returns {boolean } `true` if `file` is a file, `false` otherwise.
63- */
64- function isFile ( file ) {
65- return ! ! fs . existsSync ( file ) && ! ! fs . lstatSync ( file ) . isFile ( ) ;
66- }
57+ const findings = finder
58+ . withRelativePaths ( )
59+ . filter ( pathsMatch ( relativeToCwd ) )
60+ . crawl ( cwd )
61+ . sync ( ) ;
6762
68- /**
69- * Generate glob pattern for given input.
70- *
71- * @param {string } input Given input.
72- * @returns {string } Glob pattern.
73- */
74- function generatePattern ( input ) {
75- let pattern = '' ;
63+ const firstPath = findings [ 0 ] ;
7664
77- for ( let i = 0 ; i < input . length ; ++ i ) {
78- const c = input [ i ] ;
79- const up = c . toUpperCase ( ) ;
80- const low = c . toLowerCase ( ) ;
81- pattern += up !== low ? `[${ low } ${ up } ]` : low ;
65+ if ( firstPath ) {
66+ const file = path . join ( cwd , firstPath ) ;
67+ return fs . readFileSync ( file , 'utf-8' ) ;
68+ }
8269 }
8370
84- return ` ${ pattern } *` ;
71+ return null ;
8572}
0 commit comments