Skip to content
This repository has been archived by the owner on Oct 17, 2020. It is now read-only.

Commit

Permalink
improve handling of quotes in keys in the sanitize() function
Browse files Browse the repository at this point in the history
implements the tests defined in 6cf3754
fixes #6
  • Loading branch information
bgotink committed Apr 22, 2016
1 parent 6cf3754 commit 28b8c27
Showing 1 changed file with 32 additions and 18 deletions.
50 changes: 32 additions & 18 deletions lib/caml.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,26 +86,40 @@ function replaceVariables(yamlLines) {
function sanitize(yamlString) {
return yamlString.split('\n')
.map(function (line) {
var enclosedDottedMatch = line.trim().match(/["'].*\..*["']:\s/);
var rawDottedMatch = line.trim().match(/.*\..*:\s/);

if (enclosedDottedMatch) {
var enclosedSubstituted = line.replace(enclosedDottedMatch[0],
enclosedDottedMatch[0]
.replace(/["']/g, '') // Strip " or ' from the keys
.replace(/\./g, DOT_SUBSTITUTE) // Replace . by DOT_SUBSTITUTE in "" keys
);

return enclosedSubstituted;
} else if (rawDottedMatch) {
var rawSubstituted = line.replace(rawDottedMatch[0],
rawDottedMatch[0]
.replace(/\./g, DOT_SUBSTITUTE + DOT_SUBSTITUTE) // Replace . by DOT_SUBSTITUTE + DOT_SUBSTITUTE in raw dotted keys
);
return rawSubstituted;
} else {
var colonIdx = line.indexOf(':');

// not an object -> no escaping needed
if (colonIdx === -1) {
return line;
}

var key = line.slice(0, colonIdx);
var value = line.slice(colonIdx + 1);

while (quoteMatch = key.match(/["']/)) {
var quote = quoteMatch[0];
var startIdx = quoteMatch.index;

var endIdx = key.indexOf(quote, startIdx + 1);

if (endIdx === -1) {
throw new Error('Key contains incomplete quoted section: "' + line + '"');
}

var quoted = key.slice(startIdx + 1, endIdx);

if (quoted.match(/['"]/)) {
throw new Error('Key cannot contain nested quotes: "' + line + '"');
}

key = key.slice(0, startIdx)
+ quoted.replace(/\./g, DOT_SUBSTITUTE)
+ key.slice(endIdx + 1);
}

key = key.replace(/\./g, DOT_SUBSTITUTE + DOT_SUBSTITUTE);

return key + ':' + value;
})
.join('\n');
}
Expand Down

0 comments on commit 28b8c27

Please sign in to comment.