{"size": 1529, "ext": "js", "max_stars_repo_path": "lib/index.js", "max_stars_repo_name": "aichbauer/node-template-dir", "max_stars_repo_stars_event_min_datetime": "2017-09-15T12:24:09.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-20T08:30:04.000Z", "max_issues_repo_path": "lib/index.js", "max_issues_repo_name": "aichbauer/node-template-dir", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/index.js", "max_forks_repo_name": "aichbauer/node-template-dir", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.58, "max_line_length": 120, "alphanum_fraction": 0.6533682145}
import fs from 'fs';
import path from 'path';
import pathIsAbsolute from 'path-is-absolute';

import { renderString } from 'template-file';

const templateDir = ({ source = '', destination = 'destination', onlyFiles = false, exclude = [] } = {}, data = {}) => {
  const cwd = process.cwd();

  const thisSource = pathIsAbsolute(source) ? source : path.join(cwd, source);
  const thisDestination = pathIsAbsolute(destination) ? destination : path.join(cwd, destination);
  const thisOnlyFiles = onlyFiles;
  const thisExclude = exclude;


  try {
    const listOfFiles = fs.readdirSync(thisSource);
    const destinationExists = fs.existsSync(thisDestination);

    if (!destinationExists) {
      fs.mkdirSync(thisDestination);
    }

    listOfFiles.forEach((file) => {
      const thisFile = path.join(thisSource, file);
      const stat = fs.statSync(thisFile);

      if (stat && stat.isDirectory() && !thisOnlyFiles && !thisExclude.includes(file)) {
        const nextDestination = path.join(thisDestination, file);

        templateDir({
          source: thisFile,
          destination: nextDestination,
          onlyFiles: thisOnlyFiles,
          exclude: thisExclude,
        }, data);
      } else if (!stat.isDirectory()) {
        const template = fs.readFileSync(thisFile, 'utf-8');
        const filledTemplate = renderString(template, data);

        fs.writeFileSync(path.join(thisDestination, file), filledTemplate);
      }
    });
  } catch (e) {
    throw new Error(e);
  }
};

export default templateDir;
