Skip to content

Commit

Permalink
Fix: toExpression handles double quotes in strings (elastic#232)
Browse files Browse the repository at this point in the history
add tests for double quotes and backslashes in string type values
  • Loading branch information
w33ble authored Nov 14, 2017
1 parent 858a1f3 commit 482a563
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
36 changes: 36 additions & 0 deletions common/lib/__tests__/ast.toExpression.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,42 @@ describe('ast toExpression', () => {
expect(expression).to.equal('csv input="stuff\nthings"');
});

it('single expression string value with a backslash', () => {
const astObj = {
type: 'expression',
chain: [{
type: 'function',
function: 'csv',
arguments: {
input: [
'slash \\\\ slash',
],
},
}],
};

const expression = toExpression(astObj);
expect(expression).to.equal('csv input="slash \\\\ slash"');
});

it('single expression string value with a double quote', () => {
const astObj = {
type: 'expression',
chain: [{
type: 'function',
function: 'csv',
arguments: {
input: [
'stuff\nthings\n"such"',
],
},
}],
};

const expression = toExpression(astObj);
expect(expression).to.equal('csv input="stuff\nthings\n\\"such\\""');
});

it('single expression with number argument', () => {
const astObj = {
type: 'expression',
Expand Down
7 changes: 5 additions & 2 deletions common/lib/ast.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import { getType } from '../lib/get_type';

function getArgumentString(arg, argKey) {
const type = getType(arg);
// TODO: MAJOR -- This breaks for single quoted strings that contain double quotes!

function maybeArgKey(argString) {
return (argKey == null || argKey === '_') ? argString : `${argKey}=${argString}`;
}

if (type === 'string') return maybeArgKey(`"${arg}"`);
// TODO: this works, but seems a little hacky. it removes existing escaped chars on quotes
// and adds the escaping onto all other double quotes it finds in the string
const escapeQuotes = (val) => val.replace(/\\\"/g, '"').replace(/\"/g, '\\"');

if (type === 'string') return maybeArgKey(`"${escapeQuotes(arg)}"`);
if (type === 'boolean' || type === 'null' || type === 'number') return maybeArgKey(`${arg}`);
if (type === 'expression') return maybeArgKey(`{${getExpression(arg.chain)}}`);
if (type === 'partial') return maybeArgKey('${' + getExpression(arg.chain) + '}');
Expand Down

0 comments on commit 482a563

Please sign in to comment.