From e471a39e82bf27a58b052483c71ef10ff3ee34f8 Mon Sep 17 00:00:00 2001 From: paul Date: Sun, 11 Oct 2026 13:11:37 +0200 Subject: [PATCH 1/3] fix: an unparsable config file no longer deletes the database entry on import --- server/services/main.js | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/server/services/main.js b/server/services/main.js index 5a73e6ad..ebacc3a2 100644 --- a/server/services/main.js +++ b/server/services/main.js @@ -94,14 +94,24 @@ export default () => ({ // Replace reserved characters in filenames. configName = configName.replace(/:/g, "#").replace(/\//g, "$"); + const filePath = `${strapi.config.get('plugin::config-sync.syncDir')}${configType}.${configName}.json`; const readFile = util.promisify(fs.readFile); - return readFile(`${strapi.config.get('plugin::config-sync.syncDir')}${configType}.${configName}.json`) - .then((data) => { - return JSON.parse(data); - }) - .catch(() => { - return null; - }); + + let data; + try { + data = await readFile(filePath); + } catch (e) { + // No file for this config. + if (e.code === 'ENOENT') return null; + throw e; + } + + try { + return JSON.parse(data); + } catch (e) { + // A file that can't be parsed is not a missing file: it must never lead to deleting the config. + throw new Error(`The config file '${filePath}' is not valid JSON (${e.message}).`); + } }, @@ -136,7 +146,13 @@ export default () => ({ return; } - const fileContents = await strapi.plugin('config-sync').service('main').readConfigFile(type, name); + let fileContents; + try { + fileContents = await strapi.plugin('config-sync').service('main').readConfigFile(type, name); + } catch (e) { + strapi.log.warn(logMessage(`The config file '${file}' can't be read and is left out of the diff: ${e.message}`)); + return; + } if (!fileContents) { strapi.log.warn(logMessage(`An empty config file '${file}' was found in the sync directory`)); @@ -242,9 +258,9 @@ export default () => ({ const type = configName.split('.')[0]; // Grab the first part of the filename. const name = configName.split(/\.(.+)/)[1]; // Grab the rest of the filename. - const fileContents = await strapi.plugin('config-sync').service('main').readConfigFile(type, name); try { + const fileContents = await strapi.plugin('config-sync').service('main').readConfigFile(type, name); const importState = await strapi.plugin('config-sync').types[type].importSingle(name, fileContents, force); if (onSuccess && importState !== false) onSuccess(`${type}.${name}`); } catch (e) { From ea9cfba6278233c85ea7f452114dc9c0f3dd0fcf Mon Sep 17 00:00:00 2001 From: paul Date: Sun, 11 Oct 2026 13:35:21 +0200 Subject: [PATCH 2/3] test: importing an unparsable config file fails and keeps the config --- playground/__tests__/cli.test.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/playground/__tests__/cli.test.js b/playground/__tests__/cli.test.js index 8ace6c68..9ee1eb1e 100644 --- a/playground/__tests__/cli.test.js +++ b/playground/__tests__/cli.test.js @@ -1,5 +1,6 @@ 'use strict'; +const fs = require('fs'); const util = require('util'); const exec = util.promisify(require('child_process').exec); @@ -46,6 +47,27 @@ describe('Test the config-sync CLI', () => { expect(diffOutput).toContain('No differences between DB and sync directory'); }); + test('Import (unparsable file)', async () => { + // A file that can't be parsed (a merge conflict left in it, a typo) is not a missing file: + // importing it must fail, and leave the config in the database. + const file = 'config/sync/user-role.public.json'; + const original = fs.readFileSync(file, 'utf8'); + fs.writeFileSync(file, '<<<<<<< HEAD\n{ "name": "Public",\n'); + let output; + try { + const { stdout, stderr } = await exec('yarn cs import -p user-role.public -y'); + output = stdout + stderr; + } catch (e) { + output = `${e.stdout}${e.stderr}`; + } finally { + fs.writeFileSync(file, original); + } + expect(output).toContain('is not valid JSON'); + // The role is still in the database: with its file back, nothing differs. + const { stdout: diffOutput } = await exec('yarn cs diff'); + expect(diffOutput).toContain('No differences between DB and sync directory'); + }); + test('Non-empty diff returns 1', async () => { await exec('rm -rf config/sync/admin-role.strapi-editor.json'); // Work around Jest not supporting custom error matching. From 774c79e7b88ca6e361d068bad1281bf3bd021bd5 Mon Sep 17 00:00:00 2001 From: Boaz Poolman Date: Mon, 9 Nov 2026 20:42:49 +0100 Subject: [PATCH 3/3] fix: make the 'invalid file' config state more prominent during import/export/diff actions both admin and server --- admin/src/components/ConfigDiff/index.jsx | 66 ++++++++---- .../ConfigList/ConfigListRow/index.jsx | 5 + admin/src/components/ConfigList/index.jsx | 5 + admin/src/index.cy.jsx | 102 ++++++++++++++++++ admin/src/state/actions/Config.js | 25 ++++- admin/src/translations/en.json | 4 + docs/docs/getting-started/admin-gui.md | 3 + docs/docs/getting-started/cli.md | 2 + package.json | 1 + playground/__tests__/cli.test.js | 60 ++++++++++- server/cli.js | 14 ++- server/config/type.js | 9 ++ server/controllers/config.js | 20 +++- server/services/main.js | 37 ++++++- server/utils/invalidConfigFileError.js | 8 ++ yarn.lock | 5 + 16 files changed, 326 insertions(+), 40 deletions(-) create mode 100644 server/utils/invalidConfigFileError.js diff --git a/admin/src/components/ConfigDiff/index.jsx b/admin/src/components/ConfigDiff/index.jsx index dc0fda3a..e28f9988 100644 --- a/admin/src/components/ConfigDiff/index.jsx +++ b/admin/src/components/ConfigDiff/index.jsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useEffect, useState } from 'react'; import { useDispatch } from 'react-redux'; import RDV, { DiffMethod } from 'react-diff-viewer-continued'; import { useIntl } from 'react-intl'; @@ -29,11 +29,16 @@ import { import ConfirmModal from '../ConfirmModal'; import { exportAllConfig, importAllConfig } from '../../state/actions/Config'; -const ConfigDiff = ({ oldValue, newValue, configName, open, onOpenChange }) => { +const ConfigDiff = ({ oldValue, newValue, error, configName, open, onOpenChange }) => { const { formatMessage } = useIntl(); const dispatch = useDispatch(); const { toggleNotification } = useNotification(); const { post, get } = getFetchClient(); + const [syncError, setSyncError] = useState(''); + useEffect(() => { + setSyncError(''); + }, [configName, open]); + return ( @@ -43,26 +48,39 @@ const ConfigDiff = ({ oldValue, newValue, configName, open, onOpenChange }) => { - - - - {formatMessage({ id: 'config-sync.ConfigDiff.SyncDirectory' })} - - - - - {formatMessage({ id: 'config-sync.ConfigDiff.Database' })} + {syncError && ( + + {syncError} + + )} + {error ? ( + + {error} + + ) : ( + <> + + + + {formatMessage({ id: 'config-sync.ConfigDiff.SyncDirectory' })} + + + + + {formatMessage({ id: 'config-sync.ConfigDiff.Database' })} + + + + + - - - - - + + )} { )} onSubmit={async (force) => { - const succeeded = await dispatch(importAllConfig([configName], force, toggleNotification, formatMessage, post, get)); + setSyncError(''); + const succeeded = await dispatch(importAllConfig([configName], force, toggleNotification, formatMessage, post, get, setSyncError)); if (succeeded) onOpenChange(false, configName); }} /> @@ -85,7 +104,8 @@ const ConfigDiff = ({ oldValue, newValue, configName, open, onOpenChange }) => { )} onSubmit={async () => { - const succeeded = await dispatch(exportAllConfig([configName], toggleNotification, formatMessage, post, get)); + setSyncError(''); + const succeeded = await dispatch(exportAllConfig([configName], toggleNotification, formatMessage, post, get, setSyncError)); if (succeeded) onOpenChange(false, configName); }} /> diff --git a/admin/src/components/ConfigList/ConfigListRow/index.jsx b/admin/src/components/ConfigList/ConfigListRow/index.jsx index 08b106c3..4f5916fe 100644 --- a/admin/src/components/ConfigList/ConfigListRow/index.jsx +++ b/admin/src/components/ConfigList/ConfigListRow/index.jsx @@ -24,6 +24,11 @@ const CustomRow = ({ row, checked, updateValue, ...props }) => { style.color = '#3d302f'; } + if (stateStr === 'Invalid file') { + style.backgroundColor = '#f0cac7'; + style.color = '#3d302f'; + } + if (stateStr === 'Different') { style.backgroundColor = '#e8e6b7'; style.color = '#4a4934'; diff --git a/admin/src/components/ConfigList/index.jsx b/admin/src/components/ConfigList/index.jsx index 4045a26f..9ff9e5fc 100644 --- a/admin/src/components/ConfigList/index.jsx +++ b/admin/src/components/ConfigList/index.jsx @@ -29,6 +29,10 @@ const ConfigList = ({ diff, isLoading }) => { const { formatMessage } = useIntl(); const getConfigState = (configName) => { + if (diff.invalidConfig && diff.invalidConfig[configName]) { + return formatMessage({ id: 'config-sync.ConfigList.Invalid' }); + } + if ( diff.fileConfig[configName] && diff.databaseConfig[configName] @@ -150,6 +154,7 @@ const ConfigList = ({ diff, isLoading }) => { { diff --git a/admin/src/index.cy.jsx b/admin/src/index.cy.jsx index bdd1b9bc..03e75a1b 100644 --- a/admin/src/index.cy.jsx +++ b/admin/src/index.cy.jsx @@ -20,6 +20,108 @@ describe('Config Sync', () => { cy.contains('"unique_email": false,'); }); + it('Shows the JSON error and location in the config diff', () => { + cy.login(); + cy.navigateToInterface(); + cy.initialExport(); + + cy.writeFile('playground/config/sync/user-role.public.json', '{\n "name": ,\n}'); + cy.intercept('GET', '/config-sync/diff').as('invalidDiff'); + cy.reload(); + cy.wait('@invalidDiff').then(({ response }) => { + expect(response.body.invalidConfig['user-role.public']).to.include('line 2, column 11'); + }); + + cy.get('tbody tr').contains('public').parents('tr').should('contain', 'Invalid file') + .click(); + cy.get('[role="dialog"]').should('contain', 'user-role.public.json') + .and('contain', 'is not valid JSON') + .and('contain', 'line 2, column 11') + .and('not.contain', 'Database'); + }); + + ['list', 'diff'].forEach((view) => { + it(`Shows an invalid-file notification when importing from the ${view}`, () => { + cy.login(); + cy.navigateToInterface(); + cy.initialExport(); + cy.writeFile('playground/config/sync/user-role.public.json', '{\n "name": ,\n}'); + cy.intercept('GET', '/config-sync/diff').as('invalidDiff'); + cy.reload(); + cy.wait('@invalidDiff'); + + if (view === 'diff') { + cy.get('tbody tr').contains('public').click(); + cy.get('[role="dialog"] footer').contains('button', 'Import').click(); + } else { + cy.contains('button', 'Import').click(); + } + + cy.intercept('POST', '/config-sync/import').as('invalidImport'); + cy.contains('button', 'Yes, import').click(); + cy.wait('@invalidImport').then(({ response }) => { + expect(response.statusCode).to.equal(400); + expect(response.body.error.details).to.include({ + code: 'CONFIG_SYNC_INVALID_FILE', + configName: 'user-role.public', + reason: 'invalid_json', + }); + }); + const message = 'Cannot import user-role.public: its config file contains invalid JSON. Open the diff for details.'; + if (view === 'diff') cy.get('[role="dialog"]').should('be.visible').and('contain', message); + else cy.contains(message).should('be.visible'); + }); + + it(`Shows an invalid-file notification when exporting without a database config from the ${view}`, () => { + cy.login(); + cy.navigateToInterface(); + cy.initialExport(); + cy.writeFile('playground/config/sync/user-role.nonexistent-config-sync-test.json', '{\n "name": ,\n}'); + cy.intercept('GET', '/config-sync/diff').as('invalidDiff'); + cy.reload(); + cy.wait('@invalidDiff'); + + if (view === 'diff') { + cy.get('tbody tr').contains('nonexistent-config-sync-test').click(); + cy.get('[role="dialog"] footer').contains('button', 'Export').click(); + } else { + cy.contains('button', 'Export').click(); + } + + cy.intercept('POST', '/config-sync/export').as('invalidExport'); + cy.contains('button', 'Yes, export').click(); + cy.wait('@invalidExport').then(({ response }) => { + expect(response.statusCode).to.equal(400); + expect(response.body.error.details).to.include({ + code: 'CONFIG_SYNC_INVALID_FILE', + configName: 'user-role.nonexistent-config-sync-test', + reason: 'no_database_config', + }); + }); + const message = 'Cannot export user-role.nonexistent-config-sync-test: its config file is invalid and there is no database config to replace it.'; + if (view === 'diff') cy.get('[role="dialog"]').should('be.visible').and('contain', message); + else cy.contains(message).should('be.visible'); + cy.readFile('playground/config/sync/user-role.nonexistent-config-sync-test.json', null) + .then((contents) => expect(contents.toString()).to.equal('{\n "name": ,\n}')); + }); + }); + + it('Exports a database config over its invalid file', () => { + cy.login(); + cy.navigateToInterface(); + cy.initialExport(); + cy.writeFile('playground/config/sync/user-role.public.json', '{\n "name": ,\n}'); + cy.intercept('GET', '/config-sync/diff').as('invalidDiff'); + cy.reload(); + cy.wait('@invalidDiff'); + cy.get('tbody tr').contains('public').click(); + cy.get('[role="dialog"] footer').contains('button', 'Export').click(); + cy.intercept('POST', '/config-sync/export').as('repairExport'); + cy.contains('button', 'Yes, export').click(); + cy.wait('@repairExport').its('response.statusCode').should('equal', 200); + cy.readFile('playground/config/sync/user-role.public.json').its('name').should('eq', 'Public'); + }); + it('Download the config as zip', () => { cy.login(); cy.navigateToInterface(); diff --git a/admin/src/state/actions/Config.js b/admin/src/state/actions/Config.js index cd0d97ea..449b71ce 100644 --- a/admin/src/state/actions/Config.js +++ b/admin/src/state/actions/Config.js @@ -6,6 +6,19 @@ import { saveAs } from 'file-saver'; import { b64toBlob } from '../../helpers/blob'; +const getSyncErrorMessage = (err, formatMessage) => { + const details = err?.response?.data?.error?.details; + if (details?.code === 'CONFIG_SYNC_INVALID_FILE' && typeof details.configName === 'string') { + if (details.reason === 'invalid_json') { + return formatMessage({ id: 'config-sync.notification.invalidJson' }, { configName: details.configName }); + } + if (details.reason === 'no_database_config') { + return formatMessage({ id: 'config-sync.notification.noDatabaseConfig' }, { configName: details.configName }); + } + } + return formatMessage({ id: 'notification.error' }); +}; + export function getAllConfigDiff(toggleNotification, formatMessage, get) { return async function(dispatch) { dispatch(setLoadingState(true)); @@ -37,7 +50,7 @@ export function setConfigPartialDiffInState(config) { }; } -export function exportAllConfig(partialDiff, toggleNotification, formatMessage, post, get) { +export function exportAllConfig(partialDiff, toggleNotification, formatMessage, post, get, onError) { return async function(dispatch) { dispatch(setLoadingState(true)); try { @@ -46,7 +59,9 @@ export function exportAllConfig(partialDiff, toggleNotification, formatMessage, await dispatch(getAllConfigDiff(toggleNotification, formatMessage, get)); return true; } catch (err) { - toggleNotification({ type: 'warning', message: formatMessage({ id: 'notification.error' }) }); + const message = getSyncErrorMessage(err, formatMessage); + if (onError) onError(message); + else toggleNotification({ type: 'warning', message }); dispatch(setLoadingState(false)); return false; } @@ -70,7 +85,7 @@ export function downloadZip(toggleNotification, formatMessage, post, get) { }; } -export function importAllConfig(partialDiff, force, toggleNotification, formatMessage, post, get) { +export function importAllConfig(partialDiff, force, toggleNotification, formatMessage, post, get, onError) { return async function(dispatch) { dispatch(setLoadingState(true)); try { @@ -82,7 +97,9 @@ export function importAllConfig(partialDiff, force, toggleNotification, formatMe await dispatch(getAllConfigDiff(toggleNotification, formatMessage, get)); return true; } catch (err) { - toggleNotification({ type: 'warning', message: formatMessage({ id: 'notification.error' }) }); + const message = getSyncErrorMessage(err, formatMessage); + if (onError) onError(message); + else toggleNotification({ type: 'warning', message }); dispatch(setLoadingState(false)); return false; } diff --git a/admin/src/translations/en.json b/admin/src/translations/en.json index 0e807e42..b6896e3d 100644 --- a/admin/src/translations/en.json +++ b/admin/src/translations/en.json @@ -24,6 +24,7 @@ "ConfigList.Different": "Different", "ConfigList.OnlyDir": "Only in sync dir", "ConfigList.OnlyDB": "Only in DB", + "ConfigList.Invalid": "Invalid file", "NoChanges.Message": "No differences between DB and sync directory. You are up-to-date!", @@ -33,6 +34,9 @@ "ConfigDiff.ImportTitle": "Import config into DB for this file only", "ConfigDiff.ExportTitle": "Export DB config for this file only", + "notification.invalidJson": "Cannot import {configName}: its config file contains invalid JSON. Open the diff for details.", + "notification.noDatabaseConfig": "Cannot export {configName}: its config file is invalid and there is no database config to replace it.", + "Buttons.Export": "Export", "Buttons.DownloadConfig": "Download Config", "Buttons.Import": "Import", diff --git a/docs/docs/getting-started/admin-gui.md b/docs/docs/getting-started/admin-gui.md index 2c4dafeb..230f75a5 100644 --- a/docs/docs/getting-started/admin-gui.md +++ b/docs/docs/getting-started/admin-gui.md @@ -10,4 +10,7 @@ This plugin ships with a React app which can be accessed from the settings page **Pro tip:** By clicking on one of the items in the diff table you can see the exact difference between sync dir and database in a git-style diff viewer. +If a config file contains invalid JSON, its state is **Invalid file**. Open it to see the parsing error and its location instead of a misleading diff. +Importing an invalid file shows an error. Exporting can replace it with the database version; if no database version exists, export reports the error and leaves the file untouched. + ![Config diff in admin](/img/assets/admin-diff-viewer.png) diff --git a/docs/docs/getting-started/cli.md b/docs/docs/getting-started/cli.md index 22f36c94..64831333 100644 --- a/docs/docs/getting-started/cli.md +++ b/docs/docs/getting-started/cli.md @@ -122,6 +122,8 @@ _Example:_ Add a single config name as the argument of the `diff` command to see the difference of that single file in a git-style diff viewer. +For invalid JSON, the diff table shows **Invalid file**, and the single-config diff reports the parsing error and its location. + _Example:_ diff --git a/package.json b/package.json index b6e8ea7b..e1cb2414 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "git-diff": "^2.0.6", "immutable": "^4.0.0", "inquirer": "^13.3.0", + "jsonc-parser": "^3.3.1", "lodash": "^4.17.23", "react-diff-viewer-continued": "4.0.6", "react-intl": "^6", diff --git a/playground/__tests__/cli.test.js b/playground/__tests__/cli.test.js index faef94e8..965bc314 100644 --- a/playground/__tests__/cli.test.js +++ b/playground/__tests__/cli.test.js @@ -1,6 +1,5 @@ 'use strict'; -const fs = require('fs'); const util = require('util'); const fs = require('fs'); const exec = util.promisify(require('child_process').exec); @@ -107,7 +106,13 @@ describe('Test the config-sync CLI', () => { const original = fs.readFileSync(file, 'utf8'); fs.writeFileSync(file, '<<<<<<< HEAD\n{ "name": "Public",\n'); let output; + let diffWhileInvalid; try { + try { + await exec('yarn cs diff'); + } catch (e) { + diffWhileInvalid = e.stdout; + } const { stdout, stderr } = await exec('yarn cs import -p user-role.public -y'); output = stdout + stderr; } catch (e) { @@ -115,12 +120,65 @@ describe('Test the config-sync CLI', () => { } finally { fs.writeFileSync(file, original); } + expect(diffWhileInvalid).toContain('Invalid file'); expect(output).toContain('is not valid JSON'); // The role is still in the database: with its file back, nothing differs. const { stdout: diffOutput } = await exec('yarn cs diff'); expect(diffOutput).toContain('No differences between DB and sync directory'); }); + test.each([ + ['user-role.public', '{\n "name": ,\n}', 'line 2, column 11'], + ['user-role.public', '{\n "name": "ab\\q"\n}', 'line 2, column 15'], + ['user-role.public', '', 'line 1, column 1'], + ['user-role.nonexistent-config-sync-test', '{\n "name": "test"\n', 'line 3, column 1'], + ])('Single diff reports invalid JSON in %s at the error location', async (name, contents, location) => { + const file = `config/sync/${name}.json`; + const original = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null; + fs.writeFileSync(file, contents); + + try { + let error; + try { + await exec(`yarn cs diff ${name}`); + } catch (e) { + error = e; + } + + expect(error).toHaveProperty('code', 1); + expect(error.stdout).toContain(`${name}.json`); + expect(error.stdout).toContain('is not valid JSON'); + expect(error.stdout).toContain(location); + expect(error.stdout).toContain('[error]'); + expect(error.stdout).not.toContain('No differences between DB and sync directory'); + } finally { + if (original === null) fs.unlinkSync(file); + else fs.writeFileSync(file, original); + } + }); + + test('Single diff still displays changes for valid JSON', async () => { + const file = 'config/sync/user-role.public.json'; + const original = fs.readFileSync(file, 'utf8'); + const config = JSON.parse(original); + config.description = 'Single diff test'; + fs.writeFileSync(file, JSON.stringify(config)); + + try { + let error; + try { + await exec('yarn cs diff user-role.public'); + } catch (e) { + error = e; + } + expect(error).toHaveProperty('code', 1); + expect(error.stdout).toContain('Single diff test'); + expect(error.stdout).not.toContain('[error]'); + } finally { + fs.writeFileSync(file, original); + } + }); + test('Non-empty diff returns 1', async () => { await exec('rm -rf config/sync/admin-role.strapi-editor.json'); // Work around Jest not supporting custom error matching. diff --git a/server/cli.js b/server/cli.js index d0626300..67d3c829 100644 --- a/server/cli.js +++ b/server/cli.js @@ -59,6 +59,10 @@ const initTable = (head) => { }; const getConfigState = (diff, configName, syncType) => { + if (diff.invalidConfig && diff.invalidConfig[configName]) { + return chalk.red('Invalid file'); + } + if ( diff.fileConfig[configName] && diff.databaseConfig[configName] @@ -235,11 +239,10 @@ program // `$ config-sync diff` program - .command('diff') + .command('diff [config]') .alias('d') .description('The config diff') - .action(async (options, { args }) => { - const single = args[0]; + .action(async (single) => { const app = await getStrapiApp(); const diff = await app.plugin('config-sync').service('main').getFormattedDiff(); @@ -251,6 +254,11 @@ program // Single config diff. if (single) { + if (diff.invalidConfig && diff.invalidConfig[single]) { + console.log(`${chalk.red.bold('[error]')} ${diff.invalidConfig[single]}`); + process.exit(1); + } + // No changes. if (!diff.fileConfig[single] && !diff.databaseConfig[single]) { console.log(`${chalk.cyan.bold('[notice]')} No differences between DB and sync directory for ${single}.`); diff --git a/server/config/type.js b/server/config/type.js index 69c5a50e..d4fad8ad 100644 --- a/server/config/type.js +++ b/server/config/type.js @@ -2,6 +2,7 @@ import isEmpty from 'lodash/isEmpty'; import { logMessage, sanitizeConfig, dynamicSort, noLimit, getCombinedUid, getCombinedUidWhereFilter, getUidParamsFromName } from '../utils'; import { difference, same } from '../utils/getArrayDiff'; import queryFallBack from '../utils/queryFallBack'; +import InvalidConfigFileError from '../utils/invalidConfigFileError'; const ConfigType = class ConfigType { constructor({ queryString, configName, uid, jsonFields, relations, components }) { @@ -182,6 +183,14 @@ const ConfigType = class ConfigType { const currentConfig = formattedDiff.databaseConfig[configName]; + if (!currentConfig && formattedDiff.invalidConfig[configName]) { + throw new InvalidConfigFileError( + `Cannot export '${configName}': the config file is invalid and no database config exists to replace it.`, + configName, + 'no_database_config', + ); + } + if ( !currentConfig && formattedDiff.fileConfig[configName] diff --git a/server/controllers/config.js b/server/controllers/config.js index 44c02f54..5ddf9ee9 100644 --- a/server/controllers/config.js +++ b/server/controllers/config.js @@ -2,6 +2,18 @@ import fs from 'fs'; import isEmpty from 'lodash/isEmpty'; +import InvalidConfigFileError from '../utils/invalidConfigFileError'; + +const withConfigFileErrors = async (ctx, action) => { + try { + return await action(); + } catch (error) { + if (error instanceof InvalidConfigFileError) { + return ctx.badRequest(error.message, error.details); + } + throw error; + } +}; /** * Main controllers for config import/export. @@ -14,7 +26,7 @@ export default { * @param {object} ctx - Request context object. * @returns {void} */ - exportAll: async (ctx) => { + exportAll: async (ctx) => withConfigFileErrors(ctx, async () => { if (isEmpty(ctx.request.body)) { await strapi.plugin('config-sync').service('main').exportAllConfig(); } else { @@ -27,7 +39,7 @@ export default { ctx.send({ message: `Config was successfully exported to ${strapi.config.get('plugin::config-sync.syncDir')}.`, }); - }, + }), /** * Import all config, from filesystem to db. @@ -35,7 +47,7 @@ export default { * @param {object} ctx - Request context object. * @returns {void} */ - importAll: async (ctx) => { + importAll: async (ctx) => withConfigFileErrors(ctx, async () => { // Check for existance of the config file sync dir. if (!fs.existsSync(strapi.config.get('plugin::config-sync.syncDir'))) { ctx.send({ @@ -60,7 +72,7 @@ export default { ctx.send({ message: 'Config was successfully imported.', }); - }, + }), /** * Get config diff between filesystem & db. diff --git a/server/services/main.js b/server/services/main.js index ebacc3a2..042f7523 100644 --- a/server/services/main.js +++ b/server/services/main.js @@ -4,9 +4,11 @@ import isEmpty from 'lodash/isEmpty'; import fs from 'fs'; import util from 'util'; import AdmZip from 'adm-zip'; +import { parse as parseJsonWithErrors } from 'jsonc-parser'; import difference from '../utils/getObjectDiff'; import { logMessage } from '../utils'; +import InvalidConfigFileError from '../utils/invalidConfigFileError'; /** * Main services for config import/export. @@ -91,6 +93,7 @@ export default () => ({ * @returns {object} The JSON content of the config file. */ readConfigFile: async (configType, configName) => { + const fullConfigName = `${configType}.${configName}`; // Replace reserved characters in filenames. configName = configName.replace(/:/g, "#").replace(/\//g, "$"); @@ -109,8 +112,22 @@ export default () => ({ try { return JSON.parse(data); } catch (e) { - // A file that can't be parsed is not a missing file: it must never lead to deleting the config. - throw new Error(`The config file '${filePath}' is not valid JSON (${e.message}).`); + const contents = data.toString('utf8'); + const errors = []; + parseJsonWithErrors(contents, errors, { disallowComments: true }); + let location = ''; + const position = e.message.match(/ at position (\d+)/); + if (position || errors.length) { + const offset = position ? Number(position[1]) : errors[0].offset; + const beforeError = contents.slice(0, offset); + const lines = beforeError.split(/\r\n|\r|\n/); + location = ` at line ${lines.length}, column ${lines[lines.length - 1].length + 1}`; + } + throw new InvalidConfigFileError( + `The config file '${filePath}' is not valid JSON${location} (${e.message}).`, + fullConfigName, + 'invalid_json', + ); } }, @@ -119,9 +136,10 @@ export default () => ({ * Get all the config JSON from the filesystem. * * @param {string} configType - Type of config to gather. Leave empty to get all config. + * @param {object} invalidConfig - Object that gets filled with the unreadable config files, keyed by config name. * @returns {object} Object with key value pairs of configs. */ - getAllConfigFromFiles: async (configType = null) => { + getAllConfigFromFiles: async (configType = null, invalidConfig = {}) => { if (!fs.existsSync(strapi.config.get('plugin::config-sync.syncDir'))) { return {}; } @@ -150,7 +168,8 @@ export default () => ({ try { fileContents = await strapi.plugin('config-sync').service('main').readConfigFile(type, name); } catch (e) { - strapi.log.warn(logMessage(`The config file '${file}' can't be read and is left out of the diff: ${e.message}`)); + strapi.log.warn(logMessage(`The config file '${file}' can't be read: ${e.message}`)); + invalidConfig[`${type}.${formattedName}`] = e.message; return; } @@ -264,6 +283,7 @@ export default () => ({ const importState = await strapi.plugin('config-sync').types[type].importSingle(name, fileContents, force); if (onSuccess && importState !== false) onSuccess(`${type}.${name}`); } catch (e) { + if (e instanceof InvalidConfigFileError) throw e; throw new Error(`Error when trying to import ${type}.${name}. ${e}`); } }, @@ -288,6 +308,7 @@ export default () => ({ await strapi.plugin('config-sync').types[type].exportSingle(configName); if (onSuccess) onSuccess(`${type}.${name}`); } catch (e) { + if (e instanceof InvalidConfigFileError) throw e; throw new Error(`Error when trying to export ${type}.${name}. ${e}`); } }, @@ -304,13 +325,19 @@ export default () => ({ fileConfig: {}, databaseConfig: {}, diff: {}, + invalidConfig: {}, }; - const fileConfig = await strapi.plugin('config-sync').service('main').getAllConfigFromFiles(configType); + const fileConfig = await strapi.plugin('config-sync').service('main').getAllConfigFromFiles(configType, formattedDiff.invalidConfig); const databaseConfig = await strapi.plugin('config-sync').service('main').getAllConfigFromDatabase(configType); const diff = difference(databaseConfig, fileConfig); + // Unreadable files always show up in the diff, so they can't go unnoticed. + Object.keys(formattedDiff.invalidConfig).forEach((name) => { + diff[name] = diff[name] || databaseConfig[name] || {}; + }); + formattedDiff.diff = diff; Object.keys(diff).map((changedConfigName) => { diff --git a/server/utils/invalidConfigFileError.js b/server/utils/invalidConfigFileError.js new file mode 100644 index 00000000..b538dad7 --- /dev/null +++ b/server/utils/invalidConfigFileError.js @@ -0,0 +1,8 @@ +class InvalidConfigFileError extends Error { + constructor(message, configName, reason) { + super(message); + this.details = { code: 'CONFIG_SYNC_INVALID_FILE', configName, reason }; + } +} + +export default InvalidConfigFileError; diff --git a/yarn.lock b/yarn.lock index 6328c35e..e99b10b9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10417,6 +10417,11 @@ json5@^2.1.2, json5@^2.2.3: resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== +jsonc-parser@^3.3.1: + version "3.3.1" + resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.3.1.tgz#f2a524b4f7fd11e3d791e559977ad60b98b798b4" + integrity sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ== + jsonfile@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb"