mirror of
https://github.com/chenasraf/simple-scaffold.git
synced 2026-05-18 01:29:09 +00:00
Compare commits
87 Commits
v0.1.4
...
v1.0.0-alp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
711d8f0333 | ||
|
|
8b22e96329 | ||
|
|
53c0842ab8 | ||
|
|
48631325c1 | ||
|
|
045ad0118a | ||
|
|
b4dca7a954 | ||
|
|
7c42808f63 | ||
|
|
fd42013e8b | ||
|
|
961a72fcdc | ||
|
|
d6d99cfdf2 | ||
|
|
ea4ecabe02 | ||
|
|
c7749a8d33 | ||
|
|
a59f29d71d | ||
|
|
bc224d93e1 | ||
|
|
cf923d8889 | ||
|
|
01e458ee0c | ||
|
|
93853712f5 | ||
|
|
474a3dcc1f | ||
|
|
27e84d1093 | ||
|
|
a6f25facc0 | ||
|
|
3ee66b24f5 | ||
|
|
0ce19a7e1a | ||
|
|
7273538d79 | ||
|
|
43b64965e3 | ||
|
|
4f81654e05 | ||
|
|
8fcc7a6dc6 | ||
|
|
b4b0de6f2f | ||
|
|
2d5626ca70 | ||
|
|
564e821419 | ||
|
|
a52f9a0b84 | ||
|
|
aeddd44778 | ||
|
|
7cdf5e461b | ||
|
|
c42a58c2f2 | ||
|
|
d0c0152717 | ||
|
|
208ee307c8 | ||
|
|
54834909b9 | ||
|
|
40b592072e | ||
|
|
3cb9a6fcd8 | ||
|
|
12974b5561 | ||
|
|
7f98d469a3 | ||
|
|
cd25b04886 | ||
|
|
5cd637f41f | ||
|
|
0a4467ae5f | ||
|
|
713a0ed44f | ||
|
|
edec2d1c26 | ||
|
|
2e12907412 | ||
|
|
5b7e0e30f1 | ||
|
|
09238300cd | ||
|
|
552614ca3f | ||
|
|
813f706cf0 | ||
|
|
1bc2221472 | ||
|
|
f07affa124 | ||
|
|
ce22a2c34c | ||
|
|
7c0c347002 | ||
|
|
977288ae5a | ||
|
|
4afafa5a4a | ||
|
|
7bee2a51c7 | ||
|
|
d4c049baaf | ||
|
|
06590c4b6e | ||
|
|
c4f2dfb04f | ||
|
|
a410b79195 | ||
|
|
71d544aff4 | ||
|
|
20389d7b33 | ||
|
|
d7a4362725 | ||
|
|
0a2d7c08f3 | ||
|
|
a92c471243 | ||
|
|
07b1c4b1f0 | ||
|
|
ec91fbf639 | ||
|
|
85aa9f953b | ||
|
|
d6195c6c1d | ||
|
|
b14e3d2d76 | ||
|
|
fa2ddca57e | ||
|
|
686b0bf227 | ||
|
|
0be29dd89e | ||
|
|
4f29a612a3 | ||
|
|
14b60ffc79 | ||
|
|
1275743764 | ||
|
|
b09299b432 | ||
|
|
45e8de3034 | ||
|
|
a3a77e2ab5 | ||
|
|
f36015962d | ||
|
|
e391f8f68f | ||
|
|
4ca7c6acb3 | ||
|
|
0fd996413b | ||
|
|
e64c0e4a45 | ||
|
|
3e42ac5a95 | ||
|
|
eecec82aaa |
5
.editorconfig
Normal file
5
.editorconfig
Normal file
@@ -0,0 +1,5 @@
|
||||
[*]
|
||||
tab_width = 2
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
12
.github/FUNDING.yml
vendored
Normal file
12
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: casraf
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
48
.github/workflows/alpha.yml
vendored
Normal file
48
.github/workflows/alpha.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Alpha Releases
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [alpha]
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
if: "!contains(github.event.head_commit.message, '[skip ci]')"
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: "12.x"
|
||||
- run: yarn install --frozen-lockfile
|
||||
- run: yarn build
|
||||
- run: cd ./dist && yarn pack --filename=../package.tgz
|
||||
- uses: Klemensas/action-autotag@stable
|
||||
id: update_tag
|
||||
with:
|
||||
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
|
||||
tag_prefix: "v"
|
||||
- name: Publish on NPM
|
||||
uses: JS-DevTools/npm-publish@v1
|
||||
if: "!contains(github.event.head_commit.message, '[skip publish]')"
|
||||
with:
|
||||
package: ./dist/package.json
|
||||
token: "${{ secrets.NPM_TOKEN }}"
|
||||
- name: Create Release
|
||||
if: steps.update_tag.outputs.tagname && !contains(github.event.head_commit.message, '[skip publish]')
|
||||
uses: actions/create-release@v1
|
||||
id: create_release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ steps.update_tag.outputs.tagname }}
|
||||
release_name: Release ${{ steps.update_tag.outputs.tagname }}
|
||||
- name: Upload Release Asset
|
||||
if: steps.update_tag.outputs.tagname && !contains(github.event.head_commit.message, '[skip publish]')
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./package.tgz
|
||||
asset_name: package.tgz
|
||||
asset_content_type: application/tgz
|
||||
47
.github/workflows/main.yml
vendored
Normal file
47
.github/workflows/main.yml
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
name: Releases
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
if: "!contains(github.event.head_commit.message, '[skip ci]')"
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: "12.x"
|
||||
- run: yarn install --frozen-lockfile
|
||||
- run: yarn build
|
||||
- run: cd ./dist && yarn pack --filename=../package.tgz
|
||||
- uses: Klemensas/action-autotag@stable
|
||||
id: update_tag
|
||||
with:
|
||||
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
|
||||
tag_prefix: "v"
|
||||
- name: Publish on NPM
|
||||
uses: JS-DevTools/npm-publish@v1
|
||||
with:
|
||||
package: ./dist/package.json
|
||||
token: "${{ secrets.NPM_TOKEN }}"
|
||||
- name: Create Release
|
||||
if: steps.update_tag.outputs.tagname && !contains(github.event.head_commit.message, '[skip publish]')
|
||||
uses: actions/create-release@v1
|
||||
id: create_release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ steps.update_tag.outputs.tagname }}
|
||||
release_name: Release ${{ steps.update_tag.outputs.tagname }}
|
||||
- name: Upload Release Asset
|
||||
if: steps.update_tag.outputs.tagname && !contains(github.event.head_commit.message, '[skip publish]')
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./package.tgz
|
||||
asset_name: package.tgz
|
||||
asset_content_type: application/tgz
|
||||
17
.github/workflows/pull_requests.yml
vendored
Normal file
17
.github/workflows/pull_requests.yml
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
name: Pull Requests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [master, alpha, beta]
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
if: "!contains(github.event.head_commit.message, '[skip ci]')"
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: "12.x"
|
||||
- run: yarn install --frozen-lockfile
|
||||
- run: yarn build
|
||||
- run: yarn test
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -57,4 +57,6 @@ typings/
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
|
||||
examples/test-output
|
||||
examples/test-output/**/*
|
||||
dist/
|
||||
.DS_Store
|
||||
|
||||
5
.prettierrc
Normal file
5
.prettierrc
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"semi": false,
|
||||
"printWidth": 120,
|
||||
"tabWidth": 2
|
||||
}
|
||||
24
.vscode/launch.json
vendored
24
.vscode/launch.json
vendored
@@ -4,18 +4,26 @@
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Debug Scaffold",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"protocol": "inspector",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"program": "${workspaceFolder}/test.ts",
|
||||
"outFiles": [
|
||||
"${workspaceRoot}/dist/test.js"
|
||||
],
|
||||
"env": {
|
||||
"NODE_ENV": "develop"
|
||||
},
|
||||
"sourceMaps": true,
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "attach",
|
||||
"name": "Attach by Process ID",
|
||||
"processId": "${command:PickProcess}"
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Debug Scaffold",
|
||||
"protocol": "inspector",
|
||||
"program": "${workspaceFolder}/dist/scaffold.js"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
7
.vscode/settings.json
vendored
Normal file
7
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"typescript.tsdk": "./node_modules/typescript/lib",
|
||||
"npm.packageManager": "yarn",
|
||||
"cSpell.words": [
|
||||
"massarg"
|
||||
]
|
||||
}
|
||||
53
.vscode/tasks.json
vendored
Normal file
53
.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"script": "build",
|
||||
"label": "build",
|
||||
"type": "npm",
|
||||
"problemMatcher": [],
|
||||
},
|
||||
{
|
||||
"script": "dev",
|
||||
"label": "dev",
|
||||
"type": "npm",
|
||||
"problemMatcher": [],
|
||||
},
|
||||
{
|
||||
"script": "start",
|
||||
"label": "start",
|
||||
"type": "npm",
|
||||
"problemMatcher": [],
|
||||
},
|
||||
{
|
||||
"script": "test",
|
||||
"label": "test",
|
||||
"type": "npm",
|
||||
"problemMatcher": [],
|
||||
},
|
||||
{
|
||||
"command": "yarn test --watchAll",
|
||||
"label": "yarn test --watchAll",
|
||||
"type": "shell",
|
||||
"problemMatcher": [],
|
||||
},
|
||||
{
|
||||
"script": "cmd",
|
||||
"label": "cmd",
|
||||
"type": "npm",
|
||||
"problemMatcher": [],
|
||||
},
|
||||
{
|
||||
"script": "build-test",
|
||||
"label": "build-test",
|
||||
"type": "npm",
|
||||
"problemMatcher": [],
|
||||
},
|
||||
{
|
||||
"script": "build-cmd",
|
||||
"label": "build-cmd",
|
||||
"type": "npm",
|
||||
"problemMatcher": [],
|
||||
},
|
||||
],
|
||||
}
|
||||
210
README.md
210
README.md
@@ -1,12 +1,208 @@
|
||||
# scaffolder
|
||||
Scaffolder allows you to create your structured files based on templates.
|
||||
# simple-scaffold
|
||||
|
||||
### How to use
|
||||
Simple Scaffold allows you to create your structured files based on templates.
|
||||
|
||||
#### Install
|
||||
You Scaffolder by using `npm`. Global flag is useful if you want easy cli access to it.
|
||||
## Install
|
||||
|
||||
```
|
||||
npm install -g scaffolder
|
||||
You can either use it as a command line tool or import into your own code and run from there.
|
||||
|
||||
```bash
|
||||
# npm
|
||||
npm install [-g] simple-scaffold
|
||||
# yarn
|
||||
yarn [global] add simple-scaffold
|
||||
# run without installing
|
||||
npx simple-scaffold <...args>
|
||||
```
|
||||
|
||||
## Use as a command line tool
|
||||
|
||||
### Command Line Options
|
||||
|
||||
```plaintext
|
||||
Usage: simple-scaffold [options]
|
||||
|
||||
Options:
|
||||
|
||||
--help|-h Display help information
|
||||
|
||||
--name|-n Name to be passed to the generated files. {{name}} and
|
||||
{{Name}} inside contents and file names will be replaced
|
||||
accordingly.
|
||||
|
||||
--output|-o Path to output to. If --create-sub-folder is enabled, the
|
||||
subfolder will be created inside this path.
|
||||
|
||||
--templates|-t Template files to use as input. You may provide multiple
|
||||
files, each of which can be a relative or absolute path, or a glob
|
||||
pattern for multiple file matching easily.
|
||||
|
||||
--overwrite|-w Enable to override output files, even if they already exist.
|
||||
(default: false)
|
||||
|
||||
--data|-d Add custom data to the templates. By default, only your app
|
||||
name is included.
|
||||
|
||||
--create-sub-folder|-s Create subfolder with the input name (default:
|
||||
false)
|
||||
|
||||
--quiet|-q Suppress output logs (default:
|
||||
false)
|
||||
|
||||
--dry-run|-dr Don't emit actual files. This is good for testing your
|
||||
scaffolds and making sure they don't fail, without having to write
|
||||
actual files. (default: false)
|
||||
```
|
||||
|
||||
You can also add this as a script in your `package.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"scaffold": "yarn simple-scaffold --templates scaffolds/component/**/* --output src/components --data '{\"myProp\": \"propName\", \"myVal\": \"123\"}'"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Use in Node.js
|
||||
|
||||
You can also build the scaffold yourself, if you want to create more complex arguments or scaffold groups.
|
||||
Simply pass a config object to the constructor, and invoke `run()` when you are ready to start.
|
||||
The config takes similar arguments to the command line:
|
||||
|
||||
```javascript
|
||||
const SimpleScaffold = require("simple-scaffold").default
|
||||
|
||||
const scaffold = new SimpleScaffold({
|
||||
name: "component",
|
||||
templates: [path.join(__dirname, "scaffolds", "component")],
|
||||
output: path.join(__dirname, "src", "components"),
|
||||
createSubFolder: true,
|
||||
locals: {
|
||||
property: "value",
|
||||
},
|
||||
}).run()
|
||||
```
|
||||
|
||||
The exception in the config is that `output`, when used in Node directly, may also be passed a
|
||||
function for each input file to output into a dynamic path:
|
||||
|
||||
```javascript
|
||||
config.output = (fullPath, baseDir, baseName) => {
|
||||
console.log({ fullPath, baseDir, baseName })
|
||||
return [baseDir, baseName].join(path.sep)
|
||||
}
|
||||
```
|
||||
|
||||
## Preparing files
|
||||
|
||||
### Template files
|
||||
|
||||
Put your template files anywhere, and fill them with tokens for replacement.
|
||||
|
||||
### Variable/token replacement
|
||||
|
||||
Scaffolding will replace `{{ varName }}` in both the file name and its contents and put the
|
||||
transformed files in the output directory.
|
||||
|
||||
The data available for the template parser is the data you pass to the `data` config option (or
|
||||
`--data` argument in CLI).
|
||||
|
||||
Your `data` will be pre-populated with the following:
|
||||
|
||||
- `{{Name}}`: PascalCase of the component name
|
||||
- `{{name}}`: raw name of the component
|
||||
|
||||
> Simple-Scaffold uses [Handlebars.js](https://handlebarsjs.com/) for outputting the file contents,
|
||||
> see their documentation for more information on syntax.
|
||||
> Any `data` you add in the config will be available for use with their names wrapped in
|
||||
> `{{` and `}}`.
|
||||
|
||||
Simple-Scaffold provides some built-in text transformation filters usable by handleBars.
|
||||
|
||||
For example, you may use `{{ name | snakeCase }}` inside a template file or filename, and it will
|
||||
replace `My Name` with `my_name` when producing the final value.
|
||||
|
||||
Here are the built-in helpers available for use:
|
||||
|
||||
```plaintext
|
||||
{{ name | camelCase }} => myName
|
||||
{{ name | snakeCase }} => my_name
|
||||
{{ name | startCase }} => My Name
|
||||
{{ name | kebabCase }} => my-name
|
||||
{{ name | hyphenCase }} => my-name
|
||||
{{ name | pascalCase }} => MyName
|
||||
```
|
||||
|
||||
**Note:** These helpers are available for any data property, not exclusive to `name`.
|
||||
|
||||
## Examples
|
||||
|
||||
### Command Example
|
||||
|
||||
```bash
|
||||
simple-scaffold MyComponent \
|
||||
-t project/scaffold/**/* \
|
||||
-o src/components \
|
||||
-d '{"className":"myClassName"}'
|
||||
```
|
||||
|
||||
### Example Scaffold Input
|
||||
|
||||
#### Input Directory structure
|
||||
|
||||
```plaintext
|
||||
- project
|
||||
- scaffold
|
||||
- {{Name}}.js
|
||||
- src
|
||||
- components
|
||||
- ...
|
||||
```
|
||||
|
||||
#### Contents of `project/scaffold/{{Name}}.js`
|
||||
|
||||
```js
|
||||
const React = require('react')
|
||||
|
||||
module.exports = class {{Name}} extends React.Component {
|
||||
render() {
|
||||
<div className="{{className}}">{{Name}} Component</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Example Scaffold Output
|
||||
|
||||
### Output directory structure
|
||||
|
||||
```plaintext
|
||||
- project
|
||||
- src
|
||||
- components
|
||||
- MyComponent
|
||||
- MyComponent.js
|
||||
- ...
|
||||
```
|
||||
|
||||
With `createSubfolder = false`:
|
||||
|
||||
```plaintext
|
||||
- project
|
||||
- src
|
||||
- components
|
||||
- MyComponent.js
|
||||
- ...
|
||||
```
|
||||
|
||||
#### Contents of `project/scaffold/MyComponent/MyComponent.js`
|
||||
|
||||
```js
|
||||
const React = require("react")
|
||||
|
||||
module.exports = class MyComponent extends React.Component {
|
||||
render() {
|
||||
<div className="my-component">MyComponent Component</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3
babel.config.js
Normal file
3
babel.config.js
Normal file
@@ -0,0 +1,3 @@
|
||||
module.exports = {
|
||||
plugins: ["@babel/plugin-proposal-nullish-coalescing-operator"],
|
||||
}
|
||||
1
dist/scaffold.js
vendored
1
dist/scaffold.js
vendored
@@ -1 +0,0 @@
|
||||
!function(t){function e(n){if(o[n])return o[n].exports;var i=o[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var o={};e.m=t,e.c=o,e.d=function(t,o,n){e.o(t,o)||Object.defineProperty(t,o,{configurable:!1,enumerable:!0,get:n})},e.n=function(t){var o=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(o,"a",o),o},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=0)}([function(t,e,o){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=o(1),i=(o.n(n),o(2)),s=(o.n(i),function(){function t(t){if(this.locals={},this.scaffoldName=process.argv[2],this.DefaultConfig={templates:[],output:i.resolve(process.cwd()),locals:{Name:this.scaffoldName[0].toUpperCase()+this.scaffoldName.slice(1),name:this.scaffoldName[0].toLowerCase()+this.scaffoldName.slice(1)}},!this.scaffoldName)throw new Error("Must provide scaffold name");this.config=Object.assign({},this.DefaultConfig,t),this.locals=Object.assign({},this.DefaultConfig.locals,t.locals),console.info("Config loaded:",this.config),console.info("Locals:",this.locals)}return t.prototype.parseLocals=function(t){var e=this,o=t.toString(),n=/{[%]\s*([^%{}]+)\s*[%]}/gi;return o.replace(n,function(t,o){return e.locals[o]})},t.prototype.getFileList=function(t){var e=this,o=[];return t.forEach(function(t){var s=n.lstatSync(t);if(s.isFile())console.info("pushing",t),o.push(t);else if(s.isDirectory()){console.info("going into dir",t);var r=n.readdirSync(t).map(function(e){return i.join(t,e)});o=o.concat(e.getFileList(r))}}),o},t.prototype.getFileContents=function(t){return n.readFileSync(t).toString()},t.prototype.getOutputPath=function(t){var e;return e="function"==typeof this.config.output?this.config.output(t):this.config.output+"/"+this.scaffoldName+"/"+i.basename(t),this.parseLocals(e)},t.prototype.writeFile=function(t,e){n.existsSync(i.dirname(t))||n.mkdirSync(i.dirname(t)),console.info("Writing file:",t),n.writeFileSync(t,e,{encoding:"utf-8"})},t.prototype.run=function(){var t=this,e=this.getFileList(this.config.templates);console.info(e),e.forEach(function(e){var o=t.getOutputPath(e),n=t.getFileContents(e),i=t.parseLocals(n);t.writeFile(o,i)})},t}());exports.default=s},function(t,e){t.exports=require("fs")},function(t,e){t.exports=require("path")}]);
|
||||
1
examples/test-input/Component/inner/inner-{{name}}.txt
Normal file
1
examples/test-input/Component/inner/inner-{{name}}.txt
Normal file
@@ -0,0 +1 @@
|
||||
{{name}}
|
||||
@@ -1,13 +0,0 @@
|
||||
import * as React from 'react'
|
||||
|
||||
class {%Name%} extends React.Component {
|
||||
private {%property%}
|
||||
|
||||
constructor() {
|
||||
this.{%property%} = {%value%}
|
||||
}
|
||||
|
||||
<div className={css.{%Name%}} />
|
||||
}
|
||||
|
||||
export default {%Name%}
|
||||
17
examples/test-input/Component/{{Name}}.tsx
Normal file
17
examples/test-input/Component/{{Name}}.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import * as React from "react"
|
||||
import * as css from "./{{Name}}.css"
|
||||
|
||||
class {{Name}} extends React.Component<any> {
|
||||
private {{ property }}
|
||||
|
||||
constructor(props: any) {
|
||||
super(props)
|
||||
this.{{ property }} = {{ value }}
|
||||
}
|
||||
|
||||
public render() {
|
||||
return <div className={ css.{{Name}} } />
|
||||
}
|
||||
}
|
||||
|
||||
export default {{Name}}
|
||||
15
index.d.ts
vendored
15
index.d.ts
vendored
@@ -1,15 +0,0 @@
|
||||
export namespace IScaffold {
|
||||
|
||||
export interface IConfig {
|
||||
templates: string[]
|
||||
output: string | ((path: string) => string)
|
||||
locals?: any
|
||||
}
|
||||
|
||||
export interface IReplacement {
|
||||
find: string | RegExp
|
||||
replace(): string
|
||||
[other: string]: any
|
||||
}
|
||||
|
||||
}
|
||||
196
jest.config.ts
Normal file
196
jest.config.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* For a detailed explanation regarding each configuration property and type check, visit:
|
||||
* https://jestjs.io/docs/configuration
|
||||
*/
|
||||
|
||||
export default {
|
||||
// All imported modules in your tests should be mocked automatically
|
||||
// automock: false,
|
||||
|
||||
// Stop running tests after `n` failures
|
||||
// bail: 0,
|
||||
|
||||
// The directory where Jest should store its cached dependency information
|
||||
// cacheDirectory: "/private/var/folders/q9/0mns8fgd00b4t5j5lq2wh2yh0000gn/T/jest_dx",
|
||||
|
||||
// Automatically clear mock calls and instances between every test
|
||||
clearMocks: true,
|
||||
|
||||
// Indicates whether the coverage information should be collected while executing the test
|
||||
collectCoverage: true,
|
||||
|
||||
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
||||
// collectCoverageFrom: undefined,
|
||||
|
||||
// The directory where Jest should output its coverage files
|
||||
coverageDirectory: "coverage",
|
||||
|
||||
// An array of regexp pattern strings used to skip coverage collection
|
||||
// coveragePathIgnorePatterns: [
|
||||
// "/node_modules/"
|
||||
// ],
|
||||
|
||||
// Indicates which provider should be used to instrument code for coverage
|
||||
coverageProvider: "v8",
|
||||
|
||||
// A list of reporter names that Jest uses when writing coverage reports
|
||||
// coverageReporters: [
|
||||
// "json",
|
||||
// "text",
|
||||
// "lcov",
|
||||
// "clover"
|
||||
// ],
|
||||
|
||||
// An object that configures minimum threshold enforcement for coverage results
|
||||
// coverageThreshold: undefined,
|
||||
|
||||
// A path to a custom dependency extractor
|
||||
// dependencyExtractor: undefined,
|
||||
|
||||
// Make calling deprecated APIs throw helpful error messages
|
||||
// errorOnDeprecated: false,
|
||||
|
||||
// Force coverage collection from ignored files using an array of glob patterns
|
||||
// forceCoverageMatch: [],
|
||||
|
||||
// A path to a module which exports an async function that is triggered once before all test suites
|
||||
// globalSetup: undefined,
|
||||
|
||||
// A path to a module which exports an async function that is triggered once after all test suites
|
||||
// globalTeardown: undefined,
|
||||
|
||||
// A set of global variables that need to be available in all test environments
|
||||
// globals: {},
|
||||
|
||||
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
||||
// maxWorkers: "50%",
|
||||
|
||||
// An array of directory names to be searched recursively up from the requiring module's location
|
||||
// moduleDirectories: [
|
||||
// "node_modules"
|
||||
// ],
|
||||
|
||||
// An array of file extensions your modules use
|
||||
// moduleFileExtensions: [
|
||||
// "js",
|
||||
// "jsx",
|
||||
// "ts",
|
||||
// "tsx",
|
||||
// "json",
|
||||
// "node"
|
||||
// ],
|
||||
|
||||
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
||||
// moduleNameMapper: {},
|
||||
|
||||
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
||||
modulePathIgnorePatterns: ["<rootDir>/dist"],
|
||||
|
||||
// Activates notifications for test results
|
||||
// notify: false,
|
||||
|
||||
// An enum that specifies notification mode. Requires { notify: true }
|
||||
// notifyMode: "failure-change",
|
||||
|
||||
// A preset that is used as a base for Jest's configuration
|
||||
preset: "ts-jest",
|
||||
|
||||
// Run tests from one or more projects
|
||||
// projects: undefined,
|
||||
|
||||
// Use this configuration option to add custom reporters to Jest
|
||||
// reporters: undefined,
|
||||
|
||||
// Automatically reset mock state between every test
|
||||
// resetMocks: false,
|
||||
|
||||
// Reset the module registry before running each individual test
|
||||
// resetModules: false,
|
||||
|
||||
// A path to a custom resolver
|
||||
// resolver: undefined,
|
||||
|
||||
// Automatically restore mock state between every test
|
||||
// restoreMocks: false,
|
||||
|
||||
// The root directory that Jest should scan for tests and modules within
|
||||
// rootDir: undefined,
|
||||
|
||||
// A list of paths to directories that Jest should use to search for files in
|
||||
// roots: [
|
||||
// "<rootDir>"
|
||||
// ],
|
||||
|
||||
// Allows you to use a custom runner instead of Jest's default test runner
|
||||
// runner: "jest-runner",
|
||||
|
||||
// The paths to modules that run some code to configure or set up the testing environment before each test
|
||||
// setupFiles: [],
|
||||
|
||||
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
||||
// setupFilesAfterEnv: [],
|
||||
|
||||
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
||||
// slowTestThreshold: 5,
|
||||
|
||||
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
||||
// snapshotSerializers: [],
|
||||
|
||||
// The test environment that will be used for testing
|
||||
testEnvironment: "node",
|
||||
|
||||
// Options that will be passed to the testEnvironment
|
||||
// testEnvironmentOptions: {},
|
||||
|
||||
// Adds a location field to test results
|
||||
// testLocationInResults: false,
|
||||
|
||||
// The glob patterns Jest uses to detect test files
|
||||
// testMatch: [
|
||||
// "**/__tests__/**/*.[jt]s?(x)",
|
||||
// "**/?(*.)+(spec|test).[tj]s?(x)"
|
||||
// ],
|
||||
|
||||
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
||||
// testPathIgnorePatterns: [
|
||||
// "/node_modules/"
|
||||
// ],
|
||||
|
||||
// The regexp pattern or array of patterns that Jest uses to detect test files
|
||||
// testRegex: [],
|
||||
|
||||
// This option allows the use of a custom results processor
|
||||
// testResultsProcessor: undefined,
|
||||
|
||||
// This option allows use of a custom test runner
|
||||
// testRunner: "jest-circus/runner",
|
||||
|
||||
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
|
||||
// testURL: "http://localhost",
|
||||
|
||||
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
|
||||
// timers: "real",
|
||||
|
||||
// A map from regular expressions to paths to transformers
|
||||
// transform: {},
|
||||
|
||||
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
||||
// transformIgnorePatterns: [
|
||||
// "/node_modules/",
|
||||
// "\\.pnp\\.[^\\/]+$"
|
||||
// ],
|
||||
|
||||
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
||||
// unmockedModulePathPatterns: undefined,
|
||||
|
||||
// Indicates whether each individual test should be reported during the run
|
||||
// verbose: undefined,
|
||||
|
||||
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
||||
// watchPathIgnorePatterns: [],
|
||||
|
||||
// Whether to use watchman for file crawling
|
||||
// watchman: true,
|
||||
|
||||
// extensionsToTreatAsEsm: [".ts"],
|
||||
}
|
||||
44
package.json
44
package.json
@@ -1,26 +1,42 @@
|
||||
{
|
||||
"name": "simple-scaffold",
|
||||
"version": "0.1.4",
|
||||
"version": "1.0.0-alpha.5",
|
||||
"description": "Create files based on templates",
|
||||
"repository": "https://github.com/chenasraf/simple-scaffold.git",
|
||||
"author": "Chen Asraf <inbox@casraf.com>",
|
||||
"license": "MIT",
|
||||
"main": "dist/scaffold.js",
|
||||
"bin": "dist/scaffold.js",
|
||||
"main": "index.js",
|
||||
"bin": "cmd.js",
|
||||
"types": "types.d.ts",
|
||||
"scripts": {
|
||||
"build": "webpack -p && chmod +x dist/scaffold.js",
|
||||
"dev": "webpack --watch",
|
||||
"clean": "rm -rf dist/",
|
||||
"build": "yarn clean && tsc && chmod -R +x ./dist && cp ./package.json ./dist/ && cp ./README.md ./dist/",
|
||||
"dev": "tsc --watch",
|
||||
"start": "node dist/scaffold.js",
|
||||
"test": "yarn build && node scripts/test.js"
|
||||
"test": "jest --verbose",
|
||||
"cmd": "node --trace-warnings dist/cmd.js",
|
||||
"build-test": "yarn build && yarn test",
|
||||
"build-cmd": "yarn build && yarn cmd"
|
||||
},
|
||||
"dependencies": {
|
||||
"args": "^5.0.1",
|
||||
"glob": "^7.1.3",
|
||||
"handlebars": "^4.7.7",
|
||||
"lodash": "^4.17.21",
|
||||
"massarg": "^0.1.2",
|
||||
"util.promisify": "^1.1.1"
|
||||
},
|
||||
"files": [
|
||||
"dist/scaffold.js"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@types/node": "^8.0.50",
|
||||
"ts-loader": "^3.1.1",
|
||||
"typescript": "^2.6.1",
|
||||
"webpack": "^3.8.1",
|
||||
"webpack-dev-server": "^2.9.4"
|
||||
"@types/args": "^3.0.1",
|
||||
"@types/glob": "^7.1.1",
|
||||
"@types/jest": "^26.0.24",
|
||||
"@types/lodash": "^4.14.171",
|
||||
"@types/mock-fs": "^4.13.1",
|
||||
"@types/node": "^14.14.22",
|
||||
"jest": "^27.0.6",
|
||||
"mock-fs": "^5.0.0",
|
||||
"ts-jest": "^27.0.3",
|
||||
"ts-node": "^10.1.0",
|
||||
"typescript": "^4.3.5"
|
||||
}
|
||||
}
|
||||
|
||||
88
scaffold.ts
88
scaffold.ts
@@ -1,88 +0,0 @@
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { IScaffold } from './index'
|
||||
|
||||
class SimpleScaffold {
|
||||
private config: IScaffold.IConfig
|
||||
private locals = {} as any
|
||||
public scaffoldName = process.argv[2]
|
||||
private DefaultConfig: IScaffold.IConfig = {
|
||||
templates: [],
|
||||
output: path.resolve(process.cwd()),
|
||||
locals: {
|
||||
Name: this.scaffoldName[0].toUpperCase() + this.scaffoldName.slice(1),
|
||||
name: this.scaffoldName[0].toLowerCase() + this.scaffoldName.slice(1)
|
||||
}
|
||||
}
|
||||
|
||||
constructor(config: IScaffold.IConfig) {
|
||||
if (!this.scaffoldName) {
|
||||
throw new Error('Must provide scaffold name')
|
||||
}
|
||||
this.config = (Object as any).assign({}, this.DefaultConfig, config)
|
||||
this.locals = (Object as any).assign({}, this.DefaultConfig.locals, config.locals)
|
||||
console.info('Config loaded:', this.config)
|
||||
console.info('Locals:', this.locals)
|
||||
}
|
||||
|
||||
private parseLocals(text: string): string {
|
||||
let out = text.toString()
|
||||
const pattern = /{[%]\s*([^%{}]+)\s*[%]}/gi
|
||||
return out.replace(pattern, (match: string, $1: string) => this.locals[$1])
|
||||
}
|
||||
|
||||
private getFileList(pathList: string[]): string[] {
|
||||
let outList: string[] = []
|
||||
|
||||
pathList.forEach((checkPath: string) => {
|
||||
const stat = fs.lstatSync(checkPath)
|
||||
if (stat.isFile()) {
|
||||
console.info('pushing', checkPath)
|
||||
outList.push(checkPath)
|
||||
} else if (stat.isDirectory()) {
|
||||
console.info('going into dir', checkPath)
|
||||
const innerFiles = fs.readdirSync(checkPath).map(p => path.join(checkPath, p))
|
||||
outList = outList.concat(this.getFileList(innerFiles))
|
||||
}
|
||||
})
|
||||
|
||||
return outList
|
||||
}
|
||||
|
||||
private getFileContents(filePath: string): string {
|
||||
return fs.readFileSync(filePath).toString()
|
||||
}
|
||||
|
||||
private getOutputPath(file: string): string {
|
||||
let out
|
||||
|
||||
if (typeof this.config.output === 'function') {
|
||||
out = this.config.output(file)
|
||||
} else {
|
||||
out = this.config.output + `/${this.scaffoldName}/` + path.basename(file)
|
||||
}
|
||||
|
||||
return this.parseLocals(out)
|
||||
}
|
||||
|
||||
private writeFile(filePath: string, fileContents: string): void {
|
||||
if (!fs.existsSync(path.dirname(filePath))) {
|
||||
fs.mkdirSync(path.dirname(filePath))
|
||||
}
|
||||
console.info('Writing file:', filePath)
|
||||
fs.writeFileSync(filePath, fileContents, { encoding: 'utf-8' })
|
||||
}
|
||||
|
||||
public run() {
|
||||
const inputFiles = this.getFileList(this.config.templates)
|
||||
console.info(inputFiles)
|
||||
inputFiles.forEach((file: string) => {
|
||||
const outputPath = this.getOutputPath(file)
|
||||
const contents = this.getFileContents(file)
|
||||
const outputContents = this.parseLocals(contents)
|
||||
this.writeFile(outputPath, outputContents)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
exports.default = SimpleScaffold
|
||||
@@ -1,12 +0,0 @@
|
||||
const Scaffolder = require('../dist/scaffold').default
|
||||
|
||||
const templateDir = process.cwd() + '/examples'
|
||||
|
||||
const scf = new Scaffolder({
|
||||
templates: [templateDir + '/test-input/Component'],
|
||||
output: templateDir + '/test-output',
|
||||
locals: {
|
||||
property: 'myProp',
|
||||
value: '"value"'
|
||||
}
|
||||
}).run()
|
||||
69
src/cmd.ts
Normal file
69
src/cmd.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import Scaffold from "./scaffold"
|
||||
import massarg from "massarg"
|
||||
import { ScaffoldCmdConfig } from "./types"
|
||||
|
||||
massarg<ScaffoldCmdConfig & { help: boolean; extras: string[] }>()
|
||||
.main(Scaffold)
|
||||
.option({
|
||||
name: "name",
|
||||
aliases: ["n"],
|
||||
isDefault: true,
|
||||
description:
|
||||
"Name to be passed to the generated files. {{name}} and {{Name}} inside contents and file names will be replaced accordingly.",
|
||||
})
|
||||
.option({
|
||||
name: "output",
|
||||
aliases: ["o"],
|
||||
description:
|
||||
"Path to output to. If --create-sub-folder is enabled, the subfolder will be created inside this path.",
|
||||
})
|
||||
.option({
|
||||
name: "templates",
|
||||
aliases: ["t"],
|
||||
description:
|
||||
"Template files to use as input. You may provide multiple files, each of which can be a relative or absolute path, " +
|
||||
"or a glob pattern for multiple file matching easily.",
|
||||
defaultValue: [],
|
||||
array: true,
|
||||
})
|
||||
.option({
|
||||
aliases: ["w"],
|
||||
name: "overwrite",
|
||||
description: "Enable to override output files, even if they already exist.",
|
||||
defaultValue: false,
|
||||
boolean: true,
|
||||
})
|
||||
.option({
|
||||
aliases: ["d"],
|
||||
name: "data",
|
||||
description: "Add custom data to the templates. By default, only your app name is included.",
|
||||
parse: (v) => JSON.parse(v),
|
||||
})
|
||||
.option({
|
||||
aliases: ["s"],
|
||||
name: "create-sub-folder",
|
||||
description: "Create subfolder with the input name",
|
||||
defaultValue: false,
|
||||
boolean: true,
|
||||
})
|
||||
.option({ aliases: ["q"], name: "quiet", description: "Suppress output logs", defaultValue: false, boolean: true })
|
||||
.option({
|
||||
aliases: ["dr"],
|
||||
name: "dry-run",
|
||||
description:
|
||||
"Don't emit files. This is good for testing your scaffolds and making sure they " +
|
||||
"don't fail, without having to write actual file contents or create directories.",
|
||||
defaultValue: false,
|
||||
boolean: true,
|
||||
})
|
||||
// .example({
|
||||
// input: `yarn cmd -t examples/test-input/Component -o examples/test-output -d '{"property":"myProp","value":"10"}'`,
|
||||
// description: "Usage",
|
||||
// output: "",
|
||||
// })
|
||||
.help({
|
||||
binName: "simple-scaffold",
|
||||
useGlobalColumns: true,
|
||||
usageExample: "[options]",
|
||||
})
|
||||
.parse()
|
||||
0
src/filters.ts
Normal file
0
src/filters.ts
Normal file
3
src/index.ts
Normal file
3
src/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from "./scaffold"
|
||||
import Scaffold from "./scaffold"
|
||||
export default Scaffold
|
||||
104
src/scaffold.ts
Normal file
104
src/scaffold.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { glob } from "glob"
|
||||
import path from "path"
|
||||
import { promisify } from "util"
|
||||
import { promises as fsPromises } from "fs"
|
||||
const { readFile, writeFile } = fsPromises
|
||||
|
||||
import {
|
||||
createDirIfNotExists,
|
||||
getOptionValueForFile,
|
||||
handleErr,
|
||||
handlebarsParse,
|
||||
log,
|
||||
pathExists,
|
||||
pascalCase,
|
||||
isDir,
|
||||
} from "./utils"
|
||||
import { ScaffoldConfig } from "./types"
|
||||
|
||||
export async function Scaffold(config: ScaffoldConfig) {
|
||||
try {
|
||||
const options = { ...config }
|
||||
const data = { name: options.name, Name: pascalCase(options.name), ...options.data }
|
||||
log(options, "Config:", {
|
||||
name: options.name,
|
||||
templates: options.templates,
|
||||
output: options.output,
|
||||
createSubfolder: options.createSubFolder,
|
||||
data: options.data,
|
||||
overwrite: options.overwrite,
|
||||
quiet: options.quiet,
|
||||
})
|
||||
log(options, "Data:", data)
|
||||
for (let template of config.templates) {
|
||||
try {
|
||||
const _isDir = await isDir(template)
|
||||
const basePath = path
|
||||
.resolve(process.cwd(), _isDir ? template : path.dirname(template.replace("*", "").replace("//", "/")))
|
||||
.replace(process.cwd(), ".")
|
||||
if (_isDir) {
|
||||
template = template + "/**/*"
|
||||
}
|
||||
const files = await promisify(glob)(template, { dot: true, debug: false })
|
||||
for (const templatePath of files) {
|
||||
if (!(await isDir(templatePath))) {
|
||||
await handleTemplateFile(templatePath, basePath, options, data)
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
handleErr(e)
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTemplateFile(
|
||||
templatePath: string,
|
||||
basePath: string,
|
||||
options: ScaffoldConfig,
|
||||
data: Record<string, string>
|
||||
): Promise<void> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
log(options, `Parsing ${templatePath}`)
|
||||
const inputPath = path.join(process.cwd(), templatePath)
|
||||
const outputPathOpt = getOptionValueForFile(inputPath, data, options.output)
|
||||
const outputDir = path.resolve(
|
||||
process.cwd(),
|
||||
...([outputPathOpt, options.createSubFolder ? options.name : undefined].filter(Boolean) as string[])
|
||||
)
|
||||
const outputPath = path.join(outputDir, handlebarsParse(path.basename(inputPath), data))
|
||||
const overwrite = getOptionValueForFile(inputPath, data, options.overwrite ?? false)
|
||||
const exists = await pathExists(outputPath)
|
||||
|
||||
await createDirIfNotExists(outputDir, options)
|
||||
|
||||
log(options, `Writing to ${outputPath}`)
|
||||
if (!exists || overwrite) {
|
||||
if (exists && overwrite) {
|
||||
log(options, `File ${outputPath} exists, overwriting`)
|
||||
}
|
||||
const templateBuffer = await readFile(inputPath)
|
||||
const outputContents = handlebarsParse(templateBuffer, data)
|
||||
|
||||
if (!options.dryRun) {
|
||||
await writeFile(outputPath, outputContents)
|
||||
} else {
|
||||
log(options, "Content output:")
|
||||
log(options, outputContents)
|
||||
}
|
||||
} else if (exists) {
|
||||
log(options, `File ${outputPath} already exists, skipping`)
|
||||
}
|
||||
resolve()
|
||||
} catch (e: any) {
|
||||
handleErr(e)
|
||||
reject(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export default Scaffold
|
||||
25
src/types.ts
Normal file
25
src/types.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
export type FileResponseFn<T> = (fullPath: string, basedir: string, basename: string) => T
|
||||
|
||||
export type FileResponse<T> = T | FileResponseFn<T>
|
||||
|
||||
export interface ScaffoldConfig {
|
||||
/** The name supplied for the output templates */
|
||||
name: string
|
||||
templates: string[]
|
||||
output: FileResponse<string>
|
||||
createSubFolder?: boolean
|
||||
data?: Record<string, string>
|
||||
overwrite?: FileResponse<boolean>
|
||||
quiet?: boolean
|
||||
dryRun?: boolean
|
||||
}
|
||||
export interface ScaffoldCmdConfig {
|
||||
name: string
|
||||
templates: string[]
|
||||
output: string
|
||||
createSubFolder: boolean
|
||||
data?: Record<string, string>
|
||||
overwrite: boolean
|
||||
quiet: boolean
|
||||
dryRun: boolean
|
||||
}
|
||||
97
src/utils.ts
Normal file
97
src/utils.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import path from "path"
|
||||
import { F_OK } from "constants"
|
||||
import { FileResponse, FileResponseFn, ScaffoldConfig } from "./types"
|
||||
import camelCase from "lodash/camelCase"
|
||||
import snakeCase from "lodash/snakeCase"
|
||||
import kebabCase from "lodash/kebabCase"
|
||||
import startCase from "lodash/startCase"
|
||||
import Handlebars from "handlebars"
|
||||
import { promises as fsPromises } from "fs"
|
||||
const { stat, access, mkdir } = fsPromises
|
||||
|
||||
const helpers = {
|
||||
camelCase,
|
||||
snakeCase,
|
||||
startCase,
|
||||
kebabCase,
|
||||
hyphenCase: kebabCase,
|
||||
pascalCase,
|
||||
}
|
||||
|
||||
for (const helperName in helpers) {
|
||||
Handlebars.registerHelper(helperName, helpers[helperName as keyof typeof helpers])
|
||||
}
|
||||
|
||||
export function handleErr(err: NodeJS.ErrnoException | null) {
|
||||
if (err) throw err
|
||||
}
|
||||
|
||||
export function log(options: ScaffoldConfig, ...obj: any[]) {
|
||||
if (options.quiet) {
|
||||
return
|
||||
}
|
||||
console["log"](...obj)
|
||||
}
|
||||
|
||||
export async function createDirIfNotExists(dir: string, options: ScaffoldConfig): Promise<void> {
|
||||
const parentDir = path.dirname(dir)
|
||||
|
||||
if (!(await pathExists(parentDir))) {
|
||||
await createDirIfNotExists(parentDir, options)
|
||||
}
|
||||
|
||||
if (!(await pathExists(dir))) {
|
||||
try {
|
||||
await mkdir(dir)
|
||||
return
|
||||
} catch (e: any) {
|
||||
if (e.code !== "EEXIST") {
|
||||
throw e
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getOptionValueForFile<T>(
|
||||
filePath: string,
|
||||
data: Record<string, string>,
|
||||
fn: FileResponse<T>,
|
||||
defaultValue?: T
|
||||
): T {
|
||||
if (typeof fn !== "function") {
|
||||
return defaultValue ?? (fn as T)
|
||||
}
|
||||
return (fn as FileResponseFn<T>)(
|
||||
filePath,
|
||||
path.dirname(handlebarsParse(filePath, data)),
|
||||
path.basename(handlebarsParse(filePath, data))
|
||||
)
|
||||
}
|
||||
|
||||
export function handlebarsParse(templateBuffer: Buffer | string, data: Record<string, string>) {
|
||||
const parser = Handlebars.compile(templateBuffer.toString(), { noEscape: true })
|
||||
const outputContents = parser(data)
|
||||
return outputContents
|
||||
}
|
||||
|
||||
export async function pathExists(filePath: string): Promise<boolean> {
|
||||
try {
|
||||
await access(filePath, F_OK)
|
||||
return true
|
||||
} catch (e: any) {
|
||||
if (e.code === "ENOENT") {
|
||||
return false
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
export function pascalCase(s: string): string {
|
||||
return startCase(s).replace(/\s+/g, "")
|
||||
}
|
||||
|
||||
export async function isDir(path: string): Promise<boolean> {
|
||||
const tplStat = await stat(path)
|
||||
return tplStat.isDirectory()
|
||||
}
|
||||
183
tests/scaffold.test.ts
Normal file
183
tests/scaffold.test.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
import mockFs from "mock-fs"
|
||||
import FileSystem from "mock-fs/lib/filesystem"
|
||||
import Scaffold from "../src/scaffold"
|
||||
import { readdirSync, readFileSync } from "fs"
|
||||
|
||||
const fileStructNormal = {
|
||||
input: {
|
||||
"{{name}}.txt": "Hello, my app is {{name}}",
|
||||
},
|
||||
output: {},
|
||||
}
|
||||
|
||||
const fileStructWithData = {
|
||||
input: {
|
||||
"{{name}}.txt": "Hello, my value is {{value}}",
|
||||
},
|
||||
output: {},
|
||||
}
|
||||
|
||||
const fileStructNested = {
|
||||
input: {
|
||||
"{{name}}-1.text": "This should be in root",
|
||||
"{{Name}}": {
|
||||
"{{name}}-2.txt": "Hello, my value is {{value}}",
|
||||
},
|
||||
},
|
||||
output: {},
|
||||
}
|
||||
|
||||
function withMock(fileStruct: FileSystem.DirectoryItems, testFn: jest.EmptyFunction): jest.EmptyFunction {
|
||||
return () => {
|
||||
beforeEach(() => {
|
||||
mockFs(fileStruct)
|
||||
})
|
||||
testFn()
|
||||
afterEach(() => {
|
||||
mockFs.restore()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
describe("Scaffold", () => {
|
||||
describe(
|
||||
"create subfolder",
|
||||
withMock(fileStructNormal, () => {
|
||||
test("should not create by default", async () => {
|
||||
await Scaffold({
|
||||
name: "app_name",
|
||||
output: "output",
|
||||
templates: ["input"],
|
||||
quiet: true,
|
||||
})
|
||||
|
||||
const data = readFileSync(process.cwd() + "/output/app_name.txt")
|
||||
expect(data.toString()).toBe("Hello, my app is app_name")
|
||||
})
|
||||
|
||||
test("should create with config", async () => {
|
||||
await Scaffold({
|
||||
name: "app_name",
|
||||
output: "output",
|
||||
templates: ["input"],
|
||||
createSubFolder: true,
|
||||
quiet: true,
|
||||
})
|
||||
|
||||
const data = readFileSync(process.cwd() + "/output/app_name/app_name.txt")
|
||||
expect(data.toString()).toBe("Hello, my app is app_name")
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
describe(
|
||||
"overwrite",
|
||||
withMock(fileStructWithData, () => {
|
||||
test("should not overwrite by default", async () => {
|
||||
await Scaffold({
|
||||
name: "app_name",
|
||||
output: "output",
|
||||
templates: ["input"],
|
||||
data: { value: "1" },
|
||||
quiet: true,
|
||||
})
|
||||
|
||||
await Scaffold({
|
||||
name: "app_name",
|
||||
output: "output",
|
||||
templates: ["input"],
|
||||
data: { value: "2" },
|
||||
quiet: true,
|
||||
})
|
||||
|
||||
const data = readFileSync(process.cwd() + "/output/app_name.txt")
|
||||
expect(data.toString()).toBe("Hello, my value is 1")
|
||||
})
|
||||
|
||||
test("should overwrite with config", async () => {
|
||||
await Scaffold({
|
||||
name: "app_name",
|
||||
output: "output",
|
||||
templates: ["input"],
|
||||
data: { value: "1" },
|
||||
quiet: true,
|
||||
})
|
||||
|
||||
await Scaffold({
|
||||
name: "app_name",
|
||||
output: "output",
|
||||
templates: ["input"],
|
||||
data: { value: "2" },
|
||||
overwrite: true,
|
||||
quiet: true,
|
||||
})
|
||||
|
||||
const data = readFileSync(process.cwd() + "/output/app_name.txt")
|
||||
expect(data.toString()).toBe("Hello, my value is 2")
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
describe(
|
||||
"errors",
|
||||
withMock(fileStructNormal, () => {
|
||||
let consoleMock: jest.SpyInstance
|
||||
beforeAll(() => {
|
||||
consoleMock = jest.spyOn(console, "error").mockImplementation(() => void 0)
|
||||
})
|
||||
|
||||
test("should throw for bad input", async () => {
|
||||
await expect(
|
||||
Scaffold({
|
||||
name: "app_name",
|
||||
output: "output",
|
||||
templates: ["non-existing-input"],
|
||||
data: { value: "1" },
|
||||
quiet: true,
|
||||
})
|
||||
).rejects.toThrow()
|
||||
|
||||
expect(() => readFileSync(process.cwd() + "/output/app_name.txt")).toThrow()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
consoleMock.mockRestore()
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
describe(
|
||||
"outputPath override",
|
||||
withMock(fileStructNormal, () => {
|
||||
test("should allow override function", async () => {
|
||||
await Scaffold({
|
||||
name: "app_name",
|
||||
output: (fullPath, basedir, basename) => `custom-output/${basename.split(".")[0]}`,
|
||||
templates: ["input"],
|
||||
data: { value: "1" },
|
||||
quiet: true,
|
||||
})
|
||||
const data = readFileSync(process.cwd() + "/custom-output/app_name/app_name.txt")
|
||||
expect(data.toString()).toBe("Hello, my app is app_name")
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
describe(
|
||||
"output structure",
|
||||
withMock(fileStructNested, () => {
|
||||
test("should maintain input structure on output", async () => {
|
||||
await Scaffold({
|
||||
name: "app_name",
|
||||
output: "./",
|
||||
templates: ["input"],
|
||||
data: { value: "1" },
|
||||
quiet: true,
|
||||
})
|
||||
|
||||
const dir = readdirSync(process.cwd())
|
||||
expect(dir).toHaveProperty("length")
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
@@ -1,13 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"module": "es2015",
|
||||
"target": "ES2019",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"lib": [
|
||||
"ES2019",
|
||||
],
|
||||
"declaration": true,
|
||||
"outDir": "./dist",
|
||||
"outDir": "dist",
|
||||
"strict": true,
|
||||
"sourceMap": true
|
||||
"sourceMap": true,
|
||||
"removeComments": false,
|
||||
},
|
||||
"include": [
|
||||
"src/index.ts",
|
||||
"src/cmd.ts",
|
||||
],
|
||||
"exclude": [
|
||||
"examples"
|
||||
"tests/*"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
const path = require('path')
|
||||
|
||||
module.exports = {
|
||||
target: 'node',
|
||||
entry: './scaffold.ts',
|
||||
output: {
|
||||
filename: 'scaffold.js',
|
||||
path: path.resolve(__dirname, 'dist')
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.ts']
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
loader: 'ts-loader',
|
||||
exclude: ['./examples']
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user