<commit_before>'use strict';

//3rd Party Dependencies
var fs = require('fs');
var path = require('path');

//Own Dependencies
var mongoose = require('./mongo.js');
var Template = mongoose.model('template', require('../schemas/template.js'));
var Variable = mongoose.model('variable', require('../schemas/variable.js'));

//Globals
var config = {
  templatePath: path.normalize(__dirname + "/../templates/")
};

var readTemplates = {};


//Actual Code
readTemplates.init = function () {
  console.log(config.templatePath);
  var fileList = readTemplates.readFromFolder(config.templatePath);
  console.log(fileList);
  fileList.forEach(function (filename) {
    //Load File?
    var fileContent = fs.readFileSync(config.templatePath + filename, {encoding: 'utf8'});
    var parsedTemplate = readTemplates.parseTemplate(filename, fileContent);
    parsedTemplate.save();
  });
};

readTemplates.readFromFolder = function (path) {
  return fs.readdirSync(path) || [];
};

readTemplates.parseTemplate = function (filename, fileContent) {

  var contentVars = analyseContentVars(fileContent.match(/{{([a-zA-Z0-1#\/\s]*)}}/g) || []);
  var config = fileContent.match(/<!--((?:\n|\r|.)*)-->/)[1];
  if (config) {
    try {
      config = JSON.parse(config);
    } catch (e) {
      console.warn("Could not parse config in file " + filename + "! Maybe invalid JSON?\n Error: " + e);
    }
  }

  var hasVariables = !!contentVars.length;
  var hasConfig = !!Object.keys(config).length;

  var localTemplate = new Template({
    title: path.basename(filename),
    vars: []
  });

  if (hasConfig) {
    //Best Case
    //Overwrite prefilled information with values from config
    if (config.hasOwnProperty('title')) {
      localTemplate.title = config.title;
    }

    if (config.hasOwnProperty('name')) {
      localTemplate.name = config.name;
    }

    var configVars = config.hasOwnProperty('vars') ? config.vars : {};

    console.log(createVariables(fillWithDefault(mergeVars(configVars, contentVars))));
<commit_msg>adds first implementation of checking existing templates<commit_after>'use strict';

//3rd Party Dependencies
var fs = require('fs');
var path = require('path');

//Own Dependencies
var mongoose = require('./mongo.js');
var Template = mongoose.model('template', require('../schemas/template.js'));
var Variable = mongoose.model('variable', require('../schemas/variable.js'));

//Globals
var config = {
  templatePath: path.normalize(__dirname + "/../templates/")
};

var readTemplates = {};


//Actual Code
readTemplates.init = function () {
  var fileList = readTemplates.readFromFolder(config.templatePath);
  console.log(fileList);

  Template.remove({}, function(err, result) {
    if(err) throw err;
    console.log(result.result.ok);
  });

  Variable.remove({}, function(err, result) {
    if(err) throw err;
    console.log(result.result.ok);
  });

  fileList.forEach(function (filename) {
    //Load File?

    var nameArr = filename.split('.');
    nameArr.pop();
    var basename = nameArr.join('.');

    var fileContent = fs.readFileSync(config.templatePath + filename, {encoding: 'utf8'});
    var parsedTemplate = readTemplates.parseTemplate(basename, fileContent);

    Template.findOne({'name': basename}, function(err, doc) {
      if(err) {
        throw err;
      }
      if(doc) {
        console.log("found template", doc);
        console.log(parsedTemplate);
      } else {
        parsedTemplate.save();
        console.log('succesfully saved', parsedTemplate);
      }
    });
  });
};

readTemplates.readFromFolder = function (path) {
  return fs.readdirSync(path) || [];
};

readTemplates.parseTemplate = function (filename, fileContent) {

  var contentVars = analyseContentVars(fileContent.match(/{{([a-zA-Z0-1#\/\s]*)}}/g) || []);
  var config = fileContent.match(/<!--((?:\n|\r|.)*)-->/)[1];
  if (config) {
    try {
      config = JSON.parse(config);
    } catch (e) {
      console.warn("Could not parse config in file " + filename + "! Maybe invalid JSON?\n Error: " + e);
    }
  }

  var hasVariables = !!contentVars.length;
  var hasConfig = !!Object.keys(config).length;

  var localTemplate = new Template({
    title: path.basename(filename),
    vars: []
  });

  if (hasConfig) {
    //Best Case
    //Overwrite prefilled information with values from config
    if (config.hasOwnProperty('title')) {
      localTemplate.title = config.title;
    }

    if (config.hasOwnProperty('name')) {
      localTemplate.name = config.name;
    }

    var configVars = config.hasOwnProperty('vars') ? config.vars : {};

{'fraction_non_alphanumeric': 0.16666666666666666, 'fraction_numerical': 0.0021872265966754157, 'mean_word_length': 3.563872255489022, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4598042', 'n_tokens_mistral': 1427, 'n_tokens_neox': 1415, 'n_words': 296}