-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.ts
339 lines (301 loc) · 12.6 KB
/
generate.ts
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.generate/licenses/BSD-3-Clause
*/
import * as os from "os";
import { readFileSync, existsSync, writeFileSync } from "fs";
import { flags, SfdxCommand } from "@salesforce/command";
import { Messages, SfError } from "@salesforce/core";
import { AnyJson } from "@salesforce/ts-types";
import { join } from "path";
//@ts-ignore
import * as ConfigData from "../../../../src_config/metadata_profile_generate.json";
// Initialize Messages with the current plugin directory
Messages.importMessagesDirectory(__dirname);
// Load the specific messages for this file. Messages from @salesforce/command, @salesforce/core,
// or any library that is using the messages framework can also be loaded this way.
const messages = Messages.loadMessages("sfdx-metadata-generator", "metadata_profile_generate");
export default class generate extends SfdxCommand {
public static description = messages.getMessage("commandDescription");
public static examples = messages.getMessage("examples").split(os.EOL);
public static args = [{ name: "file" }];
protected static flagsConfig = {
// flag with a value (-n, --name=VALUE)
input: flags.string({
char: "i",
description: messages.getMessage("inputFlagDescription"),
}),
outputdir: flags.string({
char: "o",
description: messages.getMessage("outputdirFlagDescription"),
}),
source: flags.string({
char: "s",
description: messages.getMessage("sourceFlagDescription"),
}),
delimiter: flags.string({
char: "d",
description: messages.getMessage("delimiterFlagDescription"),
}),
};
// Comment this out if your command does not require an generate username
protected static requiresUsername = false;
// Comment this out if your command does not support a hub generate username
protected static supportsDevhubUsername = false;
// Set this to true if your command requires a project workspace; 'requiresProject' is false by default
protected static requiresProject = false;
private static delimiter = ConfigData.delimiter;
private static permissionTags = ConfigData.permissionTags;
private static options = ConfigData.options;
private static validationResults = [];
// cache
private static permissionMetaStrs = {};
public async run(): Promise<AnyJson> {
if (!existsSync(this.flags.input)) {
throw new SfError(messages.getMessage("errorPathOfInput") + this.flags.input);
}
if (!existsSync(this.flags.outputdir)) {
throw new SfError(messages.getMessage("errorPathOfOutput") + this.flags.outputdir);
}
if (!existsSync(this.flags.source)) {
throw new SfError(messages.getMessage("errorPathOfSource") + this.flags.source);
}
if (this.flags.delimiter === undefined) {
this.flags.delimiter = generate.delimiter;
}
const csv = readFileSync(this.flags.input, {
encoding: "utf8",
})
.toString()
.split("\n")
.map((e) => e.trim())
.map((e) => e.split(",").map((e) => e.trim()));
const header = csv[0];
let metastr = readFileSync(this.flags.source, { encoding: "utf8" });
for (let rowIndex = 1; rowIndex < csv.length; rowIndex++) {
if (csv[rowIndex].length < header.length) {
continue;
}
//generates metadata for each row
metastr = this.getMetaStr(metastr, csv, rowIndex, header);
}
if (generate.validationResults.length > 0) {
this.showValidationErrorMessages();
} else {
this.saveMetaData(metastr);
}
// Return an object to be displayed with --json*/
return { input: this.flags.input };
}
private getMetaStr(metastr: string, csv: string[][], rowIndex: number, header: string[]): string {
let row = csv[rowIndex];
const indexOfFullName = header.indexOf("fullName");
const indexOfType = header.indexOf("type");
const fullName = row[indexOfFullName];
const type = row[indexOfType];
for (const tag of generate.permissionTags[type]["tags"]) {
const indexOfTag = header.indexOf(tag);
const keyTag = generate.permissionTags[type]["keyTag"];
// dose not include tag at the header
if (indexOfTag === -1) {
continue;
}
//validates inputs
if (!this.isValidInputs(tag, row, header, rowIndex)) {
continue;
}
if (generate.permissionTags[type][tag] === null) {
continue;
}
if (!generate.permissionMetaStrs[fullName]) {
this.extractMetaStrsForEachKeyTag(metastr, type, keyTag);
}
this.formatBoolean(tag, row, indexOfTag);
const permissionStr = "<" + tag + ">" + row[indexOfTag] + "</" + tag + ">";
const permissionRegexp = new RegExp("<" + tag + ">(.+)<\\/" + tag + ">");
const newPermMetaStr = generate.permissionMetaStrs[fullName].replace(permissionRegexp, permissionStr);
metastr = metastr.replace(generate.permissionMetaStrs[fullName], newPermMetaStr);
generate.permissionMetaStrs[fullName] = newPermMetaStr;
}
return metastr;
}
private extractMetaStrsForEachKeyTag(metastr: string, type: string, keyTag: string) {
const regexp = new RegExp("<" + type + ">");
let tagMetastrs = metastr.split(regexp);
for (const tagMetastr of tagMetastrs) {
const keyTagRegexp = new RegExp("<" + keyTag + ">(.+)*" + "\\</" + keyTag + ">");
const fullNameValue = tagMetastr.match(keyTagRegexp);
if (fullNameValue === null) {
continue;
}
generate.permissionMetaStrs[fullNameValue[1]] = tagMetastr;
}
}
private formatBoolean(tag: string, row: string[], indexOfTag: number) {
if (generate.options[tag] !== undefined) {
if (generate.options[tag].includes(true.toString()) && generate.options[tag].includes(false.toString())) {
row[indexOfTag] = row[indexOfTag].toLowerCase();
}
}
}
private isValidInputs(tag: string, row: string[], header: string[], rowIndex: number): boolean {
const indexOfType = header.indexOf("type");
const type = row[indexOfType];
const indexOfTag = header.indexOf(tag);
const validationResLenBefore = generate.validationResults.length;
const errorIndex = "Row" + (rowIndex + 1) + "Col" + (indexOfTag + 1);
switch (tag) {
case "editable":
if (type === "fieldPermissions") {
if (!generate.options.editable.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationEditableOptions"));
}
}
break;
case "readable":
if (type === "fieldPermissions") {
if (!generate.options.readable.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationReadableOptions"));
}
}
break;
case "allowCreate":
if (type === "objectPermissions") {
if (!generate.options.allowCreate.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationAllowCreateOptions"));
}
}
break;
case "allowDelete":
if (type === "objectPermissions") {
if (!generate.options.allowDelete.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationAllowDeleteOptions"));
}
}
break;
case "allowEdit":
if (type === "objectPermissions") {
if (!generate.options.allowEdit.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationAllowEditOptions"));
}
}
break;
case "allowRead":
if (type === "objectPermissions") {
if (!generate.options.allowRead.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationAllowReadOptions"));
}
}
break;
case "modifyAllRecords":
if (type === "objectPermissions") {
if (!generate.options.modifyAllRecords.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationModifyAllRecordsOptions"));
}
}
break;
case "viewAllRecords":
if (type === "objectPermissions") {
if (!generate.options.viewAllRecords.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationViewAllRecordsOptions"));
}
}
break;
case "default":
if (type === "permissionTags" || type === "recordTypeVisibilities" || type === "applicationVisibilities") {
if (!generate.options.default.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationDefaultOptions"));
}
}
break;
case "visible":
if (type === "permissionTags" || type === "recordTypeVisibilities" || type === "applicationVisibilities") {
if (!generate.options.visible.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationVisibleOptions"));
}
}
break;
case "enabled":
if (type === "classAccesses" || type === "userPermissions" || type === "pageAccesses") {
if (!generate.options.enabled.includes(row[indexOfTag].toLowerCase()) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationEnabledOptions"));
}
}
break;
case "visibility":
if (type === "tabVisibilities") {
if (!generate.options.visibility.includes(row[indexOfTag]) && row[indexOfTag] !== "") {
this.pushValidationResult(errorIndex, messages.getMessage("validationVisibilityOptions") + generate.options.visibility.toString());
}
}
break;
}
return validationResLenBefore == generate.validationResults.length;
}
private pushValidationResult(index: string, errorMessage: string) {
generate.validationResults.push({ INDEX: index, PROBLEM: errorMessage });
}
private saveMetaData(metastr: string) {
const blue = "\u001b[34m";
const white = "\u001b[37m";
console.log("===" + blue + " Generated Source" + white);
const dirsToSource = this.flags.source.split("/");
if (!existsSync(join(this.flags.outputdir, dirsToSource[dirsToSource.length - 1]))) {
writeFileSync(join(this.flags.outputdir, dirsToSource[dirsToSource.length - 1]), metastr, "utf8");
}
console.log(
"Successfully saved " + dirsToSource[dirsToSource.length - 1] + " in " + join(this.flags.outputdir, dirsToSource[dirsToSource.length - 1])
);
}
private showValidationErrorMessages() {
const logLengths = this.getLogLenghts(generate.validationResults);
this.showLogHeader(logLengths);
this.showLogBody(generate.validationResults, logLengths);
throw new SfError(messages.getMessage("validation"));
}
private getLogLenghts(logs: any[]) {
let logLengths = {};
for (const log of logs) {
for (const logName in log) {
if (logLengths[logName] < log[logName].length || logLengths[logName] === undefined) {
logLengths[logName] = log[logName].length;
}
}
}
return logLengths;
}
private showLogHeader(logLengths: any) {
let header = "";
let line = "";
const whiteSpace = " ";
const lineChar = "─";
let counter = 0;
for (const logName in logLengths) {
counter++;
header += logName;
if (counter < Object.keys(logLengths).length) {
header += whiteSpace.repeat(logLengths[logName] - logName.length) + "\t";
}
line += lineChar.repeat(logLengths[logName]) + "\t";
}
console.log(header);
console.log(line);
}
private showLogBody(logs: any[], logLengths: any) {
const whiteSpace = " ";
for (const log of logs) {
let logMessage = "";
let counter = 0;
for (const logName in log) {
counter++;
logMessage += log[logName];
if (counter < Object.keys(log).length) {
logMessage += whiteSpace.repeat(logLengths[logName] - log[logName].length) + "\t";
}
}
console.log(logMessage);
}
}
}