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

Add aliases support for add-icon-data script #7863

Merged
merged 5 commits into from
Sep 28, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
56 changes: 54 additions & 2 deletions scripts/add-icon-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import getRelativeLuminance from 'get-relative-luminance';
import {
URL_REGEX,
collator,
getJsonSchemaData,
getIconsDataString,
getIconDataPath,
writeIconsData,
Expand All @@ -15,6 +16,7 @@ import {
const hexPattern = /^#?[a-f0-9]{3,8}$/i;

const iconsData = JSON.parse(await getIconsDataString());
const jsonSchema = await getJsonSchemaData();

const titleValidator = (text) => {
if (!text) return 'This field is required';
Expand Down Expand Up @@ -42,6 +44,18 @@ const hexTransformer = (text) => {
return chalk.bgHex(`#${color}`).hex(luminance < 0.4 ? '#fff' : '#000')(text);
};

const aliasesTransformer = (text) =>
text
.split(',')
.map((x) => chalk.cyan(x))
.join(',');

const aliasesChoices = Object.entries(
jsonSchema.definitions.brand.properties.aliases.properties,
)
.filter(([k]) => k !== 'loc')
.map(([k, v]) => ({ name: `${k}: ${v.description}`, value: k }));

const getIconDataFromAnswers = (answers) => ({
title: answers.title,
hex: answers.hex,
Expand All @@ -55,6 +69,21 @@ const getIconDataFromAnswers = (answers) => ({
},
}
: {}),
...(answers.hasAliases
? {
aliases: aliasesChoices.reduce((previous, current) => {
const promptKey = `${current.value}AliasesList`;
if (answers[promptKey])
return {
...previous,
[current.value]: answers[promptKey]
.split(',')
.map((x) => x.trim()),
};
return previous;
}, {}),
}
: {}),
});

const dataPrompt = [
Expand Down Expand Up @@ -112,7 +141,29 @@ const dataPrompt = [
},
{
type: 'confirm',
name: 'confirm',
name: 'hasAliases',
message: 'The icon has brand aliases?',
default: false,
},
{
type: 'checkbox',
name: 'aliasesTypes',
message: 'What types of aliases do you want to add?',
choices: aliasesChoices,
when: ({ hasAliases }) => hasAliases,
},
...aliasesChoices.map((x) => ({
type: 'input',
name: `${x.value}AliasesList`,
message: x.value,
suffix: ' (separate with commas)',
validate: (text) => Boolean(text),
transformer: aliasesTransformer,
when: (answers) => answers?.aliasesTypes.includes(x.value),
})),
{
type: 'confirm',
name: 'confirmToAdd',
message: (answers) => {
const icon = getIconDataFromAnswers(answers);
return [
Expand All @@ -127,11 +178,12 @@ const dataPrompt = [
const answers = await inquirer.prompt(dataPrompt);
const icon = getIconDataFromAnswers(answers);

if (answers.confirm) {
if (answers.confirmToAdd) {
iconsData.icons.push(icon);
iconsData.icons.sort((a, b) => collator.compare(a.title, b.title));
await writeIconsData(iconsData);
} else {
console.log(answers);
LitoMore marked this conversation as resolved.
Show resolved Hide resolved
console.log('Aborted.');
process.exit(1);
}
36 changes: 16 additions & 20 deletions scripts/lint/jsonlint.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,23 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { Validator } from 'jsonschema';
import { getDirnameFromImportMeta, getIconsData } from '../utils.js';
import {
getDirnameFromImportMeta,
getIconsData,
getJsonSchemaData,
} from '../utils.js';

const icons = await getIconsData();
const __dirname = getDirnameFromImportMeta(import.meta.url);
const schema = await getJsonSchemaData(path.resolve(__dirname, '..', '..'));

const rootDir = path.resolve(__dirname, '..', '..');
const schemaFile = path.resolve(rootDir, '.jsonschema.json');
const validator = new Validator();
const result = validator.validate({ icons }, schema);
if (result.errors.length > 0) {
result.errors.forEach((error) => {
console.error(error);
});

(async () => {
const icons = await getIconsData();
const schema = JSON.parse(await fs.readFile(schemaFile, 'utf8'));

const validator = new Validator();
const result = validator.validate({ icons }, schema);
if (result.errors.length > 0) {
result.errors.forEach((error) => {
console.error(error);
});

console.error(
`Found ${result.errors.length} error(s) in simple-icons.json`,
);
process.exit(1);
}
})();
console.error(`Found ${result.errors.length} error(s) in simple-icons.json`);
process.exit(1);
}
39 changes: 27 additions & 12 deletions scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import path from 'node:path';
import fs from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { readFile } from 'node:fs';
LitoMore marked this conversation as resolved.
Show resolved Hide resolved

const TITLE_TO_SLUG_REPLACEMENTS = {
'+': 'plus',
Expand All @@ -30,6 +31,16 @@ const TITLE_TO_SLUG_RANGE_REGEX = /[^a-z0-9]/g;

export const URL_REGEX = /^https:\/\/[^\s]+$/;

/**
* Get the directory name where this file is located from `import.meta.url`,
* equivalent to the `__dirname` global variable in CommonJS.
* @param {String} importMetaUrl import.meta.url
*/
export const getDirnameFromImportMeta = (importMetaUrl) =>
path.dirname(fileURLToPath(importMetaUrl));

const __dirname = getDirnameFromImportMeta(import.meta.url);

/**
* Get the slug/filename for an icon.
* @param {Object} icon The icon data as it appears in _data/simple-icons.json
Expand Down Expand Up @@ -95,14 +106,26 @@ export const htmlFriendlyToTitle = (htmlFriendlyTitle) =>
(_, ref) => ({ quot: '"', amp: '&', lt: '<', gt: '>' }[ref]),
);

/**
* Get JSON schema data.
* @param {String|undefined} rootDir Path to the root directory of the project.
*/
export const getJsonSchemaData = async (
rootDir = path.resolve(__dirname, '..'),
) => {
const __dirname = getDirnameFromImportMeta(import.meta.url);
const jsonSchemaPath = path.resolve(rootDir, '.jsonschema.json');
const jsonSchemaString = await fs.readFile(jsonSchemaPath, 'utf8');
return JSON.parse(jsonSchemaString);
};

/**
* Get path of _data/simpe-icons.json.
* @param {String|undefined} rootDir Path to the root directory of the project.
*/
export const getIconDataPath = (rootDir) => {
if (rootDir === undefined) {
rootDir = path.resolve(getDirnameFromImportMeta(import.meta.url), '..');
}
export const getIconDataPath = (
rootDir = path.resolve(getDirnameFromImportMeta(import.meta.url), '..'),
) => {
return path.resolve(rootDir, '_data', 'simple-icons.json');
};

Expand Down Expand Up @@ -136,14 +159,6 @@ export const writeIconsData = async (iconsData, rootDir) => {
);
};

/**
* Get the directory name where this file is located from `import.meta.url`,
* equivalent to the `__dirname` global variable in CommonJS.
* @param {String} importMetaUrl import.meta.url
*/
export const getDirnameFromImportMeta = (importMetaUrl) =>
path.dirname(fileURLToPath(importMetaUrl));

/**
* Replace Windows newline characters by Unix ones.
* @param {String} text The text to replace
Expand Down