From aba957660f1f4a08a1308fc1630bad07b2dc8250 Mon Sep 17 00:00:00 2001 From: Matthew Irish Date: Wed, 28 Nov 2018 10:35:55 -0600 Subject: [PATCH] UI - fix bug in policy creation from files (#5864) * fix bug in trim-right util where the last ending wasn't trimming from the end of the string * simplify based on feedback --- ui/app/utils/trim-right.js | 10 +++++++--- ui/tests/unit/utils/trim-right-test.js | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/ui/app/utils/trim-right.js b/ui/app/utils/trim-right.js index 46e42c9ff..17829d518 100644 --- a/ui/app/utils/trim-right.js +++ b/ui/app/utils/trim-right.js @@ -1,4 +1,8 @@ -export default function(fileName, toTrimArray = []) { - const extension = new RegExp(toTrimArray.join('$|')); - return fileName.replace(extension, ''); +// will trim a given set of endings from the end of a string +// if isExtension is true, the first char of that string will be escaped +// in the regex +export default function(str, endings = [], isExtension = true) { + let prefix = isExtension ? '\\' : ''; + let trimRegex = new RegExp(endings.map(ext => `${prefix}${ext}$`).join('|')); + return str.replace(trimRegex, ''); } diff --git a/ui/tests/unit/utils/trim-right-test.js b/ui/tests/unit/utils/trim-right-test.js index 0515de525..4b66f83ae 100644 --- a/ui/tests/unit/utils/trim-right-test.js +++ b/ui/tests/unit/utils/trim-right-test.js @@ -25,4 +25,23 @@ module('Unit | Util | trim right', function() { assert.equal(trimmedName, 'my-file-name-is-cool.json'); }); + + test('it allows the last extension to also be part of the file name', function(assert) { + const trimmedName = trimRight('my-policy.hcl', ['.json', '.txt', '.hcl', '.policy']); + + assert.equal(trimmedName, 'my-policy'); + }); + + test('it allows the last extension to also be part of the file name and the extenstion', function(assert) { + const trimmedName = trimRight('my-policy.policy', ['.json', '.txt', '.hcl', '.policy']); + + assert.equal(trimmedName, 'my-policy'); + }); + + test('it passes endings into the regex unescaped when passing false as the third arg', function(assert) { + const trimmedName = trimRight('my-policypolicy', ['.json', '.txt', '.hcl', '.policy'], false); + + // the . gets interpreted as regex wildcard so it also trims the y character + assert.equal(trimmedName, 'my-polic'); + }); });