Skip to content

Commit

Permalink
Refactor to inject multiple properties
Browse files Browse the repository at this point in the history
  • Loading branch information
Yoann Chaudet committed Jul 20, 2022
1 parent ad12192 commit 3d2f0e5
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 78 deletions.
81 changes: 46 additions & 35 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14433,9 +14433,9 @@ const espree = __nccwpck_require__(6910)
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
Pages's path based routing.
Pages's path based routing (and work).

Supported configuration initializations:

Expand All @@ -14460,19 +14460,11 @@ Supported configuration initializations:
class ConfigParser {
// Ctor
// - 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
constructor({
configurationFile,
propertyName,
propertyValue,
blankConfigurationFile
}) {
// Save fields
constructor({configurationFile, blankConfigurationFile, properties}) {
// Save field
this.configurationFile = configurationFile
this.propertyName = propertyName
this.propertyValue = propertyValue
this.properties = properties

// If the configuration file does not exist, initialize it with the blank configuration file
if (!fs.existsSync(this.configurationFile)) {
Expand Down Expand Up @@ -14573,22 +14565,32 @@ class ConfigParser {
// Generate a (nested) property declaration.
// - properties: list of properties to generate
// - startIndex: the index at which to start in the declaration
// - propertyValue: the value of the property
//
// Return a nested property declaration as a string.
getPropertyDeclaration(properties, startIndex) {
getPropertyDeclaration(properties, startIndex, propertyValue) {
if (startIndex === properties.length - 1) {
return `${properties[startIndex]}: "${this.propertyValue}"`
return `${properties[startIndex]}: ${JSON.stringify(propertyValue)}`
} else {
return (
`${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() {
// Inject all properties into the configuration
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
core.info(`Parsing configuration:\n${this.configuration}`)

Expand All @@ -14609,7 +14611,7 @@ class ConfigParser {
// A property may be nested in the configuration file. Split the property name with `.`
// then walk the configuration object one property at a time.
var depth = 0
const properties = this.propertyName.split('.')
const properties = propertyName.split('.')
var lastNode = configurationObject
while (1) {
// Find the node for the current property
Expand All @@ -14633,7 +14635,7 @@ class ConfigParser {
if (lastNode.type === 'ObjectExpression') {
this.configuration =
this.configuration.slice(0, lastNode.range[0]) +
`"${this.propertyValue}"` +
JSON.stringify(propertyValue) +
this.configuration.slice(lastNode.range[1])
}

Expand All @@ -14642,15 +14644,19 @@ class ConfigParser {
else {
this.configuration =
this.configuration.slice(0, lastNode.range[0]) +
`"${this.propertyValue}"` +
JSON.stringify(propertyValue) +
this.configuration.slice(lastNode.range[1])
}
}

// Create nested properties in the configuration file
else {
// 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
if (lastNode.type === 'ObjectExpression') {
Expand Down Expand Up @@ -14679,7 +14685,9 @@ class ConfigParser {
else {
this.configuration =
this.configuration.slice(0, lastNode.range[0]) +
'{' + declaration + '}' +
'{' +
declaration +
'}' +
this.configuration.slice(lastNode.range[1])
}
}
Expand Down Expand Up @@ -14826,9 +14834,10 @@ function getConfigParserSettings(staticSiteGenerator, path) {
case 'nuxt':
return {
configurationFile: './nuxt.config.js',
propertyName: 'router.base',
propertyValue: path,
blankConfigurationFile: __nccwpck_require__.ab + "nuxt.js"
blankConfigurationFile: __nccwpck_require__.ab + "nuxt.js",
properties: {
'router.base': path
}
}
case 'next':
// Next does not want a trailing slash
Expand All @@ -14838,16 +14847,19 @@ function getConfigParserSettings(staticSiteGenerator, path) {

return {
configurationFile: './next.config.js',
propertyName: 'basePath',
propertyValue: path,
blankConfigurationFile: __nccwpck_require__.ab + "next.js"
blankConfigurationFile: __nccwpck_require__.ab + "next.js",
properties: {
basePath: path,
'images.unoptimized': false
}
}
case 'gatsby':
return {
configurationFile: './gatsby-config.js',
propertyName: 'pathPrefix',
propertyValue: path,
blankConfigurationFile: __nccwpck_require__.ab + "gatsby.js"
blankConfigurationFile: __nccwpck_require__.ab + "gatsby.js",
properties: {
pathPrefix: path
}
}
default:
throw `Unsupported static site generator: ${staticSiteGenerator}`
Expand All @@ -14858,9 +14870,8 @@ function getConfigParserSettings(staticSiteGenerator, path) {
function setPagesPath({staticSiteGenerator, path}) {
try {
// Parse the configuration file and try to inject the Pages configuration in it
new ConfigParser(
getConfigParserSettings(staticSiteGenerator, path)
).inject()
const settings = getConfigParserSettings(staticSiteGenerator, path)
new ConfigParser(settings).injectAll()
} catch (error) {
// Logging
core.warning(
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

54 changes: 31 additions & 23 deletions src/config-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ const espree = require('espree')
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
Pages's path based routing.
Pages's path based routing (and work).
Supported configuration initializations:
Expand All @@ -30,19 +30,11 @@ Supported configuration initializations:
class ConfigParser {
// Ctor
// - 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
constructor({
configurationFile,
propertyName,
propertyValue,
blankConfigurationFile
}) {
// Save fields
constructor({configurationFile, blankConfigurationFile, properties}) {
// Save field
this.configurationFile = configurationFile
this.propertyName = propertyName
this.propertyValue = propertyValue
this.properties = properties

// If the configuration file does not exist, initialize it with the blank configuration file
if (!fs.existsSync(this.configurationFile)) {
Expand Down Expand Up @@ -143,22 +135,32 @@ class ConfigParser {
// Generate a (nested) property declaration.
// - properties: list of properties to generate
// - startIndex: the index at which to start in the declaration
// - propertyValue: the value of the property
//
// Return a nested property declaration as a string.
getPropertyDeclaration(properties, startIndex) {
getPropertyDeclaration(properties, startIndex, propertyValue) {
if (startIndex === properties.length - 1) {
return `${properties[startIndex]}: "${this.propertyValue}"`
return `${properties[startIndex]}: ${JSON.stringify(propertyValue)}`
} else {
return (
`${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() {
// Inject all properties into the configuration
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
core.info(`Parsing configuration:\n${this.configuration}`)

Expand All @@ -179,7 +181,7 @@ class ConfigParser {
// A property may be nested in the configuration file. Split the property name with `.`
// then walk the configuration object one property at a time.
var depth = 0
const properties = this.propertyName.split('.')
const properties = propertyName.split('.')
var lastNode = configurationObject
while (1) {
// Find the node for the current property
Expand All @@ -203,7 +205,7 @@ class ConfigParser {
if (lastNode.type === 'ObjectExpression') {
this.configuration =
this.configuration.slice(0, lastNode.range[0]) +
`"${this.propertyValue}"` +
JSON.stringify(propertyValue) +
this.configuration.slice(lastNode.range[1])
}

Expand All @@ -212,15 +214,19 @@ class ConfigParser {
else {
this.configuration =
this.configuration.slice(0, lastNode.range[0]) +
`"${this.propertyValue}"` +
JSON.stringify(propertyValue) +
this.configuration.slice(lastNode.range[1])
}
}

// Create nested properties in the configuration file
else {
// 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
if (lastNode.type === 'ObjectExpression') {
Expand Down Expand Up @@ -249,7 +255,9 @@ class ConfigParser {
else {
this.configuration =
this.configuration.slice(0, lastNode.range[0]) +
'{' + declaration + '}' +
'{' +
declaration +
'}' +
this.configuration.slice(lastNode.range[1])
}
}
Expand Down
8 changes: 3 additions & 5 deletions src/config-parser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ const cases = [
property: 'a.b.c',
source: `var config = { a: { b: [], c: "hello"}}; module.exports = config`,
expected: `var config = { a: { b: { c: "value"}, c: "hello"}}; module.exports = config`
},
}
]

describe('config-parser', () => {
Expand All @@ -146,10 +146,8 @@ describe('config-parser', () => {

// Update the settings and do the injection
new ConfigParser({
configurationFile: sourceFile,
propertyName: property,
propertyValue: 'value'
}).inject()
configurationFile: sourceFile
}).inject(property, 'value')

// Compare the files
compareFiles(sourceFile, expectedFile)
Expand Down
2 changes: 1 addition & 1 deletion src/fixtures/next/blank.expected.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// Default Pages configuration for Next
const nextConfig = { basePath: "/docs" }
const nextConfig = {images: {unoptimized: false}, basePath: '/docs'}
module.exports = nextConfig
1 change: 1 addition & 0 deletions src/fixtures/next/default.expected.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {unoptimized: false},
basePath: "/docs",
reactStrictMode: true,
swcMinify: true,
Expand Down
27 changes: 15 additions & 12 deletions src/set-pages-path.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ function getConfigParserSettings(staticSiteGenerator, path) {
case 'nuxt':
return {
configurationFile: './nuxt.config.js',
propertyName: 'router.base',
propertyValue: path,
blankConfigurationFile: `${__dirname}/blank-configurations/nuxt.js`
blankConfigurationFile: `${__dirname}/blank-configurations/nuxt.js`,
properties: {
'router.base': path
}
}
case 'next':
// Next does not want a trailing slash
Expand All @@ -20,16 +21,19 @@ function getConfigParserSettings(staticSiteGenerator, path) {

return {
configurationFile: './next.config.js',
propertyName: 'basePath',
propertyValue: path,
blankConfigurationFile: `${__dirname}/blank-configurations/next.js`
blankConfigurationFile: `${__dirname}/blank-configurations/next.js`,
properties: {
basePath: path,
'images.unoptimized': false
}
}
case 'gatsby':
return {
configurationFile: './gatsby-config.js',
propertyName: 'pathPrefix',
propertyValue: path,
blankConfigurationFile: `${__dirname}/blank-configurations/gatsby.js`
blankConfigurationFile: `${__dirname}/blank-configurations/gatsby.js`,
properties: {
pathPrefix: path
}
}
default:
throw `Unsupported static site generator: ${staticSiteGenerator}`
Expand All @@ -40,9 +44,8 @@ function getConfigParserSettings(staticSiteGenerator, path) {
function setPagesPath({staticSiteGenerator, path}) {
try {
// Parse the configuration file and try to inject the Pages configuration in it
new ConfigParser(
getConfigParserSettings(staticSiteGenerator, path)
).inject()
const settings = getConfigParserSettings(staticSiteGenerator, path)
new ConfigParser(settings).injectAll()
} catch (error) {
// Logging
core.warning(
Expand Down
2 changes: 1 addition & 1 deletion src/set-pages-path.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe('configParser', () => {

// Update the settings and do the injection
settings.configurationFile = fixtureTargetFile
new ConfigParser(settings).inject()
new ConfigParser(settings).injectAll()

// Read the expected file
const expectedFile = `${fixtureFolder}/${path.basename(
Expand Down

0 comments on commit 3d2f0e5

Please sign in to comment.