loreanvictor / tmplr

Automate Code Scaffolding
MIT License
26 stars 0 forks source link

Reverse copy? #10

Closed YuriGal closed 1 year ago

YuriGal commented 1 year ago

Is there a way to do reverse copy command - take the working file and copy it into the template file replacing actual values with variable placeholders? The reasoning is - I am constantly developing the code and need the template to be in sync with the latest updates.

YuriGal commented 1 year ago

Just did a little JS script:

#!/usr/bin/env node
// @ts-nocheck

const yaml = require('js-yaml');
const fs = require('fs');

const tmplr = yaml.load(fs.readFileSync(`.tmplr.yml`, 'utf-8')).steps;
const files = tmplr.filter((step) => 'copy' in step);
const variables = tmplr.filter((step) => 'read' in step);

for (let file of files) {
  let fileContent = fs.readFileSync(file.to, 'utf-8');

  for (let variable of variables) {
    const regex = new RegExp(`(arn:aws[^:]*:[^:]*:[^:]*:)?${variable.eval}`, 'g');
    fileContent = fileContent.replace(regex, (match, p1) => (p1 ? match : `{{ tmplr.${variable.read} }}`));
  }

  fs.writeFileSync(file.copy, fileContent, { encoding: 'utf8', flag: 'w' });
  console.log(`✔ Un-templated: "${file.to}" -> "${file.copy}"`);
}

Basically reverse replacement (the RegEx part is for my particular scenario, I don't want replacement in the middle of ARN string)