UNPKG

1.98 kBJavaScriptView Raw
1const includes = require('lodash/includes');
2const map = require('lodash/map');
3const each = require('lodash/each');
4const { singular } = require('pluralize');
5
6const error = require('../error');
7const instRegistry = require('./instRegistry');
8
9const knownInstructions = [
10 'createFile',
11 'deleteFile',
12 'appendFile',
13 'detachFromFile',
14 'updateFile',
15 'rollbackFile',
16 'updateJSONFile',
17 'rollbackJSONFile',
18 'installDependency',
19 'removeDependency',
20 'runShellCommand',
21 'keepDirectoryInGit'
22];
23
24const toSingularInstName = (name) => {
25 const specialCommandNames = { 'keepDirectoriesInGit': 'keepDirectoryInGit' };
26 return specialCommandNames[name] || singular(name);
27};
28
29const isSingleCommand = (command) => {
30 return includes(knownInstructions, Object.keys(command)[0]);
31};
32
33const isArrayCommand = (command) => {
34 return includes(
35 knownInstructions,
36 toSingularInstName(Object.keys(command)[0])
37 );
38};
39
40const separateArrayCommand = (command) => {
41 const pluralName = Object.keys(command)[0];
42 return map(command[pluralName], (c) => ({ [singular(pluralName)]: c }));
43};
44
45const throwCommand = (command) => {
46 throw error(`Invalid command: ${JSON.stringify(command, null, 2)}`);
47};
48
49// Only check if command is exist yet.
50const validateCommand = (command) => {
51 if (Object.keys(command).length !== 1) {
52 throwCommand(command);
53 }
54 if (!isSingleCommand(command)) {
55 if (!isArrayCommand(command)) {
56 throw `Invalid command: ${JSON.stringify(command, null, 2)}`;
57 }
58 }
59};
60
61const pushInstruction = (command) => {
62 validateCommand(command);
63 if (isSingleCommand(command)) {
64 const name = Object.keys(command)[0];
65 const params = command[name];
66 instRegistry.push(name, params);
67 } else if (isArrayCommand(command)) {
68 each(separateArrayCommand(command), (c) => {
69 const name = Object.keys(c)[0];
70 const params = c[name];
71 instRegistry.push(name, params);
72 });
73 }
74};
75
76module.exports = pushInstruction;