Refactor to inject multiple properties

This commit is contained in:
Yoann Chaudet
2022-07-19 17:03:44 -07:00
parent ad121920a0
commit 3d2f0e5994
8 changed files with 99 additions and 78 deletions

81
dist/index.js vendored
View File

@@ -14433,9 +14433,9 @@ const espree = __nccwpck_require__(6910)
const core = __nccwpck_require__(2186) const core = __nccwpck_require__(2186)
/* /*
Parse a JavaScript based configuration file and initialize or update a given property. Parse a JavaScript based configuration file and inject arbitrary key/value in it.
This is used to make sure most static site generators can automatically handle This is used to make sure most static site generators can automatically handle
Pages's path based routing. Pages's path based routing (and work).
Supported configuration initializations: Supported configuration initializations:
@@ -14460,19 +14460,11 @@ Supported configuration initializations:
class ConfigParser { class ConfigParser {
// Ctor // Ctor
// - configurationFile: path to the configuration file // - configurationFile: path to the configuration file
// - propertyName: name of the property to update (or set)
// - propertyValue: value of the property to update (or set)
// - blankConfigurationFile: a blank configuration file to use if non was previously found // - blankConfigurationFile: a blank configuration file to use if non was previously found
constructor({ constructor({configurationFile, blankConfigurationFile, properties}) {
configurationFile, // Save field
propertyName,
propertyValue,
blankConfigurationFile
}) {
// Save fields
this.configurationFile = configurationFile this.configurationFile = configurationFile
this.propertyName = propertyName this.properties = properties
this.propertyValue = propertyValue
// If the configuration file does not exist, initialize it with the blank configuration file // If the configuration file does not exist, initialize it with the blank configuration file
if (!fs.existsSync(this.configurationFile)) { if (!fs.existsSync(this.configurationFile)) {
@@ -14573,22 +14565,32 @@ class ConfigParser {
// Generate a (nested) property declaration. // Generate a (nested) property declaration.
// - properties: list of properties to generate // - properties: list of properties to generate
// - startIndex: the index at which to start in the declaration // - startIndex: the index at which to start in the declaration
// - propertyValue: the value of the property
// //
// Return a nested property declaration as a string. // Return a nested property declaration as a string.
getPropertyDeclaration(properties, startIndex) { getPropertyDeclaration(properties, startIndex, propertyValue) {
if (startIndex === properties.length - 1) { if (startIndex === properties.length - 1) {
return `${properties[startIndex]}: "${this.propertyValue}"` return `${properties[startIndex]}: ${JSON.stringify(propertyValue)}`
} else { } else {
return ( return (
`${properties[startIndex]}: {` + `${properties[startIndex]}: {` +
this.getPropertyDeclaration(properties, startIndex + 1) + this.getPropertyDeclaration(properties, startIndex + 1, propertyValue) +
'}' '}'
) )
} }
} }
// Parse a configuration file and try to inject Pages settings in it. // Inject all properties into the configuration
inject() { injectAll() {
for (var [propertyName, propertyValue] of Object.entries(this.properties)) {
this.inject(propertyName, propertyValue)
}
}
// Inject an arbitrary property into the configuration
// - propertyName: the name of the property (may use . to target nested objects)
// - propertyValue: the value of the property
inject(propertyName, propertyValue) {
// Logging // Logging
core.info(`Parsing configuration:\n${this.configuration}`) core.info(`Parsing configuration:\n${this.configuration}`)
@@ -14609,7 +14611,7 @@ class ConfigParser {
// A property may be nested in the configuration file. Split the property name with `.` // A property may be nested in the configuration file. Split the property name with `.`
// then walk the configuration object one property at a time. // then walk the configuration object one property at a time.
var depth = 0 var depth = 0
const properties = this.propertyName.split('.') const properties = propertyName.split('.')
var lastNode = configurationObject var lastNode = configurationObject
while (1) { while (1) {
// Find the node for the current property // Find the node for the current property
@@ -14633,7 +14635,7 @@ class ConfigParser {
if (lastNode.type === 'ObjectExpression') { if (lastNode.type === 'ObjectExpression') {
this.configuration = this.configuration =
this.configuration.slice(0, lastNode.range[0]) + this.configuration.slice(0, lastNode.range[0]) +
`"${this.propertyValue}"` + JSON.stringify(propertyValue) +
this.configuration.slice(lastNode.range[1]) this.configuration.slice(lastNode.range[1])
} }
@@ -14642,7 +14644,7 @@ class ConfigParser {
else { else {
this.configuration = this.configuration =
this.configuration.slice(0, lastNode.range[0]) + this.configuration.slice(0, lastNode.range[0]) +
`"${this.propertyValue}"` + JSON.stringify(propertyValue) +
this.configuration.slice(lastNode.range[1]) this.configuration.slice(lastNode.range[1])
} }
} }
@@ -14650,7 +14652,11 @@ class ConfigParser {
// Create nested properties in the configuration file // Create nested properties in the configuration file
else { else {
// Build the declaration to inject // Build the declaration to inject
const declaration = this.getPropertyDeclaration(properties, depth) const declaration = this.getPropertyDeclaration(
properties,
depth,
propertyValue
)
// The last node identified is an object expression, so do the assignment // The last node identified is an object expression, so do the assignment
if (lastNode.type === 'ObjectExpression') { if (lastNode.type === 'ObjectExpression') {
@@ -14679,7 +14685,9 @@ class ConfigParser {
else { else {
this.configuration = this.configuration =
this.configuration.slice(0, lastNode.range[0]) + this.configuration.slice(0, lastNode.range[0]) +
'{' + declaration + '}' + '{' +
declaration +
'}' +
this.configuration.slice(lastNode.range[1]) this.configuration.slice(lastNode.range[1])
} }
} }
@@ -14826,9 +14834,10 @@ function getConfigParserSettings(staticSiteGenerator, path) {
case 'nuxt': case 'nuxt':
return { return {
configurationFile: './nuxt.config.js', configurationFile: './nuxt.config.js',
propertyName: 'router.base', blankConfigurationFile: __nccwpck_require__.ab + "nuxt.js",
propertyValue: path, properties: {
blankConfigurationFile: __nccwpck_require__.ab + "nuxt.js" 'router.base': path
}
} }
case 'next': case 'next':
// Next does not want a trailing slash // Next does not want a trailing slash
@@ -14838,16 +14847,19 @@ function getConfigParserSettings(staticSiteGenerator, path) {
return { return {
configurationFile: './next.config.js', configurationFile: './next.config.js',
propertyName: 'basePath', blankConfigurationFile: __nccwpck_require__.ab + "next.js",
propertyValue: path, properties: {
blankConfigurationFile: __nccwpck_require__.ab + "next.js" basePath: path,
'images.unoptimized': false
}
} }
case 'gatsby': case 'gatsby':
return { return {
configurationFile: './gatsby-config.js', configurationFile: './gatsby-config.js',
propertyName: 'pathPrefix', blankConfigurationFile: __nccwpck_require__.ab + "gatsby.js",
propertyValue: path, properties: {
blankConfigurationFile: __nccwpck_require__.ab + "gatsby.js" pathPrefix: path
}
} }
default: default:
throw `Unsupported static site generator: ${staticSiteGenerator}` throw `Unsupported static site generator: ${staticSiteGenerator}`
@@ -14858,9 +14870,8 @@ function getConfigParserSettings(staticSiteGenerator, path) {
function setPagesPath({staticSiteGenerator, path}) { function setPagesPath({staticSiteGenerator, path}) {
try { try {
// Parse the configuration file and try to inject the Pages configuration in it // Parse the configuration file and try to inject the Pages configuration in it
new ConfigParser( const settings = getConfigParserSettings(staticSiteGenerator, path)
getConfigParserSettings(staticSiteGenerator, path) new ConfigParser(settings).injectAll()
).inject()
} catch (error) { } catch (error) {
// Logging // Logging
core.warning( core.warning(

2
dist/index.js.map vendored

File diff suppressed because one or more lines are too long

View File

@@ -3,9 +3,9 @@ const espree = require('espree')
const core = require('@actions/core') const core = require('@actions/core')
/* /*
Parse a JavaScript based configuration file and initialize or update a given property. Parse a JavaScript based configuration file and inject arbitrary key/value in it.
This is used to make sure most static site generators can automatically handle This is used to make sure most static site generators can automatically handle
Pages's path based routing. Pages's path based routing (and work).
Supported configuration initializations: Supported configuration initializations:
@@ -30,19 +30,11 @@ Supported configuration initializations:
class ConfigParser { class ConfigParser {
// Ctor // Ctor
// - configurationFile: path to the configuration file // - configurationFile: path to the configuration file
// - propertyName: name of the property to update (or set)
// - propertyValue: value of the property to update (or set)
// - blankConfigurationFile: a blank configuration file to use if non was previously found // - blankConfigurationFile: a blank configuration file to use if non was previously found
constructor({ constructor({configurationFile, blankConfigurationFile, properties}) {
configurationFile, // Save field
propertyName,
propertyValue,
blankConfigurationFile
}) {
// Save fields
this.configurationFile = configurationFile this.configurationFile = configurationFile
this.propertyName = propertyName this.properties = properties
this.propertyValue = propertyValue
// If the configuration file does not exist, initialize it with the blank configuration file // If the configuration file does not exist, initialize it with the blank configuration file
if (!fs.existsSync(this.configurationFile)) { if (!fs.existsSync(this.configurationFile)) {
@@ -143,22 +135,32 @@ class ConfigParser {
// Generate a (nested) property declaration. // Generate a (nested) property declaration.
// - properties: list of properties to generate // - properties: list of properties to generate
// - startIndex: the index at which to start in the declaration // - startIndex: the index at which to start in the declaration
// - propertyValue: the value of the property
// //
// Return a nested property declaration as a string. // Return a nested property declaration as a string.
getPropertyDeclaration(properties, startIndex) { getPropertyDeclaration(properties, startIndex, propertyValue) {
if (startIndex === properties.length - 1) { if (startIndex === properties.length - 1) {
return `${properties[startIndex]}: "${this.propertyValue}"` return `${properties[startIndex]}: ${JSON.stringify(propertyValue)}`
} else { } else {
return ( return (
`${properties[startIndex]}: {` + `${properties[startIndex]}: {` +
this.getPropertyDeclaration(properties, startIndex + 1) + this.getPropertyDeclaration(properties, startIndex + 1, propertyValue) +
'}' '}'
) )
} }
} }
// Parse a configuration file and try to inject Pages settings in it. // Inject all properties into the configuration
inject() { injectAll() {
for (var [propertyName, propertyValue] of Object.entries(this.properties)) {
this.inject(propertyName, propertyValue)
}
}
// Inject an arbitrary property into the configuration
// - propertyName: the name of the property (may use . to target nested objects)
// - propertyValue: the value of the property
inject(propertyName, propertyValue) {
// Logging // Logging
core.info(`Parsing configuration:\n${this.configuration}`) core.info(`Parsing configuration:\n${this.configuration}`)
@@ -179,7 +181,7 @@ class ConfigParser {
// A property may be nested in the configuration file. Split the property name with `.` // A property may be nested in the configuration file. Split the property name with `.`
// then walk the configuration object one property at a time. // then walk the configuration object one property at a time.
var depth = 0 var depth = 0
const properties = this.propertyName.split('.') const properties = propertyName.split('.')
var lastNode = configurationObject var lastNode = configurationObject
while (1) { while (1) {
// Find the node for the current property // Find the node for the current property
@@ -203,7 +205,7 @@ class ConfigParser {
if (lastNode.type === 'ObjectExpression') { if (lastNode.type === 'ObjectExpression') {
this.configuration = this.configuration =
this.configuration.slice(0, lastNode.range[0]) + this.configuration.slice(0, lastNode.range[0]) +
`"${this.propertyValue}"` + JSON.stringify(propertyValue) +
this.configuration.slice(lastNode.range[1]) this.configuration.slice(lastNode.range[1])
} }
@@ -212,7 +214,7 @@ class ConfigParser {
else { else {
this.configuration = this.configuration =
this.configuration.slice(0, lastNode.range[0]) + this.configuration.slice(0, lastNode.range[0]) +
`"${this.propertyValue}"` + JSON.stringify(propertyValue) +
this.configuration.slice(lastNode.range[1]) this.configuration.slice(lastNode.range[1])
} }
} }
@@ -220,7 +222,11 @@ class ConfigParser {
// Create nested properties in the configuration file // Create nested properties in the configuration file
else { else {
// Build the declaration to inject // Build the declaration to inject
const declaration = this.getPropertyDeclaration(properties, depth) const declaration = this.getPropertyDeclaration(
properties,
depth,
propertyValue
)
// The last node identified is an object expression, so do the assignment // The last node identified is an object expression, so do the assignment
if (lastNode.type === 'ObjectExpression') { if (lastNode.type === 'ObjectExpression') {
@@ -249,7 +255,9 @@ class ConfigParser {
else { else {
this.configuration = this.configuration =
this.configuration.slice(0, lastNode.range[0]) + this.configuration.slice(0, lastNode.range[0]) +
'{' + declaration + '}' + '{' +
declaration +
'}' +
this.configuration.slice(lastNode.range[1]) this.configuration.slice(lastNode.range[1])
} }
} }

View File

@@ -130,7 +130,7 @@ const cases = [
property: 'a.b.c', property: 'a.b.c',
source: `var config = { a: { b: [], c: "hello"}}; module.exports = config`, source: `var config = { a: { b: [], c: "hello"}}; module.exports = config`,
expected: `var config = { a: { b: { c: "value"}, c: "hello"}}; module.exports = config` expected: `var config = { a: { b: { c: "value"}, c: "hello"}}; module.exports = config`
}, }
] ]
describe('config-parser', () => { describe('config-parser', () => {
@@ -146,10 +146,8 @@ describe('config-parser', () => {
// Update the settings and do the injection // Update the settings and do the injection
new ConfigParser({ new ConfigParser({
configurationFile: sourceFile, configurationFile: sourceFile
propertyName: property, }).inject(property, 'value')
propertyValue: 'value'
}).inject()
// Compare the files // Compare the files
compareFiles(sourceFile, expectedFile) compareFiles(sourceFile, expectedFile)

View File

@@ -1,3 +1,3 @@
// Default Pages configuration for Next // Default Pages configuration for Next
const nextConfig = { basePath: "/docs" } const nextConfig = {images: {unoptimized: false}, basePath: '/docs'}
module.exports = nextConfig module.exports = nextConfig

View File

@@ -1,5 +1,6 @@
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
images: {unoptimized: false},
basePath: "/docs", basePath: "/docs",
reactStrictMode: true, reactStrictMode: true,
swcMinify: true, swcMinify: true,

View File

@@ -8,9 +8,10 @@ function getConfigParserSettings(staticSiteGenerator, path) {
case 'nuxt': case 'nuxt':
return { return {
configurationFile: './nuxt.config.js', configurationFile: './nuxt.config.js',
propertyName: 'router.base', blankConfigurationFile: `${__dirname}/blank-configurations/nuxt.js`,
propertyValue: path, properties: {
blankConfigurationFile: `${__dirname}/blank-configurations/nuxt.js` 'router.base': path
}
} }
case 'next': case 'next':
// Next does not want a trailing slash // Next does not want a trailing slash
@@ -20,16 +21,19 @@ function getConfigParserSettings(staticSiteGenerator, path) {
return { return {
configurationFile: './next.config.js', configurationFile: './next.config.js',
propertyName: 'basePath', blankConfigurationFile: `${__dirname}/blank-configurations/next.js`,
propertyValue: path, properties: {
blankConfigurationFile: `${__dirname}/blank-configurations/next.js` basePath: path,
'images.unoptimized': false
}
} }
case 'gatsby': case 'gatsby':
return { return {
configurationFile: './gatsby-config.js', configurationFile: './gatsby-config.js',
propertyName: 'pathPrefix', blankConfigurationFile: `${__dirname}/blank-configurations/gatsby.js`,
propertyValue: path, properties: {
blankConfigurationFile: `${__dirname}/blank-configurations/gatsby.js` pathPrefix: path
}
} }
default: default:
throw `Unsupported static site generator: ${staticSiteGenerator}` throw `Unsupported static site generator: ${staticSiteGenerator}`
@@ -40,9 +44,8 @@ function getConfigParserSettings(staticSiteGenerator, path) {
function setPagesPath({staticSiteGenerator, path}) { function setPagesPath({staticSiteGenerator, path}) {
try { try {
// Parse the configuration file and try to inject the Pages configuration in it // Parse the configuration file and try to inject the Pages configuration in it
new ConfigParser( const settings = getConfigParserSettings(staticSiteGenerator, path)
getConfigParserSettings(staticSiteGenerator, path) new ConfigParser(settings).injectAll()
).inject()
} catch (error) { } catch (error) {
// Logging // Logging
core.warning( core.warning(

View File

@@ -37,7 +37,7 @@ describe('configParser', () => {
// Update the settings and do the injection // Update the settings and do the injection
settings.configurationFile = fixtureTargetFile settings.configurationFile = fixtureTargetFile
new ConfigParser(settings).inject() new ConfigParser(settings).injectAll()
// Read the expected file // Read the expected file
const expectedFile = `${fixtureFolder}/${path.basename( const expectedFile = `${fixtureFolder}/${path.basename(