@actionforest/taskrunner
Version:
ActionForest taskrunner in Pomegranate
282 lines (274 loc) • 13.2 kB
JavaScript
;
/**
* @file TaskReciever
* @author Jim Bulkowski <jim.b@paperelectron.com>
* @project taskrunner
* @license MIT {@link http://opensource.org/licenses/MIT}
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const plugin_tools_1 = require("@pomegranate/plugin-tools");
const fp_1 = require("lodash/fp");
const actiontrees_1 = require("actiontrees");
const tsActionGenerator = `// Generated by the Pomegranate cli on {{creationDate}}
// Action: {{name}}
import {Task} from 'actiontrees'
export const Action = (PluginLogger): Task => {
return {
config: {
name: '{{name}}',
initial: '{{transition}}',
// Internal default values below.
//retryOnError: false,
//retryDelay: 1000,
//delayMultiplier: 1.5,
//retryLimit: 1,
//abstractHandlers: []
},
/*
* transitions prop can be populated here, additionally Pom will
* autoload and merge with functions from ./transitions
*/
transitions: {}
}
}
`;
const tsTransitionGenerator = `// Generated by the Pomegranate cli on {{creationDate}}
// Action: {{name}}
// Transition: {{transition}}
export const Transition = (PluginLogger) => {
return (State, taskController) => {
return [{to: 'done'}, State]
}
}
`;
const tsAbstractGenerator = `// Generated by the Pomegranate cli on {{creationDate}}
// AbstractTransition: {{name}}
export const Abstract = (PluginLogger) => {
return (State, taskController) => {
return [{to: 'done'}, State]
}
}
`;
exports.ActionTrees = plugin_tools_1.CreatePlugin('anything')
.configuration({
name: 'ActionTree',
injectableParam: 'ActionTree',
depends: ['@pomofficial/RabbitMQ', '@pomofficial/KnexDAO']
})
.variables({
infoLogging: false,
debugLogging: false,
tablePrefix: 'actiontree'
})
.directories(['actions', 'abstract'])
.hooks({
load: (Injector, PluginVariables, PluginFiles, PluginLogger, Knex, SQL, RabbitMQ) => __awaiter(this, void 0, void 0, function* () {
let storage = new actiontrees_1.PGStore(Knex, PluginVariables.tablePrefix);
let Trees = new actiontrees_1.ActionTree(storage, {
debugLogging: PluginVariables.debugLogging,
infoLogging: PluginVariables.infoLogging,
logger: PluginLogger
});
let abstractTransitions = yield PluginFiles('abstract').fileList({ ext: '.js' });
let actionDirs = yield PluginFiles('actions').fileList({ directories: true });
let buildTransitions = fp_1.map((dirPath) => {
let required = require(dirPath.path);
let fileName = dirPath.filename;
let baseName = dirPath.getBaseName();
let M = fp_1.get('Transition', required);
if (!M) {
throw new Error(`Action/transitions/${fileName} does not contain an export on the Transition property.`);
}
if (!fp_1.isFunction(M)) {
throw new Error(`Action/transitions/${fileName} does not export an injectable function on the Transition property.`);
}
let injected = Injector.inject(M);
return [baseName, injected];
});
let findTransitions = (dirPath) => __awaiter(this, void 0, void 0, function* () {
let transitionDir = PluginFiles('actions').join(dirPath.path, 'transitions');
let findTransitions = PluginFiles('actions').ctors.fileList(transitionDir);
let transitions = yield findTransitions({ ext: '.js' });
return fp_1.fromPairs(buildTransitions(transitions));
});
fp_1.each(([name, abstractTransition]) => {
Trees.registerAbstract(name, abstractTransition);
}, fp_1.map((dirPath) => {
let required = require(dirPath.path);
let fileName = dirPath.getBaseName();
PluginLogger.log(`Found Abstract Transition : ${fileName}.`, 2);
let M = fp_1.get('Abstract', required);
if (!M) {
throw new Error(`${fileName} does not contain an export on the Abstract property.`);
}
if (!fp_1.isFunction(M)) {
throw new Error(`${fileName} does not export an injectable function on the Abstract property.`);
}
return [fileName, Injector.inject(M)];
}, abstractTransitions));
fp_1.each((task) => __awaiter(this, void 0, void 0, function* () {
let t = yield task;
Trees.registerTask(t);
}), fp_1.map((dirPath) => __awaiter(this, void 0, void 0, function* () {
let required = require(dirPath.path);
let fileName = dirPath.filename;
PluginLogger.log(`Found Task Directory: ${fileName}.`, 2);
let M = fp_1.get('Action', required);
if (!M) {
throw new Error(`Action/index ${fileName} does not contain an export on the Action property.`);
}
if (!fp_1.isFunction(M)) {
throw new Error(`Action/index ${fileName} does not export an injectable function on the Action property.`);
}
let action = Injector.inject(M);
let transitions = yield findTransitions(dirPath);
let allTransitions = fp_1.merge(transitions, fp_1.getOr({}, 'transitions', action));
return fp_1.set('transitions', allTransitions, action);
}), actionDirs));
return Trees;
})
})
.commands((PomConfig, PluginVariables, PluginFiles, PluginPickDirectory, Handlebars) => {
return (yargs) => {
return yargs
.usage('usage: $0')
.command({
command: 'generate',
aliases: 'g',
describe: 'Generates ActionTree resources',
builder: (yargs) => {
return yargs
.command({
command: 'action <name> <transition>',
aliases: 'a',
describe: `Generates Action directory and files at <name> with <transition> transition.
If the <action> doesnt exists, <transition> will be added as its inititial transition.
`,
builder: (yargs) => {
return yargs
.positional('name', {
describe: 'The name of the Action to create, or add to.',
type: 'string'
})
.positional('transition', {
describe: 'The name of the transition to create',
type: 'string'
});
},
handler: (argv) => __awaiter(this, void 0, void 0, function* () {
let Pf = PluginFiles('actions');
let indexPath = Pf.join(argv.name, 'index.ts');
let transitionPath = Pf.join(argv.name, 'transitions', `${argv.transition}.ts`);
let actionExists = yield Pf.projectFileExists(indexPath);
let transitionExists = yield Pf.projectFileExists(transitionPath);
if (!actionExists && !argv.force) {
let compileAction = Handlebars.compile(tsActionGenerator);
let compiledAction = compileAction({
creationDate: new Date().toDateString(),
name: argv.name,
transition: argv.transition
});
yield Pf.outputProjectFile(indexPath, compiledAction);
console.log(`Created @actionforest/ActionTree at ${indexPath}`);
}
if (!transitionExists) {
let compileTransition = Handlebars.compile(tsTransitionGenerator);
let compiledTransition = compileTransition({
creationDate: new Date().toDateString(),
name: argv.name,
transition: argv.transition
});
yield Pf.outputProjectFile(transitionPath, compiledTransition);
console.log(`Created @actionforest/ActionTree Transition ${argv.transition} at ${transitionPath}`);
return;
}
else {
console.log(`ActionTree ${argv.name}, Transition ${argv.transition} at ${transitionPath} already exists`);
}
})
})
.command({
command: 'abstract <name>',
aliases: 'abs',
describe: `Generates abstract handler <name>.`,
builder: (yargs) => {
return yargs
.positional('name', {
describe: 'The name of the abstract handler to create',
type: 'string'
})
.option('force', {
alias: 'f',
default: false,
describe: 'overwrites the specified file if it exists.',
type: 'boolean'
});
},
handler: (argv) => __awaiter(this, void 0, void 0, function* () {
let Pf = PluginFiles('abstract');
let abstractPath = Pf.join(`${argv.name}.ts`);
let abstractExists = yield Pf.projectFileExists(abstractPath);
if (abstractExists && !argv.force) {
throw new Error(`${abstractPath} \nexists, \nrerun with -f to overwrite.`);
}
let compileAbstract = Handlebars.compile(tsAbstractGenerator);
let compiledAbstract = compileAbstract({
creationDate: new Date().toDateString(),
name: argv.name,
});
yield Pf.outputProjectFile(abstractPath, compiledAbstract);
console.log(`Created @actionforest/ActionTree Transition ${argv.name} at ${abstractPath}`);
})
})
.command({
command: 'migrations <type>',
aliases: 'm',
describe: `Generates Knex migration files.`,
builder: (yargs) => {
return yargs
.positional('type', {
describe: 'The database type to generate migrations for.',
type: 'string'
})
.option('force', {
alias: 'f',
default: false,
describe: 'overwrites the specified file if it exists.',
type: 'boolean'
});
},
handler: (argv) => __awaiter(this, void 0, void 0, function* () {
let prefix = PluginVariables.tablePrefix;
let MigrationTmplt = actiontrees_1.PgMigrationTemplate(prefix);
let compileTmplt = Handlebars.compile(MigrationTmplt);
let compiledMigration = compileTmplt({ tablePrefix: prefix });
let filename = `${prefix}_cli_migration.js`;
return PluginPickDirectory('@pomofficial/KnexClient', 'migrations')
.outputProjectFile(filename, compiledMigration)
.then((result) => {
console.log(`${filename} migration file created
Run
pom p @pomofficial/knexclient migrate latest
to apply it
`);
});
})
})
.help();
},
handler: () => {
yargs.showHelp();
}
})
.help();
};
});
//# sourceMappingURL=ActionTrees.js.map