-
Notifications
You must be signed in to change notification settings - Fork 20
/
nginxbeautifier.js
381 lines (345 loc) · 12.4 KB
/
nginxbeautifier.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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/**
* Ported by Yosef on 24/08/2016.
* from project:
* https://github.com/1connect/nginx-config-formatter
* from file:
* nginxfmt.py
*
*/
/**
POLYFILLS START
not required in nodejs
*/
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
if (!String.prototype.includes) {
String.prototype.includes = function (search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
}
else {
return this.indexOf(search, start) !== -1;
}
};
}
if (!String.prototype.repeat) {
String.prototype.repeat = function (count) {
'use strict';
if (this == null) {
throw new TypeError('can\'t convert ' + this + ' to object');
}
var str = '' + this;
count = +count;
if (count != count) {
count = 0;
}
if (count < 0) {
throw new RangeError('repeat count must be non-negative');
}
if (count == Infinity) {
throw new RangeError('repeat count must be less than infinity');
}
count = Math.floor(count);
if (str.length == 0 || count == 0) {
return '';
}
// Ensuring count is a 31-bit integer allows us to heavily optimize the
// main part. But anyway, most current (August 2014) browsers can't handle
// strings 1 << 28 chars or longer, so:
if (str.length * count >= 1 << 28) {
throw new RangeError('repeat count must not overflow maximum string size');
}
var rpt = '';
for (; ;) {
if ((count & 1) == 1) {
rpt += str;
}
count >>>= 1;
if (count == 0) {
break;
}
str += str;
}
// Could we try:
// return Array(count + 1).join(this);
return rpt;
}
}
//required in nodejs
//removes element from array
if (!Array.prototype.remove) {
Array.prototype.remove = function (index, item) {
this.splice(index, 1);
};
}
if (!String.prototype.contains) {
String.prototype.contains = String.prototype.includes;
}
if (!Array.prototype.insert) {
Array.prototype.insert = function (index, item) {
this.splice(index, 0, item);
};
}
/**
* POLYFILLS end
*
*
*/
/**
* Grabs text in between two seperators seperator1 thetextIwant seperator2
* @param {string} input String to seperate
* @param {string} seperator1 The first seperator to use
* @param {string} seperator2 The second seperator to use
* @return {string}
*/
function extractTextBySeperator(input, seperator1, seperator2) {
if (seperator2 == undefined)
seperator2 = seperator1;
var seperator1Regex = new RegExp(seperator1);
var seperator2Regex = new RegExp(seperator2);
var catchRegex = new RegExp(seperator1 + "(.*?)" + seperator2);
if (seperator1Regex.test(input) && seperator2Regex.test(input)) {
return input.match(catchRegex)[1];
}
else {
return "";
}
}
/**
* Grabs text in between two seperators seperator1 thetextIwant seperator2
* @param {string} input String to seperate
* @param {string} seperator1 The first seperator to use
* @param {string} seperator2 The second seperator to use
* @return {object}
*/
function extractAllPossibleText(input, seperator1, seperator2) {
if (seperator2 == undefined)
seperator2 = seperator1;
var extracted = {};
var textInBetween;
var cnt = 0;
var seperator1CharCode = seperator1.length > 0 ? seperator1.charCodeAt(0) : "";
var seperator2CharCode = seperator2.length > 0 ? seperator2.charCodeAt(0) : "";
while ((textInBetween = extractTextBySeperator(input, seperator1, seperator2)) != "") {
var placeHolder = "#$#%#$#placeholder" + cnt + "" + seperator1CharCode + "" + seperator2CharCode + "#$#%#$#";
extracted[placeHolder] = seperator1 + textInBetween + seperator2;
input = input.replace(extracted[placeHolder], placeHolder);
cnt++;
}
return {
filteredInput: input,
extracted: extracted,
getRestored: function () {
var textToFix = this.filteredInput;
for (var key in extracted) {
textToFix = textToFix.replace(key, extracted[key]);
}
return textToFix;
}
};
}
/**
* @param {string} single_line the whole nginx config
* @return {string} stripped out string without multi spaces
*/
function strip_line(single_line) {
//"""Strips the line and replaces neighbouring whitespaces with single space (except when within quotation marks)."""
//trim the line before and after
var trimmed = single_line.trim();
//get text without any quatation marks(text foudn with quatation marks is replaced with a placeholder)
var removedDoubleQuatations = extractAllPossibleText(trimmed, '"', '"');
//replace multi spaces with single spaces, but skip in sub_filter directive
if (!removedDoubleQuatations.filteredInput.includes('sub_filter')) {
removedDoubleQuatations.filteredInput = removedDoubleQuatations.filteredInput.replace(/\s\s+/g, ' ');
}
//restore anything of quatation marks
return removedDoubleQuatations.getRestored();
}
/**
* @param {string} configContents the whole nginx config
*/
function clean_lines(configContents) {
var splittedByLines = configContents.split(/\r\n|\r|\n/g);
//put { } on their own seperate lines
//trim the spaces before and after each line
//trim multi spaces into single spaces
//trim multi lines into two
for (var index = 0, newline = 0; index < splittedByLines.length; index++) {
splittedByLines[index] = splittedByLines[index].trim();
if (!splittedByLines[index].startsWith("#") && splittedByLines[index] != "") {
newline = 0;
var line = splittedByLines[index] = strip_line(splittedByLines[index]);
if (line != "}" && line != "{" && !(line.includes("('{") || line.includes("}')") || line.includes("'{'") || line.includes("'}'"))) {
var startOfComment = line.indexOf("#");
var comment = startOfComment >= 0 ? line.slice(startOfComment) : "";
var code = startOfComment >= 0 ? line.slice(0, startOfComment) : line;
var removedDoubleQuatations = extractAllPossibleText(code, '"', '"');
code = removedDoubleQuatations.filteredInput;
var startOfParanthesis = code.indexOf("}");
if (startOfParanthesis >= 0) {
if (startOfParanthesis > 0) {
splittedByLines[index] = strip_line(code.slice(0, startOfParanthesis - 1));
splittedByLines.insert(index + 1, "}");
}
var l2 = strip_line(code.slice(startOfParanthesis + 1));
if (l2 != "")
splittedByLines.insert(index + 2, l2);
code = splittedByLines[index];
}
var endOfParanthesis = code.indexOf("{");
if (endOfParanthesis >= 0) {
splittedByLines[index] = strip_line(code.slice(0, endOfParanthesis));
splittedByLines.insert(index + 1, "{");
var l2 = strip_line(code.slice(endOfParanthesis + 1));
if (l2 != "")
splittedByLines.insert(index + 2, l2);
}
removedDoubleQuatations.filteredInput = splittedByLines[index];
line = removedDoubleQuatations.getRestored();
splittedByLines[index] = line;
}
}
//remove more than two newlines
else if (splittedByLines[index] == "") {
if (newline++ >= 2) {
//while(splittedByLines[index]=="")
splittedByLines.splice(index, 1);
index--;
}
}
}
return splittedByLines;
}
function join_opening_bracket(lines) {
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line == "{") {
//just make sure we don't put anything before 0
if (i >= 1) {
lines[i] = lines[i - 1] + " {";
if (options.trailingBlankLines && lines.length > (i + 1) && lines[i + 1].length > 0)
lines.insert(i + 1, "");
lines.remove(i - 1);
}
}
}
return lines;
}
var INDENTATION = '\t';
var options = {INDENTATION};
function perform_indentation(lines) {
var indented_lines, current_indent, line;
"Indents the lines according to their nesting level determined by curly brackets.";
indented_lines = [];
current_indent = 0;
var iterator1 = lines;
for (var index1 = 0; index1 < iterator1.length; index1++) {
line = iterator1[index1];
if (!line.startsWith("#") && /.*?\}(\s*#.*)?$/.test(line) && current_indent > 0) {
current_indent -= 1;
}
if (line !== "") {
indented_lines.push(options.INDENTATION.repeat(current_indent) + line);
}
else {
indented_lines.push("");
}
if (!line.startsWith("#") && /.*?\{(\s*#.*)?$/.test(line)) {
current_indent += 1;
}
}
return indented_lines;
}
function perform_alignment(lines) {
var all_lines = [], attribute_lines = [], iterator1 = lines, line, minAlignColumn = 0;
for (let index1 = 0; index1 < iterator1.length; index1++) {
line = iterator1[index1];
if (line !== "" &&
!/.*?\{(\s*#.*)?$/.test(line) &&
!line.startsWith("#") &&
!/.*?\}(\s*#.*)?$/.test(line) &&
!line.trim().startsWith("upstream") &&
!line.trim().contains("location")) {
const splitLine = line.match(/\S+/g);
if (splitLine.length > 1) {
attribute_lines.push(line);
const columnAtAttrValue = line.indexOf(splitLine[1]) + 1;
if (minAlignColumn < columnAtAttrValue) {
minAlignColumn = columnAtAttrValue;
}
}
}
all_lines.push(line);
}
for (let index1 = 0; index1 < all_lines.length; index1++) {
line = all_lines[index1];
if (attribute_lines.includes(line)) {
const split = line.match(/\S+/g);
const indent = line.match(/\s+/g)[0];
line = indent + split[0] + " ".repeat(minAlignColumn - split[0].length - indent.length) + split.slice(1, split.length).join(" ");
all_lines[index1] = line;
}
}
return all_lines;
}
/**nodejs relevant**/
// List all files in a directory in Node.js recursively in a synchronous fashion
function walkSync(dir, ext, filelist) {
var fs = fs || require('fs'),
files = fs.readdirSync(dir);
filelist = filelist || [];
ext = ext || "";
files.forEach(function (file) {
if (fs.statSync(dir + '/' + file).isDirectory()) {
filelist = walkSync(dir + '/' + file, ext, filelist);
}
else if (file.endsWith(ext)) {
filelist.push(dir + '/' + file);
}
});
return filelist;
};
/**
* option1: INDENTATION : '\t'
* @param inputOptions
*/
function modifyOptions(inputOptions) {
for (var k in inputOptions) {
options[k] = inputOptions[k];
}
}
if (typeof module != "undefined") {
module.exports = {
walkSync,
perform_alignment,
perform_indentation,
join_opening_bracket,
clean_lines,
modifyOptions,
strip_line
};
}