Skip to content

Commit

Permalink
Merge branch 'anithri-rmLodash'
Browse files Browse the repository at this point in the history
  • Loading branch information
jondot committed Aug 25, 2019
2 parents cb82e84 + ce89010 commit 3d63fc5
Show file tree
Hide file tree
Showing 24 changed files with 219 additions and 212 deletions.
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"semi": false,
"singleQuote": true,
"trailingComma": "all"
}
4 changes: 1 addition & 3 deletions lib/config-resolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

const L = require('lodash');

const fs = require('fs-extra');

const configResolver = new _config.ConfigResolver('.hygen.js', {
Expand All @@ -31,7 +29,7 @@ function () {
var _ref = _asyncToGenerator(function* (config) {
const cwd = config.cwd,
templates = config.templates;
const resolvedTemplates = L.find([process.env.HYGEN_TMPLS, _path.default.join(cwd, '_templates')], _ => _ && fs.existsSync(_)) || templates;
const resolvedTemplates = [process.env.HYGEN_TMPLS, _path.default.join(cwd, '_templates')].find(_ => _ && fs.existsSync(_)) || templates;
return _objectSpread({}, config, {
templates: resolvedTemplates
}, (yield configResolver.resolve(cwd)));
Expand Down
34 changes: 13 additions & 21 deletions lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ConfigResolver = exports.configLookup = void 0;
exports.reversePathsToWalk = exports.ConfigResolver = exports.configLookup = void 0;

var _path = _interopRequireDefault(require("path"));

var _lodash = _interopRequireDefault(require("lodash"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
Expand All @@ -18,31 +16,25 @@ function _asyncToGenerator(fn) { return function () { var self = this, args = ar
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

// inline fp methods due to perf
const reduce = (f, init) => arr => _lodash.default.reduce(arr, f, init);
const uniq = arr => arr.filter((elem, pos, a) => a.indexOf(elem) === pos);

const reversePathsToWalk = _lodash.default.flow(({
const reversePathsToWalk = ({
folder,
path
}) => ({
resolved: path.resolve(folder),
path
}), ({
resolved,
path
}) => ({
parts: resolved.split(path.sep),
path
}), ({
parts,
path
}) => {
return reduce((acc, p) => [...acc, path.join(_lodash.default.last(acc), p)], [path.join(_lodash.default.head(parts), path.sep)])(_lodash.default.tail(parts));
}, _lodash.default.reverse, _lodash.default.uniq);
const resolved = path.resolve(folder);
const parts = resolved.split(path.sep);
const results = parts.map((n, idx, arr) => arr.slice(0, idx + 1).join(path.sep));
results[0] = results[0] || '/';
return results.reverse();
};

exports.reversePathsToWalk = reversePathsToWalk;

const configLookup = (file, folder, path = _path.default) => _lodash.default.map(reversePathsToWalk({
const configLookup = (file, folder, path = _path.default) => uniq(reversePathsToWalk({
folder,
path
}), p => path.join(p, file));
}).map(p => path.join(p, file)));

exports.configLookup = configLookup;

Expand Down
11 changes: 8 additions & 3 deletions lib/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

const L = require('lodash');

const inflection = require('inflection');

const changeCase = require('change-case'); // supports kebab-case to KebabCase
Expand All @@ -21,12 +19,19 @@ const helpers = {
inflection,
changeCase
};

const doCapitalization = (hsh, [key, value]) => {
hsh[key] = value;
if (localsToCapitalize.includes(key)) hsh[helpers.capitalize(key)] = helpers.capitalize(value);
return hsh;
};

const localsToCapitalize = ['name'];
const localsDefaults = {
name: 'unnamed'
};

const capitalizedLocals = locals => L.mapValues(L.mapKeys(L.pick(locals, localsToCapitalize), (v, k) => helpers.capitalize(k)), v => helpers.capitalize(v));
const capitalizedLocals = locals => Object.entries(locals).reduce(doCapitalization, {});

const context = (locals, config) => {
const localsWithDefaults = Object.assign({}, localsDefaults, locals);
Expand Down
12 changes: 12 additions & 0 deletions lib/engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ function () {
const generator = args.generator,
action = args.action,
actionfolder = args.actionfolder;

if (['-h', '--help'].includes(argv[0])) {
logger.log(`
Usage:
hygen [option] GENERATOR ACTION [--name NAME] [data-options]
Options:
-h, --help # Show this message and quit
--dry # Perform a dry run. Files will be generated but not saved.`);
process.exit(0);
}

logger.log(args.dry ? '(dry mode)' : '');

if (!generator) {
Expand Down
10 changes: 4 additions & 6 deletions lib/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@

const fs = require('fs');

const L = require('lodash');

const path = require('path');

const chalk = require('chalk');

const pkg = require('../package.json');

const availableActions = templates => {
const generators = L.filter(fs.readdirSync(templates), _ => fs.lstatSync(path.join(templates, _)).isDirectory());
return L.reduce(generators, (acc, generator) => {
const generators = fs.readdirSync(templates).filter(_ => fs.lstatSync(path.join(templates, _)).isDirectory());
return generators.reduce((acc, generator) => {
const actions = fs.readdirSync(path.join(templates, generator));
acc[generator] = actions;
return acc;
Expand Down Expand Up @@ -44,8 +42,8 @@ const printHelp = (templates, logger) => {
return;
}

L.each(availableActions(templates), (v, k) => {
logger.log(`${chalk.bold(k)}: ${v.join(', ')}`);
Object.entries(availableActions(templates)).forEach(([k, v]) => {
logger.log(chalk.bold(k) + ': ' + v.join(', '));
});
};

Expand Down
8 changes: 3 additions & 5 deletions lib/ops/injector.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d =

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

const L = require('lodash');

const injector = (action, content) => {
const _action$attributes = action.attributes,
skip_if = _action$attributes.skip_if,
Expand Down Expand Up @@ -40,11 +38,11 @@ const injector = (action, content) => {
};

const getPragmaticIndex = (pattern, lines, isBefore) => {
const oneLineMatchIndex = L.findIndex(lines, l => l.match(pattern));
const oneLineMatchIndex = lines.findIndex(l => l.match(pattern));

if (oneLineMatchIndex < 0) {
const fullText = lines.join('\n');
const fullMatch = fullText.match(new RegExp(pattern, "m"));
const fullMatch = fullText.match(new RegExp(pattern, 'm'));

if (fullMatch && fullMatch.length) {
if (isBefore) {
Expand All @@ -70,7 +68,7 @@ const locations = {
};

const indexByLocation = (attributes, lines) => {
const pair = L.find(L.toPairs(attributes), ([k, v]) => locations[k]);
const pair = Object.entries(attributes).find(([k, v]) => locations[k]);

if (pair) {
const _pair = _slicedToArray(pair, 2),
Expand Down
27 changes: 16 additions & 11 deletions lib/params.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"use strict";

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
Expand All @@ -12,8 +16,6 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

const L = require('lodash');

const path = require('path');

const yargs = require('yargs-parser');
Expand Down Expand Up @@ -42,23 +44,26 @@ function () {
};
}

const _L$split = L.split(action, ':'),
_L$split2 = _slicedToArray(_L$split, 2),
mainAction = _L$split2[0],
subaction = _L$split2[1];
const _action$split = action.split(':'),
_action$split2 = _slicedToArray(_action$split, 2),
mainAction = _action$split2[0],
subaction = _action$split2[1];

const actionfolder = path.join(templates, generator, mainAction);
const cleanArgs = Object.assign(L.omit(argv, ['_']), name && {
name
});
const promptArgs = yield prompt(createPrompter, actionfolder, cleanArgs);

const _ = argv._,
cleanArgv = _objectWithoutProperties(argv, ["_"]);

const promptArgs = yield prompt(createPrompter, actionfolder, cleanArgv);
const args = Object.assign({
templates,
actionfolder,
generator,
action,
subaction
}, promptArgs, cleanArgs);
}, promptArgs, cleanArgv, name && {
name
});
return args;
});

Expand Down
4 changes: 1 addition & 3 deletions lib/prompt.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@ const path = require('path');

const fs = require('fs');

const L = require('lodash');

const hooksfiles = ['prompt.js', 'index.js'];

const prompt = (createPrompter, actionfolder, args) => {
const hooksfile = L.first(L.filter(L.map(hooksfiles, f => path.resolve(path.join(actionfolder, f))), f => fs.existsSync(f)));
const hooksfile = hooksfiles.map(f => path.resolve(path.join(actionfolder, f))).find(f => fs.existsSync(f));

if (!hooksfile) {
return Promise.resolve({});
Expand Down
13 changes: 6 additions & 7 deletions lib/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

const L = require('lodash');

const fs = require('fs-extra');

const ejs = require('ejs');
Expand All @@ -21,13 +19,13 @@ const _require = require('path'),
// inline what we use here with the regular lodash.


const map = f => arr => L.map(arr, f);
const map = f => arr => arr.map(f);

const filter = f => arr => L.filter(arr, f);
const filter = f => arr => arr.filter(f);

const ignores = ['prompt.js', 'index.js'];

const renderTemplate = (tmpl, locals, config) => L.isString(tmpl) ? ejs.render(tmpl, context(locals, config)) : tmpl;
const renderTemplate = (tmpl, locals, config) => typeof tmpl === 'string' ? ejs.render(tmpl, context(locals, config)) : tmpl;

function getFiles(_x) {
return _getFiles.apply(this, arguments);
Expand Down Expand Up @@ -58,7 +56,8 @@ const render =
function () {
var _ref = _asyncToGenerator(function* (args, config) {
return yield getFiles(args.actionfolder).then(things => things.sort((a, b) => a.localeCompare(b))) // TODO: add a test to verify this sort
.then(filter(f => !L.find(ignores, ig => L.endsWith(f, ig)))) // TODO: add a test for ignoring prompt.js and index.js
.then(filter(f => !ignores.find(ig => f.endsWith(ig)))) // TODO: add a
// test for ignoring prompt.js and index.js
.then(filter(file => args.subaction ? file.match(args.subaction) : true)).then(map(file => fs.readFile(file).then(text => ({
file,
text: text.toString()
Expand All @@ -73,7 +72,7 @@ function () {
body
}) => ({
file,
attributes: L.mapValues(attributes, _ => renderTemplate(_, args, config)),
attributes: Object.entries(attributes).reduce((obj, [key, value]) => (obj[key] = renderTemplate(value, args, config)) && obj, {}),
body: renderTemplate(body, args, config)
})));
});
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
"front-matter": "^2.3.0",
"fs-extra": "^7.0.1",
"inflection": "^1.12.0",
"lodash": "^4.17.11",
"yargs-parser": "^13.0.0"
},
"devDependencies": {
Expand Down Expand Up @@ -80,4 +79,4 @@
"redux",
"react"
]
}
}
Loading

0 comments on commit 3d63fc5

Please sign in to comment.