Compare commits

...

16 Commits

Author SHA1 Message Date
Chen Asraf
0be29dd89e v0.3.0 2018-01-15 02:19:23 +02:00
Chen Asraf
4f29a612a3 cleanups 2018-01-15 02:18:39 +02:00
Chen Asraf
14b60ffc79 output is optional 2018-01-15 02:16:51 +02:00
Chen Asraf
1275743764 Update README.md 2018-01-07 02:25:27 +02:00
Chen Asraf
b09299b432 Uodate README.md 2018-01-05 04:53:41 +02:00
Chen Asraf
45e8de3034 Rename 2018-01-05 04:52:52 +02:00
Chen Asraf
a3a77e2ab5 Update README.md 2018-01-05 04:52:26 +02:00
Chen Asraf
f36015962d v0.2.0 2018-01-05 04:45:31 +02:00
Chen Asraf
e391f8f68f Improve cmd script, add readme 2018-01-05 04:44:11 +02:00
Chen Asraf
4ca7c6acb3 Fixed cmd 2018-01-05 04:04:33 +02:00
Chen Asraf
0fd996413b Improve build 2018-01-05 03:53:43 +02:00
Chen Asraf
e64c0e4a45 Use handlebars, add cmd script in package.json 2018-01-05 03:35:00 +02:00
Chen Asraf
3e42ac5a95 Move all scripts to webpack, add wip cmd script for bin 2018-01-05 03:06:25 +02:00
Chen Asraf
eecec82aaa v0.1.5 2018-01-01 23:27:10 +02:00
Chen Asraf
6ec19fc4cd v0.1.4 2018-01-01 23:22:20 +02:00
Chen Asraf
a5776d6108 v0.1.3 2018-01-01 23:20:36 +02:00
26 changed files with 1407 additions and 114 deletions

24
.vscode/launch.json vendored
View File

@@ -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"
}
}
]
}

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"typescript.tsdk": "./node_modules/typescript/lib"
}

7
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
"version": "0.1.0",
"command": "webpack",
"isShellCommand": true,
"args": [],
"showOutput": "always"
}

120
README.md
View File

@@ -1,12 +1,120 @@
# scaffolder
# simple-scaffolder
Scaffolder allows you to create your structured files based on templates.
### How to use
## Install
You can either use it as a command line tool or import into your own code and run from there.
#### Install
You Scaffolder by using `npm`. Global flag is useful if you want easy cli access to it.
You can install simple-scaffold globally like so:
```
npm install -g scaffolder
```bash
# npm
npm install -g simple-scaffold
# yarn
yarn global add simple-scaffold
```
## Use as a command line tool
### Command line options
```bash
simple-scaffold MyComponent --template scaffolds/component/**/* \
--output src/components \
--locals myProp="propname",myVal=123
```
##### `--template glob [--template glob2 [...]]`
A glob pattern of template files to load.
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 path`
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 key=value[,key=value[,...]]`
Pass a KV map to the template for parsing.
### Use in Node.js
You can also build the scaffold yourself.
Simply pass a config object to the constructor, and invoke `run()` when you are ready to start.
The config takes the same arguments as 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'),
locals: {
property: 'value',
}
}).run()
```
## Example Scaffold Input
Scaffolding will replace interpolations in both the file name and contents.
Your context will be pre-populated with
- `{{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 `}}`.
### Input Directory structure
```
- project
- scaffold
- {{Name}}.css
- src
- components
- ...
```
#### project/scaffold/{{Name}}.css
```css
.{{className}} {
border: 1px solid black;
}
.{{className}}-child {
background: red;
}
```
### Run Example
```bash
simple-scaffold MyComponent \
--template project/scaffold/**/* \
--output src/components \
--locals 'className=my-component`
```
## Example Scaffold Output
#### Directory structure
```
- project
- src
- components
- MyComponent
- MyComponent.css
- ...
```
#### project/src/components/MyComponent/MyComponent.css
```css
.my-component {
border: 1px solid black;
}
.my-component-child {
background: red;
}
```

86
cmd.ts Normal file
View File

@@ -0,0 +1,86 @@
import SimpleScaffold from './scaffold'
import * as fs from 'fs'
import IScaffold from './index'
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'].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()
}
}
new ScaffoldCmd().run()

333
dist/cmd.js vendored Executable file
View File

@@ -0,0 +1,333 @@
#!/usr/bin/env node
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["library"] = factory();
else
root["library"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 6);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = __webpack_require__(2);
var path = __webpack_require__(0);
var glob = __webpack_require__(3);
var handlebars = __webpack_require__(4);
var SimpleScaffold = /** @class */ (function () {
function SimpleScaffold(config) {
this.locals = {};
var DefaultConfig = {
name: 'scaffold',
templates: [],
output: process.cwd(),
};
this.config = Object.assign({}, DefaultConfig, config);
var DefaultLocals = {
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({}, DefaultLocals, config.locals);
}
SimpleScaffold.prototype.parseLocals = function (text) {
var template = handlebars.compile(text, {
noEscape: true
});
return template(this.locals);
};
SimpleScaffold.prototype.fileList = function (input) {
var _i, input_1, checkPath, files, idx, cleanCheckPath, _a, files_1, file;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_i = 0, input_1 = input;
_b.label = 1;
case 1:
if (!(_i < input_1.length)) return [3 /*break*/, 6];
checkPath = input_1[_i];
files = glob.sync(checkPath).map(function (g) { return g[0] == '/' ? g : path.join(process.cwd(), g); });
idx = checkPath.indexOf('*');
cleanCheckPath = checkPath;
if (idx >= 0) {
cleanCheckPath = checkPath.slice(0, idx - 1);
}
_a = 0, files_1 = files;
_b.label = 2;
case 2:
if (!(_a < files_1.length)) return [3 /*break*/, 5];
file = files_1[_a];
return [4 /*yield*/, { base: cleanCheckPath, file: file }];
case 3:
_b.sent();
_b.label = 4;
case 4:
_a++;
return [3 /*break*/, 2];
case 5:
_i++;
return [3 /*break*/, 1];
case 6: return [2 /*return*/];
}
});
};
SimpleScaffold.prototype.getFileContents = function (filePath) {
return fs.readFileSync(filePath).toString();
};
SimpleScaffold.prototype.getOutputPath = function (file, basePath) {
var out;
if (typeof this.config.output === 'function') {
out = this.config.output(file, basePath);
}
else {
var outputDir = this.config.output + ("/" + this.config.name + "/");
var idx = file.indexOf(basePath);
var relativeFilePath = file;
if (idx >= 0) {
relativeFilePath = file.slice(idx + basePath.length + 1);
}
out = outputDir + relativeFilePath;
}
return this.parseLocals(out);
};
SimpleScaffold.prototype.writeFile = function (filePath, fileContents) {
if (!fs.existsSync(path.dirname(filePath))) {
fs.mkdirSync(path.dirname(filePath));
}
console.info('Writing file:', filePath);
fs.writeFileSync(filePath, fileContents, { encoding: 'utf-8' });
};
SimpleScaffold.prototype.run = function () {
console.log("Generating scaffold: " + this.config.name + "...");
var templates = this.fileList(this.config.templates);
var fileConf, count = 0;
while (fileConf = templates.next().value) {
count++;
var file = fileConf.file, base = fileConf.base;
var outputPath = this.getOutputPath(file, base);
var contents = this.getFileContents(file);
var outputContents = this.parseLocals(contents);
this.writeFile(outputPath, outputContents);
console.info('Parsing:', { file: file, base: base, outputPath: outputPath, outputContents: outputContents.replace("\n", "\\n") });
}
if (!count) {
throw new Error('No files to scaffold!');
}
console.log('Done');
};
return SimpleScaffold;
}());
exports.default = SimpleScaffold;
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = require("fs");
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = require("glob");
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("handlebars");
/***/ }),
/* 5 */,
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var scaffold_1 = __webpack_require__(1);
var args = process.argv.slice(2);
var ScaffoldCmd = /** @class */ (function () {
function ScaffoldCmd() {
this.config = this.getOptionsFromArgs();
}
ScaffoldCmd.prototype.getOptionsFromArgs = function () {
var _this = this;
var skipNext = false;
var options = {};
args.forEach(function (arg, i) {
if (skipNext) {
skipNext = false;
return;
}
if (arg.slice(0, 2) == '--') {
skipNext = true;
var value = void 0;
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';
}
var 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(function (o) { return options[o] !== undefined; })) {
throw new Error("Config is missing keys: " + JSON.stringify(options));
}
return options;
};
ScaffoldCmd.prototype.getArgValue = function (arg, value, options) {
switch (arg) {
case 'templates':
return (options.templates || []).concat([value]);
case 'output':
return value;
case 'locals':
var split = value.split(',');
var locals = options.locals || {};
for (var _i = 0, split_1 = split; _i < split_1.length; _i++) {
var item = split_1[_i];
var _a = item.split('='), k = _a[0], v = _a[1];
locals[k] = v;
}
return locals;
default:
throw TypeError("arguments invalid for config: arg=`" + arg + "`, value=`" + value + "`");
}
};
ScaffoldCmd.prototype.run = function () {
var config = this.config;
console.info('Config:', config);
var scf = new scaffold_1.default({
name: config.name,
templates: config.templates,
output: config.output,
locals: config.locals,
}).run();
};
return ScaffoldCmd;
}());
new ScaffoldCmd().run();
/***/ })
/******/ ]);
});
//# sourceMappingURL=cmd.js.map

1
dist/cmd.js.map vendored Executable file

File diff suppressed because one or more lines are too long

0
dist/dist/cmd.d.ts vendored Executable file
View File

13
dist/dist/scaffold.d.ts vendored Normal file → Executable file
View File

@@ -0,0 +1,13 @@
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;

0
dist/dist/test.d.ts vendored Executable file
View File

96
dist/main.js vendored Normal file
View File

@@ -0,0 +1,96 @@
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["library"] = factory();
else
root["library"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 7);
/******/ })
/************************************************************************/
/******/ ({
/***/ 7:
/***/ (function(module, exports, __webpack_require__) {
(function webpackMissingModule() { throw new Error("Cannot find module \"add\""); }());
module.exports = __webpack_require__(8);
/***/ }),
/***/ 8:
/***/ (function(module, exports) {
module.exports = require("jest");
/***/ })
/******/ });
});
//# sourceMappingURL=main.js.map

1
dist/main.js.map vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["webpack/universalModuleDefinition","webpack/bootstrap c994c2c400fa1fc61abe","external \"jest\""],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;AAEA;AACA;;;;;;;;;;;;;;;;;AC7DA,iC","file":"main.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"library\"] = factory();\n\telse\n\t\troot[\"library\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 7);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap c994c2c400fa1fc61abe","module.exports = require(\"jest\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"jest\"\n// module id = 8\n// module chunks = 3"],"sourceRoot":""}

247
dist/scaffold.js vendored
View File

@@ -1 +1,246 @@
!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")}]);
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["library"] = factory();
else
root["library"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = __webpack_require__(2);
var path = __webpack_require__(0);
var glob = __webpack_require__(3);
var handlebars = __webpack_require__(4);
var SimpleScaffold = /** @class */ (function () {
function SimpleScaffold(config) {
this.locals = {};
var DefaultConfig = {
name: 'scaffold',
templates: [],
output: process.cwd(),
};
this.config = Object.assign({}, DefaultConfig, config);
var DefaultLocals = {
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({}, DefaultLocals, config.locals);
}
SimpleScaffold.prototype.parseLocals = function (text) {
var template = handlebars.compile(text, {
noEscape: true
});
return template(this.locals);
};
SimpleScaffold.prototype.fileList = function (input) {
var _i, input_1, checkPath, files, idx, cleanCheckPath, _a, files_1, file;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_i = 0, input_1 = input;
_b.label = 1;
case 1:
if (!(_i < input_1.length)) return [3 /*break*/, 6];
checkPath = input_1[_i];
files = glob.sync(checkPath).map(function (g) { return g[0] == '/' ? g : path.join(process.cwd(), g); });
idx = checkPath.indexOf('*');
cleanCheckPath = checkPath;
if (idx >= 0) {
cleanCheckPath = checkPath.slice(0, idx - 1);
}
_a = 0, files_1 = files;
_b.label = 2;
case 2:
if (!(_a < files_1.length)) return [3 /*break*/, 5];
file = files_1[_a];
return [4 /*yield*/, { base: cleanCheckPath, file: file }];
case 3:
_b.sent();
_b.label = 4;
case 4:
_a++;
return [3 /*break*/, 2];
case 5:
_i++;
return [3 /*break*/, 1];
case 6: return [2 /*return*/];
}
});
};
SimpleScaffold.prototype.getFileContents = function (filePath) {
return fs.readFileSync(filePath).toString();
};
SimpleScaffold.prototype.getOutputPath = function (file, basePath) {
var out;
if (typeof this.config.output === 'function') {
out = this.config.output(file, basePath);
}
else {
var outputDir = this.config.output + ("/" + this.config.name + "/");
var idx = file.indexOf(basePath);
var relativeFilePath = file;
if (idx >= 0) {
relativeFilePath = file.slice(idx + basePath.length + 1);
}
out = outputDir + relativeFilePath;
}
return this.parseLocals(out);
};
SimpleScaffold.prototype.writeFile = function (filePath, fileContents) {
if (!fs.existsSync(path.dirname(filePath))) {
fs.mkdirSync(path.dirname(filePath));
}
console.info('Writing file:', filePath);
fs.writeFileSync(filePath, fileContents, { encoding: 'utf-8' });
};
SimpleScaffold.prototype.run = function () {
console.log("Generating scaffold: " + this.config.name + "...");
var templates = this.fileList(this.config.templates);
var fileConf, count = 0;
while (fileConf = templates.next().value) {
count++;
var file = fileConf.file, base = fileConf.base;
var outputPath = this.getOutputPath(file, base);
var contents = this.getFileContents(file);
var outputContents = this.parseLocals(contents);
this.writeFile(outputPath, outputContents);
console.info('Parsing:', { file: file, base: base, outputPath: outputPath, outputContents: outputContents.replace("\n", "\\n") });
}
if (!count) {
throw new Error('No files to scaffold!');
}
console.log('Done');
};
return SimpleScaffold;
}());
exports.default = SimpleScaffold;
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = require("fs");
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = require("glob");
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("handlebars");
/***/ })
/******/ ]);
});
//# sourceMappingURL=scaffold.js.map

1
dist/scaffold.js.map vendored Executable file

File diff suppressed because one or more lines are too long

266
dist/test.js vendored Executable file
View File

@@ -0,0 +1,266 @@
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["library"] = factory();
else
root["library"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 5);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [0, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = __webpack_require__(2);
var path = __webpack_require__(0);
var glob = __webpack_require__(3);
var handlebars = __webpack_require__(4);
var SimpleScaffold = /** @class */ (function () {
function SimpleScaffold(config) {
this.locals = {};
var DefaultConfig = {
name: 'scaffold',
templates: [],
output: process.cwd(),
};
this.config = Object.assign({}, DefaultConfig, config);
var DefaultLocals = {
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({}, DefaultLocals, config.locals);
}
SimpleScaffold.prototype.parseLocals = function (text) {
var template = handlebars.compile(text, {
noEscape: true
});
return template(this.locals);
};
SimpleScaffold.prototype.fileList = function (input) {
var _i, input_1, checkPath, files, idx, cleanCheckPath, _a, files_1, file;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_i = 0, input_1 = input;
_b.label = 1;
case 1:
if (!(_i < input_1.length)) return [3 /*break*/, 6];
checkPath = input_1[_i];
files = glob.sync(checkPath).map(function (g) { return g[0] == '/' ? g : path.join(process.cwd(), g); });
idx = checkPath.indexOf('*');
cleanCheckPath = checkPath;
if (idx >= 0) {
cleanCheckPath = checkPath.slice(0, idx - 1);
}
_a = 0, files_1 = files;
_b.label = 2;
case 2:
if (!(_a < files_1.length)) return [3 /*break*/, 5];
file = files_1[_a];
return [4 /*yield*/, { base: cleanCheckPath, file: file }];
case 3:
_b.sent();
_b.label = 4;
case 4:
_a++;
return [3 /*break*/, 2];
case 5:
_i++;
return [3 /*break*/, 1];
case 6: return [2 /*return*/];
}
});
};
SimpleScaffold.prototype.getFileContents = function (filePath) {
return fs.readFileSync(filePath).toString();
};
SimpleScaffold.prototype.getOutputPath = function (file, basePath) {
var out;
if (typeof this.config.output === 'function') {
out = this.config.output(file, basePath);
}
else {
var outputDir = this.config.output + ("/" + this.config.name + "/");
var idx = file.indexOf(basePath);
var relativeFilePath = file;
if (idx >= 0) {
relativeFilePath = file.slice(idx + basePath.length + 1);
}
out = outputDir + relativeFilePath;
}
return this.parseLocals(out);
};
SimpleScaffold.prototype.writeFile = function (filePath, fileContents) {
if (!fs.existsSync(path.dirname(filePath))) {
fs.mkdirSync(path.dirname(filePath));
}
console.info('Writing file:', filePath);
fs.writeFileSync(filePath, fileContents, { encoding: 'utf-8' });
};
SimpleScaffold.prototype.run = function () {
console.log("Generating scaffold: " + this.config.name + "...");
var templates = this.fileList(this.config.templates);
var fileConf, count = 0;
while (fileConf = templates.next().value) {
count++;
var file = fileConf.file, base = fileConf.base;
var outputPath = this.getOutputPath(file, base);
var contents = this.getFileContents(file);
var outputContents = this.parseLocals(contents);
this.writeFile(outputPath, outputContents);
console.info('Parsing:', { file: file, base: base, outputPath: outputPath, outputContents: outputContents.replace("\n", "\\n") });
}
if (!count) {
throw new Error('No files to scaffold!');
}
console.log('Done');
};
return SimpleScaffold;
}());
exports.default = SimpleScaffold;
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = require("fs");
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = require("glob");
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("handlebars");
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var scaffold_1 = __webpack_require__(1);
var path = __webpack_require__(0);
var templateDir = path.join(process.cwd(), 'examples');
new scaffold_1.default({
templates: [templateDir + '/test-input/Component/**/*'],
output: templateDir + '/test-output',
locals: {
property: 'myProp',
value: '"value"'
}
}).run();
/***/ })
/******/ ]);
});
//# sourceMappingURL=test.js.map

1
dist/test.js.map vendored Executable file

File diff suppressed because one or more lines are too long

View File

@@ -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%}

View File

@@ -0,0 +1,19 @@
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
View File

@@ -1,15 +1,16 @@
export namespace IScaffold {
declare namespace IScaffold {
export interface IConfig {
name?: string
templates: string[]
output: string | ((path: string) => string)
output: string | ((path: string, base: string) => string)
locals?: any
}
export interface IReplacement {
find: string | RegExp
replace(): string
[other: string]: any
export interface IFileRepr {
base: string
file: string
}
}
export default IScaffold

View File

@@ -1,26 +1,41 @@
{
"name": "simple-scaffold",
"version": "0.1.2",
"version": "0.3.0",
"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": "dist/scaffold.js",
"bin": "dist/cmd.js",
"types": "index.d.ts",
"scripts": {
"build": "webpack -p && chmod +x ./dist/scaffold.js",
"build": "NODE_ENV=${NODE_ENV:-production} webpack -p && chmod -R +x ./dist",
"dev": "webpack --watch",
"start": "node ./dist/scaffold.js",
"test": "yarn build && node ./scripts/test.js"
"start": "node dist/scaffold.js",
"test": "jest",
"cmd": "dist/cmd.js",
"build-test": "yarn build && yarn test",
"build-cmd": "yarn build && yarn cmd"
},
"files": [
"./dist/scaffold.js"
],
"devDependencies": {
"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-dev-server": "^2.9.4",
"webpack-node-externals": "^1.6.0"
},
"devDependencies": {
"jest": "^22.0.4"
},
"jest": {
"testPathIgnorePatterns": [
"node_modules",
"dist"
]
}
}

View File

@@ -1,65 +1,69 @@
import * as fs from 'fs'
import * as path from 'path'
import { IScaffold } from './index'
import IScaffold from './index'
import * as glob from 'glob'
import * as handlebars from 'handlebars'
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)
}
}
public config: IScaffold.IConfig
public locals = {} as any
constructor(config: IScaffold.IConfig) {
if (!this.scaffoldName) {
throw new Error('Must provide scaffold name')
const DefaultConfig: IScaffold.IConfig = {
name: 'scaffold',
templates: [],
output: process.cwd(),
}
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)
this.config = (Object as any).assign({}, DefaultConfig, config)
const DefaultLocals = {
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 as any).assign({}, DefaultLocals, config.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])
const template = handlebars.compile(text, {
noEscape: true
})
return template(this.locals)
}
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))
private *fileList(input: string[]): IterableIterator<IScaffold.IFileRepr> {
for (const checkPath of input) {
const files = glob.sync(checkPath).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)
}
})
return outList
for (const file of files) {
yield {base: cleanCheckPath, file}
}
}
}
private getFileContents(filePath: string): string {
console.log(fs.readFileSync(filePath))
return fs.readFileSync(filePath).toString()
}
private getOutputPath(file: string): string {
private getOutputPath(file: string, basePath: string): string {
let out
if (typeof this.config.output === 'function') {
out = this.config.output(file)
out = this.config.output(file, basePath)
} else {
out = this.config.output + `/${this.scaffoldName}/` + path.basename(file)
const outputDir = this.config.output + `/${this.config.name}/`
const idx = file.indexOf(basePath)
let relativeFilePath = file
if (idx >= 0) {
relativeFilePath = file.slice(idx + basePath.length + 1)
}
out = outputDir + relativeFilePath
}
return this.parseLocals(out)
@@ -73,16 +77,28 @@ class SimpleScaffold {
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)
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)
this.writeFile(outputPath, outputContents)
})
console.info('Parsing:', {file, base, outputPath, outputContents: outputContents.replace("\n", "\\n")})
}
if (!count) {
throw new Error('No files to scaffold!')
}
console.log('Done')
}
}
exports.default = SimpleScaffold
export default SimpleScaffold

View File

@@ -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()

13
test.ts Normal file
View File

@@ -0,0 +1,13 @@
import SimpleScaffold from './scaffold'
import * as path from 'path'
const templateDir = path.join(process.cwd(), 'examples')
new SimpleScaffold({
templates: [templateDir + '/test-input/Component/**/*'],
output: templateDir + '/test-output',
locals: {
property: 'myProp',
value: '"value"'
}
}).run()

View File

@@ -1,9 +1,10 @@
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"module": "commonjs",
"lib": ["es2017", "es6"],
"declaration": true,
"outDir": "./dist",
"outDir": "dist",
"strict": true,
"sourceMap": true
},

View File

@@ -1,22 +1,43 @@
const path = require('path')
const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
module.exports = {
devtool: process.env.NODE_ENV === 'develop' ? 'inline-source-map' : 'source-map',
target: 'node',
entry: './scaffold.ts',
entry: {
scaffold: './scaffold.ts',
test: './test.ts',
cmd: './cmd.ts',
},
output: {
filename: 'scaffold.js',
path: path.resolve(__dirname, 'dist')
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
library: 'library',
libraryTarget: 'umd',
},
resolve: {
extensions: ['.ts']
},
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: ['./examples']
exclude: ['./examples', 'node_modules']
}
]
}
},
plugins: [
new webpack.DefinePlugin({
'__dirname': '__dirname'
}),
new webpack.BannerPlugin({
banner: '#!/usr/bin/env node',
raw: true,
include: /cmd\.js/,
})
],
}

View File

@@ -2,6 +2,30 @@
# yarn lockfile v1
"@types/events@*":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@types/events/-/events-1.1.0.tgz#93b1be91f63c184450385272c47b6496fd028e02"
"@types/glob@^5.0.34":
version "5.0.34"
resolved "https://registry.yarnpkg.com/@types/glob/-/glob-5.0.34.tgz#ee626c9be3da877d717911c6101eee0a9871bbf4"
dependencies:
"@types/events" "*"
"@types/minimatch" "*"
"@types/node" "*"
"@types/handlebars@^4.0.36":
version "4.0.36"
resolved "https://registry.yarnpkg.com/@types/handlebars/-/handlebars-4.0.36.tgz#ff57c77fa1ab6713bb446534ddc4d979707a3a79"
"@types/minimatch@*":
version "3.0.3"
resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d"
"@types/node@*":
version "0.12.14"
resolved "https://registry.yarnpkg.com/@types/node/-/node-0.12.14.tgz#117c531e3f49b0ecfa1b439495abe22517fdfa7f"
"@types/node@^8.0.50":
version "8.0.50"
resolved "https://registry.yarnpkg.com/@types/node/-/node-8.0.50.tgz#dc545448e128c88c4eec7cd64025fcc3b7604541"
@@ -59,6 +83,10 @@ align-text@^0.1.1, align-text@^0.1.3:
longest "^1.0.1"
repeat-string "^1.5.2"
amdefine@>=0.0.4:
version "1.0.1"
resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5"
ansi-html@0.0.7:
version "0.0.7"
resolved "https://registry.yarnpkg.com/ansi-html/-/ansi-html-0.0.7.tgz#813584021962a9e9e6fd039f940d12f56ca7859e"
@@ -168,7 +196,7 @@ async-each@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.1.tgz#19d386a1d9edc6e7c1c85d388aedbcc56d33602d"
async@^1.5.2:
async@^1.4.0, async@^1.5.2:
version "1.5.2"
resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a"
@@ -1125,7 +1153,7 @@ glob-parent@^2.0.0:
dependencies:
is-glob "^2.0.0"
glob@^7.0.3, glob@^7.0.5:
glob@^7.0.3, glob@^7.0.5, glob@^7.1.2:
version "7.1.2"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15"
dependencies:
@@ -1154,6 +1182,16 @@ handle-thing@^1.2.5:
version "1.2.5"
resolved "https://registry.yarnpkg.com/handle-thing/-/handle-thing-1.2.5.tgz#fd7aad726bf1a5fd16dfc29b2f7a6601d27139c4"
handlebars@^4.0.11:
version "4.0.11"
resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.11.tgz#630a35dfe0294bc281edae6ffc5d329fc7982dcc"
dependencies:
async "^1.4.0"
optimist "^0.6.1"
source-map "^0.4.4"
optionalDependencies:
uglify-js "^2.6"
har-schema@^1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-1.0.5.tgz#d263135f43307c02c602afc8fe95970c0151369e"
@@ -1763,6 +1801,10 @@ minimist@^1.1.3, minimist@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284"
minimist@~0.0.1:
version "0.0.10"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf"
mkdirp@0.5.x, "mkdirp@>=0.5 0", mkdirp@^0.5.1, mkdirp@~0.5.0:
version "0.5.1"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903"
@@ -1926,6 +1968,13 @@ opn@^5.1.0:
dependencies:
is-wsl "^1.1.0"
optimist@^0.6.1:
version "0.6.1"
resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686"
dependencies:
minimist "~0.0.1"
wordwrap "~0.0.2"
original@>=0.0.5:
version "1.0.0"
resolved "https://registry.yarnpkg.com/original/-/original-1.0.0.tgz#9147f93fa1696d04be61e01bd50baeaca656bd3b"
@@ -2493,6 +2542,12 @@ source-list-map@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/source-list-map/-/source-list-map-2.0.0.tgz#aaa47403f7b245a92fbc97ea08f250d6087ed085"
source-map@^0.4.4:
version "0.4.4"
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b"
dependencies:
amdefine ">=0.0.4"
source-map@^0.5.3, source-map@^0.5.6, source-map@~0.5.1:
version "0.5.7"
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
@@ -2735,7 +2790,7 @@ typescript@^2.6.1:
version "2.6.1"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.6.1.tgz#ef39cdea27abac0b500242d6726ab90e0c846631"
uglify-js@^2.8.29:
uglify-js@^2.6, uglify-js@^2.8.29:
version "2.8.29"
resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd"
dependencies:
@@ -2888,6 +2943,10 @@ webpack-dev-server@^2.9.4:
webpack-dev-middleware "^1.11.0"
yargs "^6.6.0"
webpack-node-externals@^1.6.0:
version "1.6.0"
resolved "https://registry.yarnpkg.com/webpack-node-externals/-/webpack-node-externals-1.6.0.tgz#232c62ec6092b100635a3d29d83c1747128df9bd"
webpack-sources@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-1.0.2.tgz#d0148ec083b3b5ccef1035a6b3ec16442983b27a"
@@ -2961,6 +3020,10 @@ wordwrap@0.0.2:
version "0.0.2"
resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f"
wordwrap@~0.0.2:
version "0.0.3"
resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107"
wrap-ansi@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85"