{"size": 2055, "ext": "js", "max_stars_repo_path": "index.js", "max_stars_repo_name": "widdix/aws-cf-chcker", "max_stars_repo_stars_event_min_datetime": "2015-10-28T07:39:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T04:18:04.000Z", "max_issues_repo_path": "index.js", "max_issues_repo_name": "widdix/aws-cf-chcker", "max_issues_repo_issues_event_min_datetime": "2016-04-08T14:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-14T06:13:05.000Z", "max_forks_repo_path": "index.js", "max_forks_repo_name": "widdix/aws-cf-chcker", "max_forks_repo_forks_event_min_datetime": "2016-07-04T15:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T08:07:06.000Z"}
{"max_stars_count": 46, "max_issues_count": 5, "max_forks_count": 9, "avg_line_length": 23.0898876404, "max_line_length": 76, "alphanum_fraction": 0.598053528}
"use strict";

var fs = require("fs");
var _ = require("lodash");
var async = require("neo-async");

function loadJSONFile(filename, cb) {
  fs.readFile(filename, {"encoding": "utf8"}, cb);
}

function parseJSON(json, cb) {
  cb(null, JSON.parse(json));
}

function clone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

function mapTemplate(template, cb) {
  var objects = [];
  function mapper(part) {
    return function(object, logicalId) {
      var res = clone(object);
      res.LogicalId = logicalId;
      res.Part = part;
      return res;
    };
  }
  objects = objects.concat(_.map(template.Parameters, mapper("Parameter")));
  objects = objects.concat(_.map(template.Mappings, mapper("Mapping")));
  objects = objects.concat(_.map(template.Conditions, mapper("Condition")));
  objects = objects.concat(_.map(template.Resources, mapper("Resource")));
  objects = objects.concat(_.map(template.Outputs, mapper("Output")));
  cb(null, objects);
}

function runChecks(objects, checks, cb) {
  async.map(Object.keys(checks), function(check, cb) {
    var required;
    try {
      required = require("./check/" + check + ".js");
    } catch (err) {
      cb(err);
      return;
    }
    required.check(objects, checks[check], function(err, findings) {
      if (err) {
        cb(err);
      } else {
        cb(null, findings);
      }
    });
  }, function(err, nestedFindings) {
    if (err) {
      cb(err);
    } else {
      cb(null, _.flatten(nestedFindings));
    }
  });
}

function checkTemplate(template, checks, cb) {
  mapTemplate(template, function(err, objects) {
    if (err) {
      cb(err);
    } else {
      runChecks(objects, checks, cb);
    }
  });
}

exports.checkTemplate = checkTemplate;

exports.checkFile = function(filename, checks, cb) {
  loadJSONFile(filename, function(err, json) {
    if (err) {
      cb(err);
    } else {
      parseJSON(json, function(err, template) {
        if (err) {
          cb(err);
        } else {
          checkTemplate(template, checks, cb);
        }
      });
    }
  });
};
