Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 43 additions & 23 deletions admin/src/components/ConfigDiff/index.jsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 (
<Modal.Root open={open} onOpenChange={onOpenChange}>
<Modal.Content>
Expand All @@ -43,26 +48,39 @@ const ConfigDiff = ({ oldValue, newValue, configName, open, onOpenChange }) => {
</Typography>
</Modal.Header>
<Modal.Body>
<Grid.Root paddingBottom={4} style={{ textAlign: 'center' }}>
<Grid.Item col={6}>
<Typography variant="delta" style={{ width: '100%' }}>
{formatMessage({ id: 'config-sync.ConfigDiff.SyncDirectory' })}
</Typography>
</Grid.Item>
<Grid.Item col={6}>
<Typography variant="delta" style={{ width: '100%' }}>
{formatMessage({ id: 'config-sync.ConfigDiff.Database' })}
{syncError && (
<Typography as="p" textColor="danger600" role="alert">
{syncError}
</Typography>
)}
{error ? (
<Typography textColor="danger600" style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>
{error}
</Typography>
) : (
<>
<Grid.Root paddingBottom={4} style={{ textAlign: 'center' }}>
<Grid.Item col={6}>
<Typography variant="delta" style={{ width: '100%' }}>
{formatMessage({ id: 'config-sync.ConfigDiff.SyncDirectory' })}
</Typography>
</Grid.Item>
<Grid.Item col={6}>
<Typography variant="delta" style={{ width: '100%' }}>
{formatMessage({ id: 'config-sync.ConfigDiff.Database' })}
</Typography>
</Grid.Item>
</Grid.Root>
<Typography variant="pi">
<ReactDiffViewer
oldValue={JSON.stringify(oldValue, null, 2) ?? ''}
newValue={JSON.stringify(newValue, null, 2) ?? ''}
splitView
compareMethod={DiffMethod.WORDS}
/>
</Typography>
</Grid.Item>
</Grid.Root>
<Typography variant="pi">
<ReactDiffViewer
oldValue={JSON.stringify(oldValue, null, 2) ?? ''}
newValue={JSON.stringify(newValue, null, 2) ?? ''}
splitView
compareMethod={DiffMethod.WORDS}
/>
</Typography>
</>
)}
</Modal.Body>
<Modal.Footer justifyContent="flex-end" gap={2}>
<ConfirmModal
Expand All @@ -73,7 +91,8 @@ const ConfigDiff = ({ oldValue, newValue, configName, open, onOpenChange }) => {
</Button>
)}
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);
}}
/>
Expand All @@ -85,7 +104,8 @@ const ConfigDiff = ({ oldValue, newValue, configName, open, onOpenChange }) => {
</Button>
)}
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);
}}
/>
Expand Down
5 changes: 5 additions & 0 deletions admin/src/components/ConfigList/ConfigListRow/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
5 changes: 5 additions & 0 deletions admin/src/components/ConfigList/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -150,6 +154,7 @@ const ConfigList = ({ diff, isLoading }) => {
<ConfigDiff
oldValue={diff.fileConfig?.[cName]}
newValue={diff.databaseConfig?.[cName]}
error={diff.invalidConfig?.[cName]}
configName={cName}
open={Boolean(cName)}
onOpenChange={(open, syncedName) => {
Expand Down
102 changes: 102 additions & 0 deletions admin/src/index.cy.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
25 changes: 21 additions & 4 deletions admin/src/state/actions/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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 {
Expand All @@ -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;
}
Expand All @@ -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 {
Expand All @@ -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;
}
Expand Down
4 changes: 4 additions & 0 deletions admin/src/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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!",

Expand All @@ -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",
Expand Down
3 changes: 3 additions & 0 deletions docs/docs/getting-started/admin-gui.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
2 changes: 2 additions & 0 deletions docs/docs/getting-started/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:_

<Tabs groupId="yarn-npm">
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading