mirror of
https://github.com/chenasraf/simple-scaffold.git
synced 2026-05-18 01:29:09 +00:00
Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -57,4 +57,5 @@ typings/
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
|
||||
examples/test-output
|
||||
examples/test-output/**/*
|
||||
!examples/test-output/.gitkeep
|
||||
|
||||
3
.prettierrc
Normal file
3
.prettierrc
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"semi": false
|
||||
}
|
||||
5
.vscode/settings.json
vendored
5
.vscode/settings.json
vendored
@@ -1,3 +1,4 @@
|
||||
{
|
||||
"typescript.tsdk": "./node_modules/typescript/lib"
|
||||
}
|
||||
"typescript.tsdk": "./node_modules/typescript/lib",
|
||||
"npm.packageManager": "yarn"
|
||||
}
|
||||
52
.vscode/tasks.json
vendored
52
.vscode/tasks.json
vendored
@@ -1,7 +1,47 @@
|
||||
{
|
||||
"version": "0.1.0",
|
||||
"command": "webpack",
|
||||
"isShellCommand": true,
|
||||
"args": [],
|
||||
"showOutput": "always"
|
||||
}
|
||||
"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": [],
|
||||
},
|
||||
{
|
||||
"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": [],
|
||||
},
|
||||
],
|
||||
}
|
||||
169
README.md
169
README.md
@@ -1,47 +1,158 @@
|
||||
# scaffolder
|
||||
Scaffolder allows you to create your structured files based on templates.
|
||||
# simple-scaffold
|
||||
|
||||
Simple Scaffold allows you to create your structured files based on templates.
|
||||
|
||||
## Install
|
||||
You can either use it as a command line tool or import into your own code and run from there.
|
||||
|
||||
You can install simple-scaffold globally like so:
|
||||
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
|
||||
npm install [-g] simple-scaffold
|
||||
# yarn
|
||||
yarn global add simple-scaffold
|
||||
yarn [global] add simple-scaffold
|
||||
```
|
||||
|
||||
## Use as a command line tool
|
||||
#### Command line options
|
||||
|
||||
### Command Line Options
|
||||
|
||||
```plaintext
|
||||
Scaffold Generator
|
||||
|
||||
Generate scaffolds for your project based on file templates.
|
||||
Usage: simple-scaffold scaffold-name [options]
|
||||
|
||||
Options
|
||||
|
||||
-n, --name string Component output name
|
||||
-t, --templates File[] A glob pattern of template files to load.
|
||||
A template file may be of any type and extension, and supports Handlebars as
|
||||
a parsing engine for the file names and contents, so you may customize both
|
||||
with variables from your configuration.
|
||||
-o, --output File The output directory to put the new files in. They will attempt to maintain
|
||||
their regular structure as they are found, if possible.
|
||||
-l, --locals Key=Value A key-value map for the template to use in parsing.
|
||||
-w, --overwrite Boolean Whether to overwrite files when they are found to already exist. default=true
|
||||
-S, --create-sub-folder Boolean Whether to create a subdirectory with {{Name}} in the output directory.
|
||||
default=true
|
||||
-h, --help Display this help message
|
||||
```
|
||||
|
||||
You can add this as a script in your `package.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"scaffold": "yarn simple-scaffold --template scaffolds/component/**/* --output src/components --locals myProp=\"propname\",myVal=123"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Scaffolding
|
||||
|
||||
Scaffolding will replace {{vars}} in both the file name and its contents and put the transformed files
|
||||
in `<output>/<{{Name}}>`, as per the Handlebars formatting rules.
|
||||
|
||||
Your context will be pre-populated with the following:
|
||||
|
||||
- `{{Name}}`: CapitalizedName of the component
|
||||
- `{{name}}`: camelCasedName of the component
|
||||
|
||||
Any `locals` you add in the config will populate with their names wrapped in `{{` and `}}`.
|
||||
They are all stringified, so be sure to parse them accordingly by creating a script, if necessary.
|
||||
|
||||
### 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 = (filename, basePath) => [basePath, filename].join(path.sep)
|
||||
```
|
||||
|
||||
## Example Scaffold Input
|
||||
|
||||
### Input Directory structure
|
||||
|
||||
```
|
||||
- project
|
||||
- scaffold
|
||||
- {{Name}}.js
|
||||
- src
|
||||
- components
|
||||
- ...
|
||||
```
|
||||
|
||||
#### project/scaffold/{{Name}}.js
|
||||
|
||||
```js
|
||||
const React = require('react')
|
||||
|
||||
module.exports = class {{Name}} extends React.Component {
|
||||
render() {
|
||||
<div className="{{className}}">{{Name}} Component</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Run Example
|
||||
|
||||
```bash
|
||||
simple-scaffold MyComponent --template scaffolds/component \
|
||||
--output src/components \
|
||||
--locals myProp="propname",myVal=123
|
||||
simple-scaffold MyComponent \
|
||||
-t project/scaffold/**/* \
|
||||
-o src/components \
|
||||
-l className=my-component
|
||||
```
|
||||
|
||||
##### `--template`
|
||||
A glob pattern of template files to load.
|
||||
## Example Scaffold Output
|
||||
|
||||
|
||||
A template file may be of any type and extension, and supports [Handlebars](https://handlebarsjs.com) as a parsing engine for the file names and contents, so you may customize both with variables from your configuration.
|
||||
|
||||
You may load more than one template list by simple adding more `--template` arguments.
|
||||
|
||||
##### `--output`
|
||||
The output directory to put the new files in. They will attempt to maintain their regular structure as they are found, if possible.
|
||||
|
||||
Your new scaffold will be placed under a directory with the scaffold name from the argumemts.
|
||||
|
||||
You may also pass a function to transform the output path for each file individually.
|
||||
This function takes 2 arguments: filename, and base glob path
|
||||
|
||||
##### `--locals`
|
||||
You may set local variables to be pushed into the template and replaced.
|
||||
The format for the value of this argument is:
|
||||
#### Directory structure
|
||||
|
||||
```
|
||||
property=value[,property=value[,...]]
|
||||
- project
|
||||
- src
|
||||
- components
|
||||
- MyComponent
|
||||
- MyComponent.js
|
||||
- ...
|
||||
```
|
||||
|
||||
With `createSubfolder = false`:
|
||||
|
||||
```
|
||||
- project
|
||||
- src
|
||||
- components
|
||||
- MyComponent.js
|
||||
- ...
|
||||
```
|
||||
|
||||
#### 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>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
192
cmd.ts
192
cmd.ts
@@ -1,86 +1,112 @@
|
||||
import SimpleScaffold from './scaffold'
|
||||
import * as fs from 'fs'
|
||||
import IScaffold from './index'
|
||||
import SimpleScaffold from "./scaffold"
|
||||
import * as fs from "fs"
|
||||
import { IScaffold } from "./index"
|
||||
import * as cliArgs from "command-line-args"
|
||||
import * as cliUsage from "command-line-usage"
|
||||
import * as path from "path"
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
|
||||
class ScaffoldCmd {
|
||||
private config: IScaffold.IConfig
|
||||
|
||||
constructor() {
|
||||
this.config = this.getOptionsFromArgs()
|
||||
}
|
||||
|
||||
private getOptionsFromArgs(): IScaffold.IConfig {
|
||||
let skipNext = false
|
||||
const options = {} as any
|
||||
|
||||
args.forEach((arg, i) => {
|
||||
if (skipNext) {
|
||||
skipNext = false
|
||||
return
|
||||
}
|
||||
|
||||
if (arg.slice(0, 2) == '--') {
|
||||
skipNext = true
|
||||
let value: string
|
||||
|
||||
if (arg.indexOf('=') >= 0) {
|
||||
value = arg.split('=').slice(1).join('')
|
||||
} else if (args.length >= i + 1 && args[i + 1] && args[i + 1].slice(0, 2) !== '--') {
|
||||
value = args[i + 1]
|
||||
} else {
|
||||
value = 'true'
|
||||
}
|
||||
|
||||
const argName = arg.slice(2)
|
||||
options[argName] = this.getArgValue(argName, value, options)
|
||||
} else {
|
||||
if (!options.name) {
|
||||
options.name = arg
|
||||
} else {
|
||||
throw new TypeError(`Invalid argument: ${arg}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (!['name', 'templates', 'output'].every(o => options[o] !== undefined)) {
|
||||
throw new Error(`Config is missing keys: ${JSON.stringify(options)}`)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
private getArgValue(arg: string, value: string, options: IScaffold.IConfig) {
|
||||
switch (arg) {
|
||||
case 'templates':
|
||||
return (options.templates || []).concat([value])
|
||||
case 'output':
|
||||
return value
|
||||
case 'locals':
|
||||
const split = value.split(',')
|
||||
const locals = options.locals || {}
|
||||
for (const item of split) {
|
||||
const [k, v] = item.split('=')
|
||||
locals[k] = v
|
||||
}
|
||||
return locals
|
||||
default:
|
||||
throw TypeError(`arguments invalid for config: arg=\`${arg}\`, value=\`${value}\``)
|
||||
}
|
||||
}
|
||||
|
||||
public run() {
|
||||
const config: IScaffold.IConfig = this.config
|
||||
console.info('Config:', config)
|
||||
|
||||
const scf = new SimpleScaffold({
|
||||
name: config.name,
|
||||
templates: config.templates,
|
||||
output: config.output,
|
||||
locals: config.locals,
|
||||
}).run()
|
||||
}
|
||||
type Def = cliArgs.OptionDefinition & {
|
||||
description?: string
|
||||
typeLabel?: string
|
||||
}
|
||||
|
||||
new ScaffoldCmd().run()
|
||||
function localsParser(content: string) {
|
||||
return JSON.parse(content)
|
||||
}
|
||||
|
||||
function filePathParser(content: string) {
|
||||
if (content.startsWith("/")) {
|
||||
return content
|
||||
}
|
||||
return [process.cwd(), content].join(path.sep)
|
||||
}
|
||||
|
||||
function booleanParser(text: string) {
|
||||
return text && text.trim().length
|
||||
? ["true", "1", "on"].includes(text.trim())
|
||||
: true
|
||||
}
|
||||
|
||||
const defs: Def[] = [
|
||||
{
|
||||
name: "name",
|
||||
alias: "n",
|
||||
type: String,
|
||||
description: "Component output name",
|
||||
defaultOption: true,
|
||||
},
|
||||
{
|
||||
name: "templates",
|
||||
alias: "t",
|
||||
type: filePathParser,
|
||||
typeLabel: "{underline File}[]",
|
||||
description: `A glob pattern of template files to load.\nA template file may be of any type and extension, and supports Handlebars as a parsing engine for the file names and contents, so you may customize both with variables from your configuration.`,
|
||||
multiple: true,
|
||||
},
|
||||
{
|
||||
name: "output",
|
||||
alias: "o",
|
||||
type: filePathParser,
|
||||
typeLabel: "{underline File}",
|
||||
description: `The output directory to put the new files in. They will attempt to maintain their regular structure as they are found, if possible.`,
|
||||
},
|
||||
{
|
||||
name: "locals",
|
||||
alias: "l",
|
||||
description: `A JSON string for the template to use in parsing.`,
|
||||
typeLabel: "{underline JSON string}",
|
||||
type: localsParser,
|
||||
},
|
||||
{
|
||||
name: "overwrite",
|
||||
alias: "w",
|
||||
description: `Whether to overwrite files when they are found to already exist. {bold default=true}`,
|
||||
type: booleanParser,
|
||||
typeLabel: "{underline Boolean}",
|
||||
defaultValue: true,
|
||||
},
|
||||
{
|
||||
name: "create-sub-folder",
|
||||
alias: "S",
|
||||
typeLabel: "{underline Boolean}",
|
||||
description:
|
||||
"Whether to create a subdirectory with \\{\\{Name\\}\\} in the {underline output} directory. {bold default=true}",
|
||||
type: booleanParser,
|
||||
defaultValue: true,
|
||||
},
|
||||
{
|
||||
name: "help",
|
||||
alias: "h",
|
||||
type: Boolean,
|
||||
description: "Display this help message",
|
||||
},
|
||||
]
|
||||
|
||||
const args = cliArgs(defs, { camelCase: true })
|
||||
|
||||
const help = [
|
||||
{
|
||||
header: "Scaffold Generator",
|
||||
content: `Generate scaffolds for your project based on file templates.\nUsage: {bold simple-scaffold} {underline scaffold-name} {underline [options]}`,
|
||||
},
|
||||
{ header: "Options", optionList: defs },
|
||||
]
|
||||
|
||||
if (args.createSubFolder === null) {
|
||||
args.createSubFolder = true
|
||||
}
|
||||
|
||||
if (args.help || !args.name) {
|
||||
console.log(cliUsage(help))
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
console.info("Config:", args)
|
||||
new SimpleScaffold({
|
||||
name: args.name,
|
||||
templates: args.templates,
|
||||
output: args.output,
|
||||
locals: args.locals,
|
||||
createSubfolder: args.createSubFolder,
|
||||
overwrite: args.overwrite,
|
||||
}).run()
|
||||
|
||||
1
dist/cmd.d.ts
vendored
Executable file
1
dist/cmd.d.ts
vendored
Executable file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
2
dist/cmd.js
vendored
2
dist/cmd.js
vendored
File diff suppressed because one or more lines are too long
2
dist/cmd.js.map
vendored
2
dist/cmd.js.map
vendored
File diff suppressed because one or more lines are too long
13
dist/dist/scaffold.d.ts
vendored
13
dist/dist/scaffold.d.ts
vendored
@@ -1,13 +0,0 @@
|
||||
import IScaffold from './index';
|
||||
declare class SimpleScaffold {
|
||||
private config;
|
||||
private locals;
|
||||
constructor(config: IScaffold.IConfig);
|
||||
private parseLocals(text);
|
||||
private fileList(input);
|
||||
private getFileContents(filePath);
|
||||
private getOutputPath(file, basePath);
|
||||
private writeFile(filePath, fileContents);
|
||||
run(): void;
|
||||
}
|
||||
export default SimpleScaffold;
|
||||
29
dist/index.d.ts
vendored
Executable file
29
dist/index.d.ts
vendored
Executable file
@@ -0,0 +1,29 @@
|
||||
declare namespace IScaffold {
|
||||
class SimpleScaffold {
|
||||
constructor(config: Config)
|
||||
run(): void
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
name?: string
|
||||
templates: string[]
|
||||
output:
|
||||
| string
|
||||
| ((fullPath: string, basedir: string, basename: string) => string)
|
||||
locals?: Locals
|
||||
createSubfolder?: boolean
|
||||
overwrite?: boolean | ((path: string) => boolean)
|
||||
}
|
||||
|
||||
export interface Locals {
|
||||
[k: string]: string
|
||||
}
|
||||
|
||||
export interface FileRepr {
|
||||
base: string
|
||||
file: string
|
||||
}
|
||||
}
|
||||
|
||||
export default IScaffold.SimpleScaffold
|
||||
export { IScaffold }
|
||||
2
dist/index.js
vendored
Executable file
2
dist/index.js
vendored
Executable file
@@ -0,0 +1,2 @@
|
||||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.library=e():t.library=e()}(global,(function(){return(()=>{"use strict";var t={493:function(t,e,o){var i=this&&this.__assign||function(){return(i=Object.assign||function(t){for(var e,o=1,i=arguments.length;o<i;o++)for(var r in e=arguments[o])Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}).apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var r=o(747),n=o(622),s=o(878),c=o(778),a=function(){function t(t){this.locals={};var e={name:"scaffold",templates:[],output:process.cwd(),createSubfolder:!0,overwrite:!0};this.config=i(i({},e),t);var o={Name:this.config.name[0].toUpperCase()+this.config.name.slice(1),name:this.config.name[0].toLowerCase()+this.config.name.slice(1)};this.locals=i(i({},o),t.locals)}return t.prototype.parseLocals=function(t){try{return c.compile(t,{noEscape:!0})(this.locals)}catch(e){return console.warn("Problem using Handlebars, returning unmodified content"),t}},t.prototype.fileList=function(t){for(var e=[],o=0,i=t;o<i.length;o++){var r=i[o],c=s.sync(r,{dot:!0}).map((function(t){return"/"==t[0]?t:n.join(process.cwd(),t)})),a=r.indexOf("*"),l=r;a>=0&&(l=r.slice(0,a-1));for(var f=0,u=c;f<u.length;f++){var p=u[f];e.push({base:l,file:p})}}return e},t.prototype.getFileContents=function(t){return console.log(r.readFileSync(t)),r.readFileSync(t).toString()},t.prototype.getOutputPath=function(t,e){var o;if("function"==typeof this.config.output)o=this.config.output(t,e,n.basename(t));else{var i=this.config.output+(this.config.createSubfolder?"/"+this.config.name+"/":"/"),r=t.indexOf(e),s=t;r>=0&&(s=t!==e?t.slice(r+e.length+1):n.basename(t)),o=i+s}return this.parseLocals(o)},t.prototype.writeFile=function(t,e){var o=n.dirname(t);this.writeDirectory(o,t),r.writeFile(t,e,{encoding:"utf-8"},(function(t){if(t)throw t}))},t.prototype.shouldWriteFile=function(t){var e,o,i="boolean"==typeof this.config.overwrite?this.config.overwrite:null===(o=(e=this.config).overwrite)||void 0===o?void 0:o.call(e,t);return!r.existsSync(t)||!1!==i},t.prototype.run=function(){console.log("Generating scaffold: "+this.config.name+"...");var t,e=this.fileList(this.config.templates),o=0;console.log("Template files:",e);for(var i=0,n=e;i<n.length;i++){t=n[i];var s=void 0,c=void 0,a=void 0,l=void 0,f=void 0;try{if(o++,l=t.file,f=t.base,s=this.getOutputPath(l,f),r.lstatSync(l).isDirectory()){this.writeDirectory(s,l);continue}c=this.getFileContents(l),a=this.parseLocals(c),this.shouldWriteFile(s)?(console.info("Writing:",{file:l,base:f,outputPath:s,outputContents:a.replace("\n","\\n")}),this.writeFile(s,a)):console.log("Skipping file "+s)}catch(t){throw console.error("Error while processing file:",{file:l,base:f,contents:c,outputPath:s,outputContents:a}),t}}if(!o)throw new Error("No files to scaffold!");console.log("Done")},t.prototype.writeDirectory=function(t,e){var o=n.dirname(t);r.existsSync(o)||this.writeDirectory(o,t),r.existsSync(t)||(console.info("Creating directory:",{file:e,outputPath:t}),r.mkdirSync(t))},t}();e.default=a},747:t=>{t.exports=require("fs")},878:t=>{t.exports=require("glob")},778:t=>{t.exports=require("handlebars")},622:t=>{t.exports=require("path")}},e={};return function o(i){if(e[i])return e[i].exports;var r=e[i]={exports:{}};return t[i].call(r.exports,r,r.exports,o),r.exports}(493)})()}));
|
||||
//# sourceMappingURL=index.js.map
|
||||
1
dist/index.js.map
vendored
Executable file
1
dist/index.js.map
vendored
Executable file
File diff suppressed because one or more lines are too long
15
dist/scaffold.d.ts
vendored
Executable file
15
dist/scaffold.d.ts
vendored
Executable file
@@ -0,0 +1,15 @@
|
||||
import { IScaffold } from "./index.d";
|
||||
declare class SimpleScaffold {
|
||||
config: IScaffold.Config;
|
||||
locals: IScaffold.Config["locals"];
|
||||
constructor(config: IScaffold.Config);
|
||||
private parseLocals;
|
||||
private fileList;
|
||||
private getFileContents;
|
||||
private getOutputPath;
|
||||
private writeFile;
|
||||
private shouldWriteFile;
|
||||
run(): void;
|
||||
private writeDirectory;
|
||||
}
|
||||
export default SimpleScaffold;
|
||||
2
dist/scaffold.js
vendored
2
dist/scaffold.js
vendored
@@ -1,2 +0,0 @@
|
||||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.library=t():e.library=t()}(this,function(){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:o})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=1)}([function(e,t){e.exports=require("path")},function(e,t,n){"use strict";var o=this&&this.__generator||function(e,t){function n(e){return function(t){return o([e,t])}}function o(n){if(r)throw new TypeError("Generator is already executing.");for(;c;)try{if(r=1,i&&(s=i[2&n[0]?"return":n[0]?"throw":"next"])&&!(s=s.call(i,n[1])).done)return s;switch(i=0,s&&(n=[0,s.value]),n[0]){case 0:case 1:s=n;break;case 4:return c.label++,{value:n[1],done:!1};case 5:c.label++,i=n[1],n=[0];continue;case 7:n=c.ops.pop(),c.trys.pop();continue;default:if(s=c.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){c=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){c.label=n[1];break}if(6===n[0]&&c.label<s[1]){c.label=s[1],s=n;break}if(s&&c.label<s[2]){c.label=s[2],c.ops.push(n);break}s[2]&&c.ops.pop(),c.trys.pop();continue}n=t.call(e,c)}catch(e){n=[6,e],i=0}finally{r=s=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}var r,i,s,a,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a};Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),i=n(0),s=n(3),a=n(4),c=function(){function e(e){this.locals={};var t={name:"scaffold",templates:[],output:process.cwd()};this.config=Object.assign({},t,e);var n={Name:this.config.name[0].toUpperCase()+this.config.name.slice(1),name:this.config.name[0].toLowerCase()+this.config.name.slice(1)};this.locals=Object.assign({},n,e.locals)}return e.prototype.parseLocals=function(e){return a.compile(e,{noEscape:!0})(this.locals)},e.prototype.fileList=function(e){var t,n,r,a,c,u,l,f,p;return o(this,function(o){switch(o.label){case 0:t=0,n=e,o.label=1;case 1:if(!(t<n.length))return[3,6];r=n[t],a=s.sync(r).map(function(e){return"/"==e[0]?e:i.join(process.cwd(),e)}),c=r.indexOf("*"),u=r,c>=0&&(u=r.slice(0,c-1)),l=0,f=a,o.label=2;case 2:return l<f.length?(p=f[l],[4,{base:u,file:p}]):[3,5];case 3:o.sent(),o.label=4;case 4:return l++,[3,2];case 5:return t++,[3,1];case 6:return[2]}})},e.prototype.getFileContents=function(e){return r.readFileSync(e).toString()},e.prototype.getOutputPath=function(e,t){var n;if("function"==typeof this.config.output)n=this.config.output(e,t);else{var o=this.config.output+"/"+this.config.name+"/",r=e.indexOf(t),i=e;r>=0&&(i=e.slice(r+t.length+1)),n=o+i}return this.parseLocals(n)},e.prototype.writeFile=function(e,t){r.existsSync(i.dirname(e))||r.mkdirSync(i.dirname(e)),console.info("Writing file:",e),r.writeFileSync(e,t,{encoding:"utf-8"})},e.prototype.run=function(){console.log("Generating scaffold: "+this.config.name+"...");for(var e,t=this.fileList(this.config.templates),n=0;e=t.next().value;){n++;var o=e.file,r=e.base,i=this.getOutputPath(o,r),s=this.getFileContents(o),a=this.parseLocals(s);this.writeFile(i,a),console.info("Parsing:",{file:o,base:r,outputPath:i,outputContents:a.replace("\n","\\n")})}if(!n)throw new Error("No files to scaffold!");console.log("Done")},e}();t.default=c},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("glob")},function(e,t){e.exports=require("handlebars")}])});
|
||||
//# sourceMappingURL=scaffold.js.map
|
||||
1
dist/scaffold.js.map
vendored
1
dist/scaffold.js.map
vendored
File diff suppressed because one or more lines are too long
1
dist/test.d.ts
vendored
Executable file
1
dist/test.d.ts
vendored
Executable file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
2
dist/test.js
vendored
2
dist/test.js
vendored
@@ -1,2 +1,2 @@
|
||||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.library=t():e.library=t()}(this,function(){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:o})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=5)}([function(e,t){e.exports=require("path")},function(e,t,n){"use strict";var o=this&&this.__generator||function(e,t){function n(e){return function(t){return o([e,t])}}function o(n){if(r)throw new TypeError("Generator is already executing.");for(;u;)try{if(r=1,i&&(s=i[2&n[0]?"return":n[0]?"throw":"next"])&&!(s=s.call(i,n[1])).done)return s;switch(i=0,s&&(n=[0,s.value]),n[0]){case 0:case 1:s=n;break;case 4:return u.label++,{value:n[1],done:!1};case 5:u.label++,i=n[1],n=[0];continue;case 7:n=u.ops.pop(),u.trys.pop();continue;default:if(s=u.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){u=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){u.label=n[1];break}if(6===n[0]&&u.label<s[1]){u.label=s[1],s=n;break}if(s&&u.label<s[2]){u.label=s[2],u.ops.push(n);break}s[2]&&u.ops.pop(),u.trys.pop();continue}n=t.call(e,u)}catch(e){n=[6,e],i=0}finally{r=s=0}if(5&n[0])throw n[1];return{value:n[0]?n[1]:void 0,done:!0}}var r,i,s,a,u={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a};Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),i=n(0),s=n(3),a=n(4),u=function(){function e(e){this.locals={};var t={name:"scaffold",templates:[],output:process.cwd()};this.config=Object.assign({},t,e);var n={Name:this.config.name[0].toUpperCase()+this.config.name.slice(1),name:this.config.name[0].toLowerCase()+this.config.name.slice(1)};this.locals=Object.assign({},n,e.locals)}return e.prototype.parseLocals=function(e){return a.compile(e,{noEscape:!0})(this.locals)},e.prototype.fileList=function(e){var t,n,r,a,u,c,l,f,p;return o(this,function(o){switch(o.label){case 0:t=0,n=e,o.label=1;case 1:if(!(t<n.length))return[3,6];r=n[t],a=s.sync(r).map(function(e){return"/"==e[0]?e:i.join(process.cwd(),e)}),u=r.indexOf("*"),c=r,u>=0&&(c=r.slice(0,u-1)),l=0,f=a,o.label=2;case 2:return l<f.length?(p=f[l],[4,{base:c,file:p}]):[3,5];case 3:o.sent(),o.label=4;case 4:return l++,[3,2];case 5:return t++,[3,1];case 6:return[2]}})},e.prototype.getFileContents=function(e){return r.readFileSync(e).toString()},e.prototype.getOutputPath=function(e,t){var n;if("function"==typeof this.config.output)n=this.config.output(e,t);else{var o=this.config.output+"/"+this.config.name+"/",r=e.indexOf(t),i=e;r>=0&&(i=e.slice(r+t.length+1)),n=o+i}return this.parseLocals(n)},e.prototype.writeFile=function(e,t){r.existsSync(i.dirname(e))||r.mkdirSync(i.dirname(e)),console.info("Writing file:",e),r.writeFileSync(e,t,{encoding:"utf-8"})},e.prototype.run=function(){console.log("Generating scaffold: "+this.config.name+"...");for(var e,t=this.fileList(this.config.templates),n=0;e=t.next().value;){n++;var o=e.file,r=e.base,i=this.getOutputPath(o,r),s=this.getFileContents(o),a=this.parseLocals(s);this.writeFile(i,a),console.info("Parsing:",{file:o,base:r,outputPath:i,outputContents:a.replace("\n","\\n")})}if(!n)throw new Error("No files to scaffold!");console.log("Done")},e}();t.default=u},function(e,t){e.exports=require("fs")},function(e,t){e.exports=require("glob")},function(e,t){e.exports=require("handlebars")},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),r=n(0),i=r.join(process.cwd(),"examples");new o.default({templates:[i+"/test-input/Component/**/*"],output:i+"/test-output",locals:{property:"myProp",value:'"value"'}}).run()}])});
|
||||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.library=t():e.library=t()}(global,(function(){return(()=>{"use strict";var e={493:function(e,t,o){var r=this&&this.__assign||function(){return(r=Object.assign||function(e){for(var t,o=1,r=arguments.length;o<r;o++)for(var n in t=arguments[o])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0});var n=o(747),i=o(622),s=o(878),a=o(778),l=function(){function e(e){this.locals={};var t={name:"scaffold",templates:[],output:process.cwd(),createSubfolder:!0,overwrite:!0};this.config=r(r({},t),e);var o={Name:this.config.name[0].toUpperCase()+this.config.name.slice(1),name:this.config.name[0].toLowerCase()+this.config.name.slice(1)};this.locals=r(r({},o),e.locals)}return e.prototype.parseLocals=function(e){try{return a.compile(e,{noEscape:!0})(this.locals)}catch(t){return console.warn("Problem using Handlebars, returning unmodified content"),e}},e.prototype.fileList=function(e){for(var t=[],o=0,r=e;o<r.length;o++){var n=r[o],a=s.sync(n,{dot:!0}).map((function(e){return"/"==e[0]?e:i.join(process.cwd(),e)})),l=n.indexOf("*"),c=n;l>=0&&(c=n.slice(0,l-1));for(var u=0,p=a;u<p.length;u++){var f=p[u];t.push({base:c,file:f})}}return t},e.prototype.getFileContents=function(e){return console.log(n.readFileSync(e)),n.readFileSync(e).toString()},e.prototype.getOutputPath=function(e,t){var o;if("function"==typeof this.config.output)o=this.config.output(e,t,i.basename(e));else{var r=this.config.output+(this.config.createSubfolder?"/"+this.config.name+"/":"/"),n=e.indexOf(t),s=e;n>=0&&(s=e!==t?e.slice(n+t.length+1):i.basename(e)),o=r+s}return this.parseLocals(o)},e.prototype.writeFile=function(e,t){var o=i.dirname(e);this.writeDirectory(o,e),n.writeFile(e,t,{encoding:"utf-8"},(function(e){if(e)throw e}))},e.prototype.shouldWriteFile=function(e){var t,o,r="boolean"==typeof this.config.overwrite?this.config.overwrite:null===(o=(t=this.config).overwrite)||void 0===o?void 0:o.call(t,e);return!n.existsSync(e)||!1!==r},e.prototype.run=function(){console.log("Generating scaffold: "+this.config.name+"...");var e,t=this.fileList(this.config.templates),o=0;console.log("Template files:",t);for(var r=0,i=t;r<i.length;r++){e=i[r];var s=void 0,a=void 0,l=void 0,c=void 0,u=void 0;try{if(o++,c=e.file,u=e.base,s=this.getOutputPath(c,u),n.lstatSync(c).isDirectory()){this.writeDirectory(s,c);continue}a=this.getFileContents(c),l=this.parseLocals(a),this.shouldWriteFile(s)?(console.info("Writing:",{file:c,base:u,outputPath:s,outputContents:l.replace("\n","\\n")}),this.writeFile(s,l)):console.log("Skipping file "+s)}catch(e){throw console.error("Error while processing file:",{file:c,base:u,contents:a,outputPath:s,outputContents:l}),e}}if(!o)throw new Error("No files to scaffold!");console.log("Done")},e.prototype.writeDirectory=function(e,t){var o=i.dirname(e);n.existsSync(o)||this.writeDirectory(o,e),n.existsSync(e)||(console.info("Creating directory:",{file:t,outputPath:e}),n.mkdirSync(e))},e}();t.default=l},743:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0});var r=o(493),n=o(622).join(process.cwd(),"examples");new r.default({templates:[n+"/test-input/Component/**/*"],output:n+"/test-output/no-create-subpath",createSubfolder:!1,locals:{property:"myProp",value:'"value"'}}).run(),new r.default({templates:[n+"/test-input/Component/**/*"],output:n+"/test-output",locals:{property:"myProp",value:'"value"'}}).run(),new r.default({templates:[n+"/test-input/Component/**/*"],output:function(e,t,o){return console.log({file:e,basedir:t,basename:o}),e},locals:{property:"myProp",value:'"value"'}}).run()},747:e=>{e.exports=require("fs")},878:e=>{e.exports=require("glob")},778:e=>{e.exports=require("handlebars")},622:e=>{e.exports=require("path")}},t={};return function o(r){if(t[r])return t[r].exports;var n=t[r]={exports:{}};return e[r].call(n.exports,n,n.exports,o),n.exports}(743)})()}));
|
||||
//# sourceMappingURL=test.js.map
|
||||
2
dist/test.js.map
vendored
2
dist/test.js.map
vendored
File diff suppressed because one or more lines are too long
0
dist/dist/cmd.d.ts → examples/test-input/Component/.hidden-file
Executable file → Normal file
0
dist/dist/cmd.d.ts → examples/test-input/Component/.hidden-file
Executable file → Normal file
19
examples/test-input/Component/Scaffold.tsx
Normal file
19
examples/test-input/Component/Scaffold.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import * as React from 'react'
|
||||
import * as css from './Scaffold.css'
|
||||
|
||||
class Scaffold extends React.Component<any> {
|
||||
private myProp
|
||||
|
||||
constructor(props: any) {
|
||||
super(props)
|
||||
this.myProp = "value"
|
||||
}
|
||||
|
||||
public render() {
|
||||
return (
|
||||
<div className={ css.Scaffold } />
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default Scaffold
|
||||
0
dist/dist/test.d.ts → examples/test-output/.gitkeep
Executable file → Normal file
0
dist/dist/test.d.ts → examples/test-output/.gitkeep
Executable file → Normal file
25
index.d.ts
vendored
25
index.d.ts
vendored
@@ -1,22 +1,29 @@
|
||||
declare namespace IScaffold {
|
||||
class SimpleScaffold {
|
||||
constructor(config: Config)
|
||||
run(): void
|
||||
}
|
||||
|
||||
export interface IConfig {
|
||||
export interface Config {
|
||||
name?: string
|
||||
templates: string[]
|
||||
output: string | ((path: string, base: string) => string)
|
||||
locals?: any
|
||||
output:
|
||||
| string
|
||||
| ((fullPath: string, basedir: string, basename: string) => string)
|
||||
locals?: Locals
|
||||
createSubfolder?: boolean
|
||||
overwrite?: boolean | ((path: string) => boolean)
|
||||
}
|
||||
|
||||
export interface IReplacement {
|
||||
find: string | RegExp
|
||||
replace(): string
|
||||
[other: string]: any
|
||||
export interface Locals {
|
||||
[k: string]: string
|
||||
}
|
||||
|
||||
export interface IFileRepr {
|
||||
export interface FileRepr {
|
||||
base: string
|
||||
file: string
|
||||
}
|
||||
}
|
||||
|
||||
export default IScaffold
|
||||
export default IScaffold.SimpleScaffold
|
||||
export { IScaffold }
|
||||
|
||||
2
index.js
Normal file
2
index.js
Normal file
@@ -0,0 +1,2 @@
|
||||
const SimpleScaffold = require('./dist')
|
||||
module.exports = SimpleScaffold
|
||||
41
package.json
41
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "simple-scaffold",
|
||||
"version": "0.2.0",
|
||||
"version": "0.7.1",
|
||||
"description": "Create files based on templates",
|
||||
"repository": "https://github.com/chenasraf/simple-scaffold.git",
|
||||
"author": "Chen Asraf <inbox@casraf.com>",
|
||||
@@ -9,7 +9,8 @@
|
||||
"bin": "dist/cmd.js",
|
||||
"types": "index.d.ts",
|
||||
"scripts": {
|
||||
"build": "NODE_ENV=${NODE_ENV:-production} webpack -p && chmod -R +x ./dist",
|
||||
"build": "NODE_ENV=${NODE_ENV:-production} webpack && chmod -R +x ./dist",
|
||||
"prepublishOnly": "yarn build",
|
||||
"dev": "webpack --watch",
|
||||
"start": "node dist/scaffold.js",
|
||||
"test": "node dist/test.js",
|
||||
@@ -18,15 +19,29 @@
|
||||
"build-cmd": "yarn build && yarn cmd"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/glob": "^5.0.34",
|
||||
"@types/handlebars": "^4.0.36",
|
||||
"@types/node": "^8.0.50",
|
||||
"glob": "^7.1.2",
|
||||
"handlebars": "^4.0.11",
|
||||
"ts-loader": "^3.1.1",
|
||||
"typescript": "^2.6.1",
|
||||
"webpack": "^3.8.1",
|
||||
"webpack-dev-server": "^2.9.4",
|
||||
"webpack-node-externals": "^1.6.0"
|
||||
"command-line-args": "^5.0.2",
|
||||
"command-line-usage": "^6.1.1",
|
||||
"glob": "^7.1.3",
|
||||
"handlebars": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/command-line-args": "^5.0.0",
|
||||
"@types/command-line-usage": "^5.0.1",
|
||||
"@types/glob": "^7.1.1",
|
||||
"@types/node": "^14.14.22",
|
||||
"copy-webpack-plugin": "^7.0.0",
|
||||
"jest": "^26.6.3",
|
||||
"ts-loader": "^8.0.14",
|
||||
"typescript": "^4.1.3",
|
||||
"webpack": "^5.19.0",
|
||||
"webpack-cli": "^4.4.0",
|
||||
"webpack-dev-server": "^3.2.1",
|
||||
"webpack-node-externals": "^2.5.2"
|
||||
},
|
||||
"jest": {
|
||||
"testPathIgnorePatterns": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
157
scaffold.ts
157
scaffold.ts
@@ -1,66 +1,85 @@
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import IScaffold from './index'
|
||||
import * as glob from 'glob'
|
||||
import * as handlebars from 'handlebars'
|
||||
import * as fs from "fs"
|
||||
import * as path from "path"
|
||||
import { IScaffold } from "./index.d"
|
||||
import * as glob from "glob"
|
||||
import * as handlebars from "handlebars"
|
||||
|
||||
class SimpleScaffold {
|
||||
private config: IScaffold.IConfig
|
||||
private locals = {} as any
|
||||
public config: IScaffold.Config
|
||||
public locals: IScaffold.Config["locals"] = {} as any
|
||||
|
||||
constructor(config: IScaffold.IConfig) {
|
||||
const DefaultConfig: IScaffold.IConfig = {
|
||||
name: 'scaffold',
|
||||
constructor(config: IScaffold.Config) {
|
||||
const DefaultConfig: IScaffold.Config = {
|
||||
name: "scaffold",
|
||||
templates: [],
|
||||
output: process.cwd(),
|
||||
createSubfolder: true,
|
||||
overwrite: true,
|
||||
}
|
||||
|
||||
this.config = (Object as any).assign({}, DefaultConfig, config)
|
||||
this.config = { ...DefaultConfig, ...config }
|
||||
|
||||
const DefaultLocals = {
|
||||
// TODO improve
|
||||
Name: this.config.name![0].toUpperCase() + this.config.name!.slice(1),
|
||||
name: this.config.name![0].toLowerCase() + this.config.name!.slice(1)
|
||||
name: this.config.name![0].toLowerCase() + this.config.name!.slice(1),
|
||||
}
|
||||
|
||||
this.locals = (Object as any).assign({}, DefaultLocals, config.locals)
|
||||
this.locals = { ...DefaultLocals, ...config.locals }
|
||||
}
|
||||
|
||||
private parseLocals(text: string): string {
|
||||
const template = handlebars.compile(text, {
|
||||
noEscape: true
|
||||
})
|
||||
return template(this.locals)
|
||||
try {
|
||||
const template = handlebars.compile(text, {
|
||||
noEscape: true,
|
||||
})
|
||||
return template(this.locals)
|
||||
} catch (e) {
|
||||
console.warn("Problem using Handlebars, returning unmodified content")
|
||||
return text
|
||||
}
|
||||
}
|
||||
|
||||
private *fileList(input: string[]): IterableIterator<IScaffold.IFileRepr> {
|
||||
private fileList(input: string[]): IScaffold.FileRepr[] {
|
||||
const output: IScaffold.FileRepr[] = []
|
||||
for (const checkPath of input) {
|
||||
const files = glob.sync(checkPath).map(g => g[0] == '/' ? g : path.join(process.cwd(), g))
|
||||
const idx = checkPath.indexOf('*')
|
||||
const files = glob
|
||||
.sync(checkPath, { dot: true })
|
||||
.map((g) => (g[0] == "/" ? g : path.join(process.cwd(), g)))
|
||||
const idx = checkPath.indexOf("*")
|
||||
let cleanCheckPath = checkPath
|
||||
if (idx >= 0) {
|
||||
cleanCheckPath = checkPath.slice(0, idx - 1)
|
||||
}
|
||||
for (const file of files) {
|
||||
yield {base: cleanCheckPath, file}
|
||||
output.push({ base: cleanCheckPath, file })
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
private getFileContents(filePath: string): string {
|
||||
console.log(fs.readFileSync(filePath))
|
||||
return fs.readFileSync(filePath).toString()
|
||||
}
|
||||
|
||||
private getOutputPath(file: string, basePath: string): string {
|
||||
let out
|
||||
let out: string
|
||||
|
||||
if (typeof this.config.output === 'function') {
|
||||
out = this.config.output(file, basePath)
|
||||
if (typeof this.config.output === "function") {
|
||||
out = this.config.output(file, basePath, path.basename(file))
|
||||
} else {
|
||||
const outputDir = this.config.output + `/${this.config.name}/`
|
||||
const outputDir =
|
||||
this.config.output +
|
||||
(this.config.createSubfolder ? `/${this.config.name}/` : "/")
|
||||
const idx = file.indexOf(basePath)
|
||||
let relativeFilePath = file
|
||||
if (idx >= 0) {
|
||||
relativeFilePath = file.slice(idx + basePath.length + 1)
|
||||
if (file !== basePath) {
|
||||
relativeFilePath = file.slice(idx + basePath.length + 1)
|
||||
} else {
|
||||
relativeFilePath = path.basename(file)
|
||||
}
|
||||
}
|
||||
out = outputDir + relativeFilePath
|
||||
}
|
||||
@@ -69,34 +88,88 @@ class SimpleScaffold {
|
||||
}
|
||||
|
||||
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' })
|
||||
const baseDir = path.dirname(filePath)
|
||||
this.writeDirectory(baseDir, filePath)
|
||||
fs.writeFile(filePath, fileContents, { encoding: "utf-8" }, (err) => {
|
||||
if (err) {
|
||||
throw err
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private shouldWriteFile(filePath: string) {
|
||||
const overwrite =
|
||||
typeof this.config.overwrite === "boolean"
|
||||
? this.config.overwrite
|
||||
: this.config.overwrite?.(filePath)
|
||||
const exists = fs.existsSync(filePath)
|
||||
|
||||
return !exists || overwrite !== false
|
||||
}
|
||||
|
||||
public run(): void {
|
||||
console.log(`Generating scaffold: ${this.config.name}...`)
|
||||
const templates = this.fileList(this.config.templates)
|
||||
|
||||
let fileConf, count = 0
|
||||
while (fileConf = templates.next().value) {
|
||||
count++
|
||||
const {file, base} = fileConf
|
||||
const outputPath = this.getOutputPath(file, base)
|
||||
const contents = this.getFileContents(file)
|
||||
const outputContents = this.parseLocals(contents)
|
||||
let fileConf,
|
||||
count = 0
|
||||
|
||||
this.writeFile(outputPath, outputContents)
|
||||
console.info('Parsing:', {file, base, outputPath, outputContents: outputContents.replace("\n", "\\n")})
|
||||
console.log("Template files:", templates)
|
||||
for (fileConf of templates) {
|
||||
let outputPath, contents, outputContents, file, base
|
||||
try {
|
||||
count++
|
||||
file = fileConf.file
|
||||
base = fileConf.base
|
||||
outputPath = this.getOutputPath(file, base)
|
||||
if (fs.lstatSync(file).isDirectory()) {
|
||||
this.writeDirectory(outputPath, file)
|
||||
continue
|
||||
}
|
||||
contents = this.getFileContents(file)
|
||||
outputContents = this.parseLocals(contents)
|
||||
if (this.shouldWriteFile(outputPath)) {
|
||||
console.info("Writing:", {
|
||||
file,
|
||||
base,
|
||||
outputPath,
|
||||
outputContents: outputContents.replace("\n", "\\n"),
|
||||
})
|
||||
this.writeFile(outputPath, outputContents)
|
||||
} else {
|
||||
console.log(`Skipping file ${outputPath}`)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error while processing file:", {
|
||||
file,
|
||||
base,
|
||||
contents,
|
||||
outputPath,
|
||||
outputContents,
|
||||
})
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
if (!count) {
|
||||
throw new Error('No files to scaffold!')
|
||||
throw new Error("No files to scaffold!")
|
||||
}
|
||||
|
||||
console.log('Done')
|
||||
console.log("Done")
|
||||
}
|
||||
|
||||
private writeDirectory(outputPath: string, file: any): void {
|
||||
const parent = path.dirname(outputPath)
|
||||
if (!fs.existsSync(parent)) {
|
||||
this.writeDirectory(parent, outputPath)
|
||||
}
|
||||
if (!fs.existsSync(outputPath)) {
|
||||
console.info("Creating directory:", {
|
||||
file,
|
||||
outputPath,
|
||||
})
|
||||
fs.mkdirSync(outputPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
38
test.ts
38
test.ts
@@ -1,13 +1,35 @@
|
||||
import SimpleScaffold from './scaffold'
|
||||
import * as path from 'path'
|
||||
import SimpleScaffold from "./scaffold"
|
||||
import * as path from "path"
|
||||
|
||||
const templateDir = path.join(process.cwd(), 'examples')
|
||||
const templateDir = path.join(process.cwd(), "examples")
|
||||
|
||||
new SimpleScaffold({
|
||||
templates: [templateDir + '/test-input/Component/**/*'],
|
||||
output: templateDir + '/test-output',
|
||||
templates: [templateDir + "/test-input/Component/**/*"],
|
||||
output: templateDir + "/test-output/no-create-subpath",
|
||||
createSubfolder: false,
|
||||
locals: {
|
||||
property: 'myProp',
|
||||
value: '"value"'
|
||||
}
|
||||
property: "myProp",
|
||||
value: '"value"',
|
||||
},
|
||||
}).run()
|
||||
|
||||
new SimpleScaffold({
|
||||
templates: [templateDir + "/test-input/Component/**/*"],
|
||||
output: templateDir + "/test-output",
|
||||
locals: {
|
||||
property: "myProp",
|
||||
value: '"value"',
|
||||
},
|
||||
}).run()
|
||||
|
||||
new SimpleScaffold({
|
||||
templates: [templateDir + "/test-input/Component/**/*"],
|
||||
output: (file, basedir, basename) => {
|
||||
console.log({ file, basedir, basename })
|
||||
return file
|
||||
},
|
||||
locals: {
|
||||
property: "myProp",
|
||||
value: '"value"',
|
||||
},
|
||||
}).run()
|
||||
|
||||
@@ -1,43 +1,46 @@
|
||||
const path = require('path')
|
||||
const webpack = require('webpack')
|
||||
const nodeExternals = require('webpack-node-externals')
|
||||
const path = require("path")
|
||||
const webpack = require("webpack")
|
||||
const nodeExternals = require("webpack-node-externals")
|
||||
const CopyPlugin = require("copy-webpack-plugin")
|
||||
|
||||
module.exports = {
|
||||
devtool: process.env.NODE_ENV === 'develop' ? 'inline-source-map' : 'source-map',
|
||||
target: 'node',
|
||||
devtool:
|
||||
process.env.NODE_ENV === "develop" ? "inline-source-map" : "source-map",
|
||||
target: "node",
|
||||
entry: {
|
||||
scaffold: './scaffold.ts',
|
||||
test: './test.ts',
|
||||
cmd: './cmd.ts',
|
||||
index: "./scaffold.ts",
|
||||
test: "./test.ts",
|
||||
cmd: "./cmd.ts",
|
||||
},
|
||||
output: {
|
||||
filename: '[name].js',
|
||||
path: path.resolve(__dirname, 'dist'),
|
||||
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
|
||||
library: 'library',
|
||||
libraryTarget: 'umd',
|
||||
filename: "[name].js",
|
||||
path: path.resolve(__dirname, "dist"),
|
||||
devtoolModuleFilenameTemplate: "[absolute-resource-path]",
|
||||
library: "library",
|
||||
libraryTarget: "umd",
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.ts']
|
||||
extensions: [".ts"],
|
||||
},
|
||||
externals: [nodeExternals()],
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
loader: 'ts-loader',
|
||||
exclude: ['./examples', 'node_modules']
|
||||
}
|
||||
]
|
||||
test: [/\.tsx?$/],
|
||||
loader: "ts-loader",
|
||||
exclude: [/\/examples\//, /\/node_modules\//],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new webpack.DefinePlugin({
|
||||
'__dirname': '__dirname'
|
||||
__dirname: "__dirname",
|
||||
}),
|
||||
new webpack.BannerPlugin({
|
||||
banner: '#!/usr/bin/env node',
|
||||
banner: "#!/usr/bin/env node",
|
||||
raw: true,
|
||||
include: /cmd\.js/,
|
||||
})
|
||||
include: [/cmd\.js/],
|
||||
}),
|
||||
new CopyPlugin({ patterns: ["index.d.ts"] }),
|
||||
],
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user