{"size": 1965, "ext": "js", "max_stars_repo_path": "snippet-finder.js", "max_stars_repo_name": "morhook/ember-code-snippet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "snippet-finder.js", "max_issues_repo_name": "morhook/ember-code-snippet", "max_issues_repo_issues_event_min_datetime": "2017-12-11T16:17:06.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-11T16:17:06.000Z", "max_forks_repo_path": "snippet-finder.js", "max_forks_repo_name": "morhook/ember-code-snippet", "max_forks_repo_forks_event_min_datetime": "2017-12-14T19:36:58.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-14T19:36:58.000Z"}
{"max_stars_count": null, "max_issues_count": 1, "max_forks_count": 1, "avg_line_length": 24.8734177215, "max_line_length": 110, "alphanum_fraction": 0.6320610687}
/* jshint node: true */

var Writer = require('broccoli-writer');
var glob = require('glob');
var _Promise = require('es6-promise').Promise;
var fs = require('fs');
var path = require('path');


function findFiles(srcDir) {
  return new _Promise(function(resolve, reject) {
    glob(path.join(srcDir, "**/*.+(js|coffee|html|hbs|md|css|sass|scss|less|emblem)"), function (err, files) {
      if (err) {
        reject(err);
      } else {
        resolve(files);
      }
    });
  });
}

function extractSnippets(fileContent, regexes) {
  var stack = [];
  var output = {};
  fileContent.split("\n").forEach(function(line){
    var top = stack[stack.length - 1];
    if (top && top.regex.end.test(line)) {
      output[top.name] = top.content.join("\n");
      stack.pop();
    }

    stack.forEach(function(snippet) {
      snippet.content.push(line);
    });

    var match;
    var regex = regexes.find(function(regex) {
      return match = regex.begin.exec(line);
    });

    if (match) {
      stack.push({
        regex: regex,
        name: match[1],
        content: []
      });
    }
  });
  return output;
}


function SnippetFinder(inputTree, snippetRegexes) {
  if (!(this instanceof SnippetFinder)) {
    return new SnippetFinder(inputTree, snippetRegexes);
  }
  this.inputTree = inputTree;
  this.snippetRegexes = snippetRegexes;
}

SnippetFinder.prototype = Object.create(Writer.prototype);
SnippetFinder.prototype.constructor = SnippetFinder;

SnippetFinder.prototype.write = function (readTree, destDir) {
  var regexes = this.snippetRegexes;

  return readTree(this.inputTree).then(findFiles).then(function(files){
    files.forEach(function(filename){
      var snippets = extractSnippets(fs.readFileSync(filename, 'utf-8'), regexes);
      for (var name in snippets){
        fs.writeFileSync(path.join(destDir, name)+path.extname(filename),
                         snippets[name]);
      }
    });
  });
};

module.exports = SnippetFinder;
