From 72767671027c4b02eeaeb4d2216eb7fe4a9025f5 Mon Sep 17 00:00:00 2001 From: MattIPv4 Date: Thu, 21 May 2020 15:42:02 +0100 Subject: [PATCH] Fix whitespace cleanup in confs --- src/nginxconfig/generators/to_conf.js | 36 +++++++++++++++++++-------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/src/nginxconfig/generators/to_conf.js b/src/nginxconfig/generators/to_conf.js index f4e0e7b..e5bdb10 100644 --- a/src/nginxconfig/generators/to_conf.js +++ b/src/nginxconfig/generators/to_conf.js @@ -78,16 +78,30 @@ const recurse = (entriesOrObject, depth) => { return retVal; }; -export default entriesOrObject => recurse(entriesOrObject, 0) - // Cleanup triple linebreaks - .replace(/\n\n\n/g, '\n\n') +export default entriesOrObject => { + // Generate the conf + let conf = recurse(entriesOrObject, 0); + + // Do some regex cleanup + conf = conf + // Cleanup triple linebreaks + .replace(/\n\n\n/g, '\n\n') + // Double linebreak before comment + .replace(/^([^\S\r\n]*[^#\s].*[^\n])\n([^\S\r\n]*)#/gm, '$1\n\n$2#') + // Single linebreak between comment and block + .replace(/^([^\S\r\n]*#.*)(?:\n[^\S\r\n]*)+\n([^\S\r\n]*.*{)/gm, '$1\n$2') + // Double linebreak after double comment + .replace(/^([^\S\r\n]*#.*\n[^\S\r\n]*#.*\n)([^\S\r\n]*[^#\s])/gm, '$1\n$2'); + // Cleanup extra linebreaks between multiple close blocks - .replace(/^([^\S\r\n]*})(?:\n[^\S\r\n]*)+\n([^\S\r\n]*})/gm, '$1\n$2') - // Double linebreak before comment - .replace(/^([^\S\r\n]*[^#\s].*[^\n])\n([^\S\r\n]*)#/gm, '$1\n\n$2#') - // Single linebreak between comment and block - .replace(/^([^\S\r\n]*#.*)(?:\n[^\S\r\n]*)+\n([^\S\r\n]*.*{)/gm, '$1\n$2') - // Double linebreak after double comment - .replace(/^([^\S\r\n]*#.*\n[^\S\r\n]*#.*\n)([^\S\r\n]*[^#\s])/gm, '$1\n$2') + // Use a loop as this has overlapping matches + let match; + do { + match = /^([^\S\r\n]*})(?:\n[^\S\r\n]*)+\n([^\S\r\n]*})/m.exec(conf); + if (match) + conf = conf.slice(0, match.index) + match[1] + '\n' + match[2] + conf.slice(match.index + match[0].length); + } while (match); + // Remove initial & trailing whitespace - .trim(); + return conf.trim(); +};