Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating context passed for marketplace validation #527

Merged
merged 3 commits into from
Jun 21, 2021
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
10 changes: 7 additions & 3 deletions packages/cli/commands/marketplaceValidate/validateTheme.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,14 @@ exports.handler = async options => {
absoluteSrcPath,
themeFiles,
accountId
).then(results => {
logValidatorResults(results, { logAsJson: options.json });
).then(groupedResults => {
logValidatorResults(groupedResults, { logAsJson: options.json });

if (results.some(result => result.result === VALIDATION_RESULT.FATAL)) {
if (
groupedResults
.flat()
.some(result => result.result === VALIDATION_RESULT.FATAL)
) {
process.exit(1);
}
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
const fs = require('fs');
const path = require('path');

const ThemeValidator = require('../../validators/marketplaceValidators/theme/ThemeValidator');
const ThemeConfigValidator = require('../../validators/marketplaceValidators/theme/ThemeConfigValidator');
const { VALIDATION_RESULT } = require('../../validators/constants');
const { THEME_PATH } = require('./validatorTestUtils');

jest.mock('fs');
jest.mock('path');

describe('validators/marketplaceValidators/theme/ThemeValidator', () => {
describe('validators/marketplaceValidators/theme/ThemeConfigValidator', () => {
beforeEach(() => {
ThemeValidator.setThemePath(THEME_PATH);
ThemeConfigValidator.setThemePath(THEME_PATH);
});

it('returns error if no theme.json file exists', async () => {
const validationErrors = ThemeValidator.validate(['someFile.html']);
const validationErrors = ThemeConfigValidator.validate(['someFile.html']);
expect(validationErrors.length).toBe(1);
expect(validationErrors[0].result).toBe(VALIDATION_RESULT.FATAL);
});

it('returns error if theme.json file has invalid json', async () => {
fs.readFileSync.mockReturnValue('{} bad json }');

const validationErrors = ThemeValidator.validate(['theme.json']);
const validationErrors = ThemeConfigValidator.validate(['theme.json']);
expect(validationErrors.length).toBe(1);
expect(validationErrors[0].result).toBe(VALIDATION_RESULT.FATAL);
});

it('returns error if theme.json file is missing a label field', async () => {
fs.readFileSync.mockReturnValue('{ "screenshot_path": "./relative/path" }');

const validationErrors = ThemeValidator.validate(['theme.json']);
const validationErrors = ThemeConfigValidator.validate(['theme.json']);
expect(validationErrors.length).toBe(1);
expect(validationErrors[0].result).toBe(VALIDATION_RESULT.FATAL);
});
Expand All @@ -40,7 +40,7 @@ describe('validators/marketplaceValidators/theme/ThemeValidator', () => {
'{ "label": "yay", "screenshot_path": "/absolute/path" }'
);

const validationErrors = ThemeValidator.validate(['theme.json']);
const validationErrors = ThemeConfigValidator.validate(['theme.json']);
expect(validationErrors.length).toBe(1);
expect(validationErrors[0].result).toBe(VALIDATION_RESULT.FATAL);
});
Expand All @@ -52,7 +52,7 @@ describe('validators/marketplaceValidators/theme/ThemeValidator', () => {
path.relative.mockReturnValue('theme.json');
fs.existsSync.mockReturnValue(false);

const validationErrors = ThemeValidator.validate(['theme.json']);
const validationErrors = ThemeConfigValidator.validate(['theme.json']);
expect(validationErrors.length).toBe(1);
expect(validationErrors[0].result).toBe(VALIDATION_RESULT.FATAL);
});
Expand All @@ -64,7 +64,7 @@ describe('validators/marketplaceValidators/theme/ThemeValidator', () => {
path.relative.mockReturnValue('theme.json');
fs.existsSync.mockReturnValue(true);

const validationErrors = ThemeValidator.validate(['theme.json']);
const validationErrors = ThemeConfigValidator.validate(['theme.json']);
expect(validationErrors.length).toBe(0);
});
});
2 changes: 1 addition & 1 deletion packages/cli/lib/validators/applyValidators.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ async function applyValidators(validators, absoluteThemePath, ...args) {
}
return validationResult;
})
).then(errorsGroupedByValidatorType => errorsGroupedByValidatorType.flat());
);
}

module.exports = { applyValidators };
8 changes: 7 additions & 1 deletion packages/cli/lib/validators/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,11 @@ const FATAL = 'FATAL';
const SUCCESS = 'SUCCESS';

const VALIDATION_RESULT = { WARNING, FATAL, SUCCESS };
const VALIDATOR_KEYS = {
dependency: 'dependency',
module: 'module',
template: 'template',
themeConfig: 'themeConfig',
};

module.exports = { VALIDATION_RESULT };
module.exports = { VALIDATOR_KEYS, VALIDATION_RESULT };
4 changes: 2 additions & 2 deletions packages/cli/lib/validators/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const ThemeValidator = require('./marketplaceValidators/theme/ThemeValidator');
const ThemeConfigValidator = require('./marketplaceValidators/theme/ThemeConfigValidator');
const TemplateValidator = require('./marketplaceValidators/theme/TemplateValidator');
const ModuleValidator = require('./marketplaceValidators/theme/ModuleValidator');
const DependencyValidator = require('./marketplaceValidators/theme/DependencyValidator');

const MARKETPLACE_VALIDATORS = {
theme: [
ThemeValidator,
ThemeConfigValidator,
TemplateValidator,
ModuleValidator,
DependencyValidator,
Expand Down
69 changes: 38 additions & 31 deletions packages/cli/lib/validators/logValidatorResults.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
const chalk = require('chalk');
const { logger } = require('@hubspot/cli-lib/logger');
const { VALIDATION_RESULT } = require('./constants');

function logResultsAsJson(results) {
function logResultsAsJson(groupedResults) {
let success = true;
const resultObj = results.reduce((acc, result) => {
if (!acc[result.validatorKey]) {
if (success && result.result !== VALIDATION_RESULT.SUCCESS) {
success = false;
const resultObj = groupedResults.reduce((acc, resultList) => {
resultList.forEach(result => {
if (!acc[result.validatorKey]) {
if (success && result.result !== VALIDATION_RESULT.SUCCESS) {
success = false;
}
acc[result.validatorKey] = [];
}
acc[result.validatorKey] = [];
}
const {
validatorName: __omit1, // eslint-disable-line no-unused-vars
validatorKey: __omit2, // eslint-disable-line no-unused-vars
...resultWithOmittedValues
} = result;
acc[result.validatorKey].push(resultWithOmittedValues);
const {
validatorName: __omit1, // eslint-disable-line no-unused-vars
validatorKey: __omit2, // eslint-disable-line no-unused-vars
...resultWithOmittedValues
} = result;
acc[result.validatorKey].push(resultWithOmittedValues);
});
return acc;
}, {});
const result = {
Expand All @@ -26,27 +29,31 @@ function logResultsAsJson(results) {
process.stdout.write(JSON.stringify(result) + '\n');
}

function logValidatorResults(results, { logAsJson = false } = {}) {
function logValidatorResults(groupedResults, { logAsJson = false } = {}) {
if (logAsJson) {
return logResultsAsJson(results);
return logResultsAsJson(groupedResults);
}
results.forEach(({ error, validatorName, result }) => {
const message = `${validatorName}: ${error}`;
switch (result) {
case VALIDATION_RESULT.WARNING:
logger.warn(message);
break;
case VALIDATION_RESULT.FATAL:
logger.error(message);
break;
case VALIDATION_RESULT.SUCCESS:
logger.success(validatorName);
break;
default:
logger.log(message);
}
groupedResults.forEach(results => {
logger.log(chalk.bold(`${results[0].validatorName} validation results:`));
logger.group();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

results.forEach(({ error, result }) => {
switch (result) {
case VALIDATION_RESULT.WARNING:
logger.warn(error);
break;
case VALIDATION_RESULT.FATAL:
logger.error(error);
break;
case VALIDATION_RESULT.SUCCESS:
logger.success('No errors');
break;
default:
logger.log(error);
}
});
logger.log('\n');
logger.groupEnd();
});
logger.log('\n');
}

module.exports = { logValidatorResults };
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,19 @@ class BaseValidator {
};
}

getError(errorObj, file, extraCopyPlaceholders = {}) {
getError(errorObj, file, extraContext = {}) {
const relativeFilePath = file ? this.getRelativePath(file) : null;
const copyPlaceholders = {
file: relativeFilePath,
...extraCopyPlaceholders,
const context = {
filePath: relativeFilePath,
...extraContext,
};
return {
validatorKey: this.key,
validatorName: this.name,
error: errorObj.getCopy(copyPlaceholders),
error: errorObj.getCopy(context),
result: errorObj.severity || VALIDATION_RESULT.FATAL,
key: `${this.key}.${errorObj.key}`,
file: relativeFilePath,
context,
};
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const { fetchDependencies } = require('@hubspot/cli-lib/api/marketplace');
const { getExt, isRelativePath } = require('@hubspot/cli-lib/path');

const BaseValidator = require('../BaseValidator');
const { VALIDATOR_KEYS } = require('../../constants');

const MISSING_ASSET_CATEGORY_TYPES = [
'MISSING_RESOURCE',
Expand All @@ -24,17 +25,18 @@ class DependencyValidator extends BaseValidator {
this.errors = {
FAILED_TO_FETCH_DEPS: {
key: 'failedDepFetch',
getCopy: ({ file }) => `Failed to fetch dependencies for ${file}`,
getCopy: ({ filePath }) =>
`Internal Error. Failed to fetch dependencies for ${filePath}. Please try again`,
},
EXTERNAL_DEPENDENCY: {
key: 'externalDependency',
getCopy: ({ file, path }) =>
`${file} contains a path that points to an external dependency (${path})`,
getCopy: ({ filePath, referencedFilePath }) =>
`External dependency. ${filePath} references a file (${referencedFilePath}) that is outside of the theme`,
},
ABSOLUTE_DEPENDENCY_PATH: {
key: 'absoluteDependencyPath',
getCopy: ({ file, path }) =>
`${file} contains an absolute path (${path})`,
getCopy: ({ filePath, referencedFilePath }) =>
`Relative path required. ${filePath} references a file (${referencedFilePath}) using an absolute path`,
},
};
}
Expand Down Expand Up @@ -121,13 +123,13 @@ class DependencyValidator extends BaseValidator {
if (!isRelativePath(dependency)) {
validationErrors.push(
this.getError(this.errors.ABSOLUTE_DEPENDENCY_PATH, file, {
path: dependency,
referencedFilePath: dependency,
})
);
} else if (this.isExternalDep(file, dependency)) {
validationErrors.push(
this.getError(this.errors.EXTERNAL_DEPENDENCY, file, {
path: dependency,
referencedFilePath: dependency,
})
);
}
Expand All @@ -142,5 +144,5 @@ class DependencyValidator extends BaseValidator {

module.exports = new DependencyValidator({
name: 'Dependency',
key: 'dependency',
key: VALIDATOR_KEYS.dependency,
});
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const fs = require('fs');
const path = require('path');

const BaseValidator = require('../BaseValidator');
const { isModuleFolderChild } = require('@hubspot/cli-lib/modules');
const BaseValidator = require('../BaseValidator');
const { VALIDATOR_KEYS } = require('../../constants');

const MODULE_LIMIT = 50;

Expand All @@ -14,25 +15,27 @@ class ModuleValidator extends BaseValidator {
LIMIT_EXCEEDED: {
key: 'limitExceeded',
getCopy: ({ limit, total }) =>
`Cannot exceed ${limit} modules in your theme (found ${total})`,
`Module limit exceeded. Themes can only have ${limit} modules, but this theme has ${total}`,
},
MISSING_META_JSON: {
key: 'missingMetaJSON',
getCopy: ({ file }) => `Missing a meta.json file for ${file}`,
getCopy: ({ filePath }) =>
`Module ${filePath} is missing the meta.json file`,
},
INVALID_META_JSON: {
key: 'invalidMetaJSON',
getCopy: ({ file }) => `Invalid json in meta.json file for ${file}`,
getCopy: ({ filePath }) =>
`Module ${filePath} has invalid json in the meta.json file`,
},
MISSING_LABEL: {
key: 'missingLabel',
getCopy: ({ file }) =>
`The meta.json file is missing a "label" field for ${file}`,
getCopy: ({ filePath }) =>
`Missing required field for ${filePath}. The meta.json file is missing the "label" field`,
},
MISSING_ICON: {
key: 'missingIcon',
getCopy: ({ file }) =>
`The meta.json file is missing an "icon" field for ${file}`,
getCopy: ({ filePath }) =>
`Missing required field for ${filePath}. The meta.json file is missing the "icon" field`,
},
};
}
Expand Down Expand Up @@ -110,5 +113,5 @@ class ModuleValidator extends BaseValidator {

module.exports = new ModuleValidator({
name: 'Module',
key: 'module',
key: VALIDATOR_KEYS.module,
});
Loading