Skip to content

Commit

Permalink
Feature/rename script (imaginarymachines#1)
Browse files Browse the repository at this point in the history
* adds rename script
  • Loading branch information
g000m authored Oct 17, 2023
1 parent 150b324 commit 66e6e2f
Show file tree
Hide file tree
Showing 10 changed files with 399 additions and 2 deletions.
70 changes: 70 additions & 0 deletions cli/basic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#!/usr/bin/env node
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const shell = require('shelljs');
const mdSedFactory = require( './lib/mdSedFactory');
const phpSedFactory = require( './lib/phpSedFactory');

function packageJson(slug, extraScripts = undefined) {
const fs = require('fs');
let packageJson = JSON.parse(fs.readFileSync(`${slug}/package.json`, 'utf8'));

packageJson.name = slug;

if (extraScripts) {
packageJson.scripts = Object.assign(packageJson.scripts, extraScripts)
}

fs.writeFileSync(`${slug}/package.json`, JSON.stringify(packageJson));

}
readline.question(`What is your plugin's slug? Used for translation domain, main file name, etc.`, slug => {
slug = slug.replace(/[^a-zA-Z0-9-_]+/ig,'').toLowerCase();
readline.question(`Plugin name?`, pluginName => {
readline.question(`Github username?`, githubUserName => {
//sed functions for rewriting strings in files
const mdSed = mdSedFactory({pluginName,slug,githubUserName});
let phpOrJsSed = phpSedFactory({ slug });
//Copy everything in pages to new dir
shell.cp( '-R', 'pages', slug );
//Copy readme basic in place of package README
shell.cp( 'cli/templates/_README_BASIC.md', `${slug}/README.md`);
//And rename things.
mdSed( `${slug}/README.md` );
//Copy main plugin file
shell.cp( 'wordpress-plugin.php', `${slug}/${slug}.php`);
//And rename things.
//main plugin file
phpOrJsSed( `${slug}/${slug}.php` );
shell.sed('-i', "PLUGIN_NAME", pluginName, `${slug}/${slug}.php`);
//Javascript entry points
['admin', 'blocks'].map(entry => {
let fileName = `${slug}/${entry}/index.js`
phpOrJsSed( fileName );
shell.sed('-i', "PLUGIN_NAME", pluginName, fileName);
});


//Setup workflows
shell.mkdir( `${slug}/.github`);
shell.mkdir( `${slug}/.github/workflows`);
//Copy JS test action
shell.cp('cli/templates/test-js.yml', `${slug}/.github/workflows/test-js.yml`);
//Copy zipper
shell.cp('cli/templates/makeZip.js', `${slug}/makeZip.js`);
shell.sed('-i', "PLUGIN_NAME", slug, `${slug}/makeZip.js`);
//Replace slug in entry point
shell.sed('-i', "wordpress-plugin", slug, `${slug}/admin/index.js`);
//Build in the right directory
shell.sed('-i', "../build", "/build", `${slug}/webpack.config.js`);
//delete import test
shell.rm(`${slug}/__tests__/test-import.js`);
packageJson(slug, {
"zip": "yarn build && node makeZip.js"
})
readline.close()
});
});
});
9 changes: 9 additions & 0 deletions cli/lib/mdSedFactory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const shell = require('shelljs');

module.exports = function ({pluginName,slug,githubUserName}) {
return function(fileName) {
shell.sed('-i', 'Shelob9/wordpress-plugin', `${githubUserName}/${slug}`, fileName);
shell.sed('-i', 'PLUGIN_NAME', pluginName,fileName);
shell.sed('-i', 'wordpress-plugin', slug, fileName);
}
}
13 changes: 13 additions & 0 deletions cli/lib/phpSedFactory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const shell = require('shelljs');

module.exports = function ({slug,rootNamespace}) {
let originalNamespace = 'WordPressPlugin';
let slugWithUnderscore = slug.replace('-', '_');
return function (file) {
if (rootNamespace) {
shell.sed('-i', originalNamespace, rootNamespace, file);
}
shell.sed('-i', "wordpress-plugin", slug, file);
shell.sed('-i', "wordpress_plugin", slugWithUnderscore, file);
}
}
106 changes: 106 additions & 0 deletions cli/rename.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#!/usr/bin/env node
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const shell = require('shelljs');

function parseArgs(argList) {
const args = {};
for (let i = 0; i < argList.length; i++) {
if (argList[i].startsWith('--')) {
args[argList[i].substring(2)] = argList[i + 1];
}
}
return args;
}

const cmdArgs = parseArgs(process.argv);

const fs = require('fs');
const path = require('path');

const getFiles = (dir, ext) =>
fs.readdirSync(dir).flatMap(item => {
const itemPath = path.join(dir, item);
const stat = fs.statSync(itemPath);
return stat.isDirectory()
? getFiles(itemPath, ext)
: path.extname(item) === `.${ext}`
? [ itemPath ]
: [];
});

function changeNameInFiles({ fileType, replacements, targetDirs }) {
targetDirs
.filter(fs.existsSync)
.flatMap(dir => getFiles(dir, fileType))
.forEach(file => {
Object.entries(replacements).forEach(([ search, replace ]) => {
shell.sed('-i', search, replace, file);
});
});
}



function main({slug, rootNamespace, pluginName, githubUserName}) {
const originalNamespace = 'VendorNamespace';
const originalPluginNamespace = 'PluginNamespace';
const originalPluginName = 'PLUGIN_NAME';
const slugPlaceholder = 'pm2-modern-plugin';
const GithubUserNamePlaceholder = 'github-username';

const replacements = {
[slugPlaceholder]: slug,
[originalNamespace]: rootNamespace,
[originalPluginName]: pluginName,
[originalPluginNamespace]: pluginName,
[GithubUserNamePlaceholder]: githubUserName,
};

const targetDirs = ['classes', 'src', 'tests'];
const targetFilenames = ['composer.json', 'package.json', 'README.md', ];

['php', 'js', 'json', 'md', 'txt', 'css'].forEach(fileType => {
changeNameInFiles({fileType, replacements, targetDirs});
});

// Handle replacements in specific filenames
targetFilenames.forEach(filename => {
Object.entries(replacements).forEach(([placeholder, replacement]) => {
shell.sed('-i', placeholder, replacement, filename);
});
});

// Change filename for ${SlugPlaceholder}.php to ${slug}.php
const slugFilename = `${slugPlaceholder}.php`;
if (shell.test('-f', slugFilename)) {
shell.mv(slugFilename, `${slug}.php`);
} else {
console.log(`Could not find ${slugFilename} to rename`);
}

}

if (cmdArgs.slug && cmdArgs['root-namespace'] && cmdArgs['plugin-name'] && cmdArgs['github-username']) {
main({
slug: cmdArgs.slug,
rootNamespace: cmdArgs['root-namespace'],
pluginName: cmdArgs['plugin-name'],
githubUserName: cmdArgs['github-username']
});
readline.close();
} else {
readline.question(`What is your plugin's slug? `, slug => {
slug = slug.replace(/\W/g, '').toLowerCase();
readline.question(`Root Namespace `, rootNamespace => {
readline.question(`Plugin name? `, pluginName => {
readline.question(`Github username? `, githubUserName => {
main({slug, rootNamespace, pluginName, githubUserName});
readline.close();
});
});
});
});
}
34 changes: 34 additions & 0 deletions cli/templates/_README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# PLUGIN_NAME

![JavaScripts](https://github.com/Shelob9/wordpress-plugin/workflows/JavaScripts/badge.svg)
![PHP Unit Tests](https://github.com/Shelob9/wordpress-plugin/workflows/PHP%20Unit%20Tests/badge.svg)
![WordPress Tests](https://github.com/Shelob9/wordpress-plugin/workflows/WordPress%20Tests/badge.svg)

## Development Quick Start

- Git clone:
- `git clone https://github.com/Shelob9/wordpress-plugin`
- Composer install
- `composer install`
- Yarn install.
- `yarn`
- [Use Yarn 1.x, not npm](https://dev.to/shelob9/why-i-use-yarn-not-npm-dkk)
- Build JS/CSS
- `yarn build`
- Ensure unit tests pass
- `composer test`
- Start WordPress
- `npx wp-env start`

## Documentation

- [Getting Started](https://shelob9.github.io/wordpress-plugin/)
- [PHP](https://shelob9.github.io/wordpress-plugin/php)
- [JavaScript](https://shelob9.github.io/wordpress-plugin/javascript)
- [Local Development](https://shelob9.github.io/wordpress-plugin/local-dev)
- [CI/CD](https://shelob9.github.io/wordpress-plugin/cicd)


## Contributing

Please feel free to [open a pull request](https://github.com/Shelob9/wordpress-plugin/pulls) if you would like to contribute.
54 changes: 54 additions & 0 deletions cli/templates/_README_BASIC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# PLUGIN_NAME

## Development Quick Start

- Git clone:
- `git clone [email protected]:Shelob9/wordpress-plugin.git`
- Install.
- `yarn`
- Build JS/CSS
- `yarn build`
- Start JS/CSS for development
- `yarn start`
- Test changed files
- `yarn test --watch`
- Test all files once
- `yarn test`
- `yarn test --ci`
- Create an installable zip file of your plugin.
- `yarn zip`

## Entry Points

## `admin`

This entry point is used for a WordPress settings page in wp-admin.

### `block`

A gutenberg block

### To Add A New Entry Point

If you want to add additional entry points, for example if you want to add blocks or to have separate JavaScript/ CSS for the front-end, follow these steps:

- Choose a one word handle for the entry point
- Create a directory named for the handle.
- Add an index.js file to that directory
- Add the handle to the array `entryPoints` in webpack.config.js
- Run `yarn build`
- Check that `build/$handle.js` and `build/$handle.asset.php` where created.

## Local Development

Feel free to supply your own local development environment of choice. [wp-env](https://developer.wordpress.org/block-editor/packages/packages-env/) will work without any configuration, if you have Docker installed:

```vue
npx wp-env start
```

- [http://localhost:8888/](http://localhost:8888/)

## Contributing

Please feel free to [open a pull request](https://github.com/Shelob9/wordpress-plugin/pulls) if you would like to contribute.
25 changes: 25 additions & 0 deletions cli/templates/makeZip.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var fs = require('fs');
var archiver = require('archiver');

var output = fs.createWriteStream('PLUGIN_NAME.zip');
var archive = archiver('zip');

console.log( 'Zipping!')
output.on('close', function () {
console.log('Zipped!');
console.log(archive.pointer() + ' total bytes');
});

archive.on('error', function(err){
throw err;
});

archive.pipe(output);

archive.append(fs.createReadStream(
__dirname + '/PLUGIN_NAME.php'
), { name: 'PLUGIN_NAME.php' });

archive.directory('build', '/build');

archive.finalize();
17 changes: 17 additions & 0 deletions cli/templates/test-js.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: JavaScripts

on: [push]

jobs:
buildAndTest:
name: Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: "12"
- name: Install dependencies
run: yarn
- name: Test
run: yarn test --ci
Loading

0 comments on commit 66e6e2f

Please sign in to comment.