import {regExpEscape} from './regexp.js'; /** * Created a RegExp that matches an existing empty template parameter with the * given name. */ const existingEmptyParameterRegExp = paramName => new RegExp(`^( *\\| *${regExpEscape(paramName)}( *)=) *$`, 'm'); /** * Sets the value of an existing empty parameter. * @param {string} pageContent * @param {string} paramName * @param {string} value * @returns {string | null} */ export function setEmptyParameter (pageContent, paramName, value) { const regexp = existingEmptyParameterRegExp(paramName) if (pageContent.match(regexp)) { return pageContent.replace(regexp, `$1$2${value}`); } return null; } /** * Creates a RegExp that matches an existing template parameter with the given * name. */ const existingParameterRegExp = paramName => new RegExp(`^( *)\\|( *)${regExpEscape(paramName)}( *)=( *)(.*)$`, 'm'); /** * Gets the value of an existing parameter. * @param {string} pageContent * @param {string} paramName * @returns {string | null} The value, or `null` if the parameter doesn't exist */ export function readExistingParameter (pageContent, paramName) { let regexp = existingParameterRegExp(paramName); let match; if ((match = pageContent.match(regexp))) { return match[5]; } return null; } /** * Sets the value of an existing parameter. * @param {string} pageContent * @param {string} paramName * @param {string} value * @returns {string | null} */ export function setExistingParameter (pageContent, paramName, value) { const regexp = existingParameterRegExp(paramName); if (pageContent.match(regexp)) { return pageContent.replace(regexp, `$1|$2${paramName}$3=$4${value}`) } return null; } /** * Inserts a new parameter before or after an existing parameter. * @param {string} pageContent * @param {string} existingParamName * @param {'before' | 'after'} location * @param {string} newParamName * @param {string} value * @returns {string | null} */ export function addParameterBesideExistingParameter (pageContent, newParamName, value, location, existingParamName) { let regexp = existingParameterRegExp(existingParamName); if (pageContent.match(regexp)) { let newParameterPattern = `$1|$2${newParamName}$3=$4${value}`; return pageContent.replace( regexp, location === 'before' ? `${newParameterPattern}\n$&` : `$&\n${newParameterPattern}` ); } return null; } /** RegExp that matches the last parameter in an infobox. */ const existingLastParameterRegExp = /^( *)\|( *)([a-z0-9-_]+)( *)=( *)(.*)(\n *}})/m; /** Inserts a new parameter at the end of the infobox. */ export function addParameterAtBottom (pageContent, newParamName, value) { if (pageContent.match(existingLastParameterRegExp)) { // has science gone too far? return pageContent.replace( existingLastParameterRegExp, `$1|$2$3$4=$5$6\n$1|$2${newParamName}$4=$5${value}$7`, ); } return null; }