Skip to content

Commit

Permalink
template: provide more useful error message on duplicate keys in temp…
Browse files Browse the repository at this point in the history
…late

Updated the error message thrown when duplicate mapping keys are encountered during template rendering to provide additional context on how to resolve the duplicate key issue.
  • Loading branch information
garrettdieckmann authored May 3, 2024
1 parent 8311749 commit e45efe2
Show file tree
Hide file tree
Showing 5 changed files with 318 additions and 51 deletions.
2 changes: 1 addition & 1 deletion lib/github_provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class GitHubContentsApi {
}
}))
.catch(e => this._handleResponseError(e, `get contents for ${contentPath}`))
.then(resp => JSON.parse(resp.data).content)
.then(resp => resp.data.content)
.then(data => Buffer.from(data, 'base64').toString('utf8'));
}
}
Expand Down
29 changes: 27 additions & 2 deletions lib/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ function JsonPostProcessStrategy(rendered) {
if (rendered.trim() === '') {
rendered = '""';
}
return JSON.stringify(yaml.load(rendered) || '', null, 2);
return JSON.stringify(LoadYamlWithDuplicateKeyCheck(rendered) || '', null, 2);
}

/**
Expand All @@ -211,7 +211,32 @@ function YamlPostProcessStrategy(rendered) {
if (rendered.trim() === '') {
rendered = '""';
}
return yaml.dump(yaml.load(rendered));
return yaml.dump(LoadYamlWithDuplicateKeyCheck(rendered));
}

/**
* LoadYamlWithDuplicateKeyCheck will load a yaml string
* and throw a custom error response if duplicate mapping keys exist
*/
function LoadYamlWithDuplicateKeyCheck(str) {
const duplicateKeyRegex = /"(.*?)"/g;
try {
return yaml.load(str);
} catch (e) {
if (e.message.match(/^duplicated mapping key/)) {
const seenKeys = new Set();
let match;
// eslint-disable-next-line no-cond-assign
while ((match = duplicateKeyRegex.exec(e.message)) !== null) {
const matchContents = match[1];
if (seenKeys.has(matchContents)) {
throw new Error(`parameters must have unique values. The parameter value "${matchContents}" is duplicated across parameters and you must update the parameter values to ensure they are unique.`);
}
seenKeys.add(matchContents);
}
}
throw e;
}
}

/**
Expand Down
Loading

0 comments on commit e45efe2

Please sign in to comment.