-
Notifications
You must be signed in to change notification settings - Fork 0
/
reducer-maker.js
executable file
·196 lines (167 loc) · 6.54 KB
/
reducer-maker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/usr/bin/env node
const ff = require('node-find-folder');
const fs = require('fs');
const mkdirp = require('mkdirp');
const pluralize = require('pluralize');
const getopt = require('node-getopt');
const pjson = require('./package.json');
const _ = require('lodash');
const Mustache = require('mustache');
const program = process.argv[1].split("/").pop();
var args = new getopt([
['r' , 'reducer=REDUCER+', 'Specify what reducer generate (CRUD)'],
['', 'file=FILE+', 'Specify what file generate (actions, constants, reducers and states)'],
['s' , 'state=JSON', 'Path to file with initial state in json format'],
['i', 'inline-json=JSON', 'Specify inline json'],
['f', 'force', 'Force the execution'],
['w', 'workingdir=WD', 'Change working directory'],
['', 'root=ROOT', 'Specify root directory for requires/imports'],
['', 'examples', 'Show path to examples'],
['', 'actions-suffix=SUFFIX', 'Change action file suffix'],
['', 'constants-suffix=SUFFIX', 'Change constants file suffix'],
['', 'reducers-suffix=SUFFIX', 'Change reducers file suffix'],
['', 'states-suffix=SUFFIX', 'Change states file suffix'],
]);
args.setHelp(
`Usage: node ${program} [OPTION]
[[OPTIONS]]
Npm: https:\/\/www.npmjs.com/package/${pjson.name}
Respository: ${pjson.homepage}
License: ${pjson.license}
Version: ${pjson.version}`
)
.bindHelp()
.parseSystem();
if (args.options['state'] && args.options['inline-json']) {
console.error('You must specify --state or --inline-json, not both');
process.exit(1);
}
// Check for flag '--examples'
if (args.options['examples']) {
console.log(`${process.cwd()}/examples`);
process.exit(0);
}
// Check for reducers
if (!args.options['reducer']) {
reducers = {
add: true,
read: true,
list: true,
update: true,
delete: true,
};
} else {
reducers = {};
args.options['reducer'].forEach((elem) => reducers[elem] = true);
}
// Check for state file
var state = {};
if (args.options['state'] || args.options['inline-json']) {
try {
const stateFile = args.options['state'] ?
fs.readFileSync(args.options['state'], { encoding: 'utf8'}) :
args.options['inline-json'];
state = JSON.parse(stateFile);
} catch(err) {
console.error(`Error: can\'t set state - You can set default value using --force`);
!args.options['force'] && process.exit(1);
console.error("Set state by default\n");
}
}
// Check for workdir
var workingdir = "";
if (args.options['workingdir']) {
workingdir = args.options['workingdir'];
if (workingdir.slice(-1) !== "/") {
workingdir += "/";
}
if (!fs.existsSync(workingdir)) {
mkdirp.sync(workingdir, function (err) {
if (err) console.error(err);
});
}
process.chdir(workingdir);
}
// Set initial reducersNames
const reducersNames = {
actions: workingdir,
constants: workingdir,
reducers: workingdir,
states: workingdir,
};
if (args.options['file']) {
let validFiles = Object.keys(reducersNames);
console.info(validFiles);
validFiles = validFiles.filter(reducerName => !args.options['file'].includes(reducerName));
validFiles.forEach(elem => delete reducersNames[elem]);
}
// Set reducers suffixes
const reducersSuffix = {
actions: args.options['actions-suffix'] || "-actions",
constants: args.options['constants-suffix'] || ".constants",
reducers: args.options['reducers-suffix'] || "",
states: args.options['states-suffix'] || "-state",
}
function scanDirectory() {
console.log("Scanning filesystem...\n");
Object.keys(reducersNames).forEach(function(reducer) {
console.log(`Searching ${reducer} directory`);
ff_result = new ff(reducer, { nottraversal: ['dist'] });
// No reducer directory found
if (ff_result.length == 0) {
console.log(`${reducer} not found`);
reducersNames[reducer] += reducer;
console.log(`Directory setted to ${reducersNames[reducer]}\n`);
} else {
reducersNames[reducer] += ff_result[0];
console.log(`${reducer} found at '${reducersNames[reducer]}'\n`);
}
reducersNames[reducer] += '/';
});
}
function makeReducers(reducerFullName) {
Object.keys(reducersNames).forEach(function(reducer) {
let reducerSplit = reducerFullName.split("/");
let reducerName = reducerSplit[0];
let moduleName = reducerSplit[1] ? reducerSplit[1] : reducerSplit[0] ;
let reducerDir = `${reducersNames[reducer].replace(workingdir, "")}${pluralize.plural(reducerName)}-${reducer}/`;
reducerFullName = pluralize.plural(reducerFullName);
let fileName = `${pluralize.plural(moduleName)}${reducersSuffix[reducer]}.js`;
let file = `${reducerDir}${fileName}`;
let initState = state[reducerFullName] ? state[reducerFullName] : state[pluralize.singular(reducerFullName)];
let indent = ' ';
let data = {
reducerNamePluralU: pluralize.plural(reducerName).toUpperCase(),
reducerNameSingularU: pluralize.singular(reducerName).toUpperCase(),
reducerNameSingularC: _.camelCase(pluralize.singular(reducerName)),
reducerNameSingularCC: _.upperFirst(_.camelCase(pluralize.singular(reducerName))),
moduleNamePluralU: pluralize.plural(moduleName).toUpperCase(),
moduleNameSingularU: pluralize.singular(moduleName).toUpperCase(),
moduleNameSingularC: _.camelCase(pluralize.singular(moduleName)),
moduleNameSingularCC: _.upperFirst(_.camelCase(pluralize.singular(moduleName))),
moduleNamePluralC: _.camelCase(pluralize.plural(moduleName)),
moduleNamePluralCC: _.upperFirst(_.camelCase(pluralize.plural(moduleName))),
directoryBase: args.options['root'] ? args.options['root'] : reducersNames[reducer],
state: Object.keys(initState || {}).map ( field => `${indent}${field}: ${JSON.stringify(initState[field])},`).join("\n"),
fields: Object.keys(initState || {}).map( field => `${indent}${field}: ${JSON.stringify(initState[field])},\n${indent}${field}HasError: false,\n${indent}${field}ErrorMsg:"",`).join("\n"),
reducers,
};
mkdirp.sync(reducerDir, function (err) {
if (err) throw new Error(`Error creating directory ${reducersNames[reducer]}`);
});
if (fs.existsSync(file) && !args.options['f']) {
throw new Error(`Reducers already exists (${file}) - You can force using the flag --force`)
} else {
let template = fs.readFileSync(`templates/${reducer}`, 'utf8');
finalFile = Mustache.render(template, data);
fs.writeFileSync(file, finalFile);
console.log(`Created file ${reducersNames[reducer]}${fileName}`);
}
});
}
scanDirectory();
try {
args.argv.forEach(makeReducers);
} catch(err) {
console.log(err.message)
}