entria / entria-graphql

GraphQL Generators for Entria Projects
MIT License
19 stars 1 forks source link

improve type/connection/loader dependencies path resolution #10

Closed sibelius closed 6 years ago

sibelius commented 6 years ago
#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const Readable = require('readable-stream').Readable;

function complements(arr, predicate) {
    const out = [[],[]];
    arr.forEach(e => out[Number(!!predicate(e))].push(e));
    return out;
}

function isDirectory(path) {
    return fs.lstatSync(path).isDirectory();
}

function getFiles(root, stream) {

    if (!(stream instanceof Readable)) {
        stream = Readable({objectMode: true});
        stream._read = () => {}; 
    }

    fs.readdir(root, (err, paths) => {
        if (err) throw err;

        paths = paths.map(i => path.join(root, i));
        const [ files, dirs ] = complements(paths, isDirectory);

        files.forEach(f => stream.push(f));
        dirs.forEach(d => getFiles(d, stream));

    });

    return stream;
}

function grep(file, pattern, onMatch) {
    if(file.match(pattern)){
        onMatch(file);
    }
}

getFiles(process.cwd()).on('data', file => {
    grep(file, /package.json$/, fileMatch => {
        console.log(fileMatch); 
    })
});