I am writing a Node.js script that clones a GitHub repository and then prompts the user with questions. With those answers, it should go through the files and replace the respective placeholder values with the users answers. The code runs and asks the questions, but does not update the files with the answers.
#!/usr/bin/env node
// const { program } = require('commander');
// const { execa } = require('execa');
// const inquirer = require('inquirer');
// const fs = require('fs');
// const path = require('path');
import { program } from 'commander';
import { execa } from 'execa';
import inquirer from 'inquirer';
import fs from 'fs';
import path from 'path';
program
.command('make-plugin <folder-name>')
.description('Clone repo and change values')
.action(async (folderName) => {
const repoURL = 'https://github.com/wpdev95/plugin-boiler';
const targetFolder = path.resolve(process.cwd(), folderName);
// Clone the repository
await execa('git', ['clone', repoURL, folderName]);
const questions = [
{
type: 'input',
name: 'Test Plugin',
message: 'What is the Name of your plugin?',
},
{
type: 'input',
name: 'test-plugin',
message: 'What is the slug of your plugin?',
},
{
type: 'input',
name: 'Plugin Author',
message: 'What is the author\'s name?',
},
];
// Ask questions only once
const answers = await inquirer.prompt(questions);
// Obtain the list of files
const files = fs.readdirSync(targetFolder).filter(file => {
const filePath = path.join(targetFolder, file);
return fs.statSync(filePath).isFile();
});
for (const file of files) {
const filePath = path.join(targetFolder, file);
let content = fs.readFileSync(filePath, 'utf-8');
// Replace placeholders in the content
for (const key in answers) {
const placeholder = `{{${key}}}`;
const replacement = answers[key];
content = content.replace(new RegExp(placeholder, 'g'), replacement);
}
// Update PHP file name
if (file === 'plugin-boilerplate.php') {
const newPhpFileName = `${answers['plugin_slug']}.php`;
const newPhpFilePath = path.join(targetFolder, newPhpFileName);
fs.renameSync(filePath, newPhpFilePath);
}
// Write back to the file
fs.writeFileSync(filePath, content, 'utf-8');
}
console.log('Plugin boilerplate was made successfully! Happy coding! :D');
});
program.parse(process.argv);