1 | const includes = require('lodash/includes');
|
2 | const map = require('lodash/map');
|
3 | const each = require('lodash/each');
|
4 | const { singular } = require('pluralize');
|
5 |
|
6 | const error = require('../error');
|
7 | const instRegistry = require('./instRegistry');
|
8 |
|
9 | const 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 |
|
24 | const toSingularInstName = (name) => {
|
25 | const specialCommandNames = { 'keepDirectoriesInGit': 'keepDirectoryInGit' };
|
26 | return specialCommandNames[name] || singular(name);
|
27 | };
|
28 |
|
29 | const isSingleCommand = (command) => {
|
30 | return includes(knownInstructions, Object.keys(command)[0]);
|
31 | };
|
32 |
|
33 | const isArrayCommand = (command) => {
|
34 | return includes(
|
35 | knownInstructions,
|
36 | toSingularInstName(Object.keys(command)[0])
|
37 | );
|
38 | };
|
39 |
|
40 | const separateArrayCommand = (command) => {
|
41 | const pluralName = Object.keys(command)[0];
|
42 | return map(command[pluralName], (c) => ({ [singular(pluralName)]: c }));
|
43 | };
|
44 |
|
45 | const throwCommand = (command) => {
|
46 | throw error(`Invalid command: ${JSON.stringify(command, null, 2)}`);
|
47 | };
|
48 |
|
49 |
|
50 | const 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 |
|
61 | const 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 |
|
76 | module.exports = pushInstruction;
|