Skip to content

Commit

Permalink
chore: Comply to the new lint rules
Browse files Browse the repository at this point in the history
  • Loading branch information
XhmikosR committed Dec 17, 2023
1 parent d1b8d7c commit ce2a26f
Show file tree
Hide file tree
Showing 50 changed files with 174 additions and 146 deletions.
5 changes: 3 additions & 2 deletions src/__mocks__/glob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ module.exports = (
const paths = mockGlobs[glob];

if (!paths) {
return callback(new Error(`Invalid glob: ${glob}`), null);
callback(new Error(`Invalid glob: ${glob}`), null);
return;
}

return callback(null, paths);
callback(null, paths);
});
};
16 changes: 7 additions & 9 deletions src/__mocks__/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,17 @@ const resolve = (...paths: string[]) => {
let path = '';

for (const cur of paths) {
path = !path ? normalize(cur) : _path.join(path, normalize(cur));
path = path ? _path.join(path, normalize(cur)) : normalize(cur);
}

if (path.startsWith(projectDir)) {
path = _path.join('/root/project', path.substr(projectDir.length));
} else if (path.startsWith('/') && !path.startsWith('/root')) {
path = _path.join('/root/', path.substr(1));
} else {
if (path.startsWith('./')) {
path = _path.join('/root/project/', path.substr(2));
} else if (!path.startsWith('/')) {
path = _path.join('/root/project/', path);
}
} else if (path.startsWith('./')) {
path = _path.join('/root/project/', path.substr(2));
} else if (!path.startsWith('/')) {
path = _path.join('/root/project/', path);
}

return normalize(path);
Expand All @@ -31,7 +29,7 @@ const relative = (a: string, b: string) =>
const join = (...segments: string[]): string => {
const trimmed: string[] = [];

segments.forEach((current, i) => {
for (let [i, current] of segments.entries()) {
const isFirst = i === 0;
const isLast = i === segments.length - 1;

Expand All @@ -44,7 +42,7 @@ const join = (...segments: string[]): string => {
}

trimmed.push(current);
});
}

return trimmed.join('/');
};
Expand Down
7 changes: 4 additions & 3 deletions src/cli/config-loader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { readFile } from 'fs/promises';
import { join } from 'path';
import process from 'process';
import { checkPath } from '../utils/fs-async';

export const DEFAULT_FILEPATHS = [
Expand All @@ -11,17 +12,17 @@ export const DEFAULT_FILEPATHS = [
'fantasticonrc.js'
];

const attemptLoading = async (filepath: string): Promise<any | void> => {
const attemptLoading = async (filepath: string) => {
const fileExists = await checkPath(filepath, 'file');
if (fileExists) {
try {
return require(join(process.cwd(), filepath));
} catch (err) {}
} catch {}

try {
const content = await readFile(filepath, 'utf8');
return JSON.parse(content);
} catch (err) {}
} catch {}

throw new Error(`Failed parsing configuration at '${filepath}'`);
}
Expand Down
20 changes: 8 additions & 12 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import process from 'process';
import commander from 'commander';
import { FontAssetType, OtherAssetType } from '../types/misc';
import { loadConfig, DEFAULT_FILEPATHS } from './config-loader';
import { DEFAULT_OPTIONS } from '../constants';
import { generateFonts } from '../core/runner';
import { removeUndefined } from '../utils/validation';
import { loadConfig, DEFAULT_FILEPATHS } from './config-loader';
import { getLogger } from './logger';

const {
bin,
name: packageName,
version
} = require('../../package.json') as any;
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { bin, name: packageName, version } = require('../../package.json');

const getCommandName = () => (bin && Object.keys(bin)[0]) || packageName;

Expand All @@ -37,11 +34,9 @@ const printList = (available: { [key: string]: string }, defaults: string[]) =>
).join(', ')})`;

const printDefaultValue = (value: any) => {
let printVal = String(value);
const printVal = String(value);

if (typeof value === 'undefined') {
return '';
}
if (value === undefined) return '';

return ` (default: ${printVal})`;
};
Expand Down Expand Up @@ -137,6 +132,7 @@ const buildOptions = async (cmd: commander.Command, loadedConfig = {}) => {
};
};

const run = async (options: any) => await generateFonts(options, true);
const run = async (options: any) => generateFonts(options, true);

// eslint-disable-next-line @typescript-eslint/no-floating-promises
cli();
1 change: 1 addition & 0 deletions src/cli/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const getLogger = (debug = false, silent = false) => ({
this.log(picocolor.yellow('Generating font kit...'));

if (!loadedConfigPath) return;

this.log(
picocolor.green(
`${figures.tick} Using configuration file: ${picocolor.green(
Expand Down
4 changes: 2 additions & 2 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { resolve } from 'path';
import { RunnerOptions } from './types/runner';
import { FontAssetType, OtherAssetType } from './types/misc';
import { RunnerOptions } from './types/runner';
import { getIconId } from './utils/icon-id';

export const TEMPLATES_DIR = resolve(__dirname, '../templates');
Expand All @@ -26,7 +26,7 @@ export const DEFAULT_OPTIONS: Omit<RunnerOptions, 'inputDir' | 'outputDir'> = {
tag: 'i',
prefix: 'icon',
fontsUrl: undefined,
getIconId: getIconId
getIconId
};

export const DEFAULT_START_CODEPOINT = 0xf101;
22 changes: 11 additions & 11 deletions src/core/__tests__/config-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,19 @@ const mockConfig = {
};

const testError = async (options: object, key: string, message: string) =>
expect(() => parseConfig({ ...mockConfig, ...options })).rejects.toThrow(
`Invalid option ${key}: ${message}`
);
expect(async () =>
parseConfig({ ...mockConfig, ...options })
).rejects.toThrow(`Invalid option ${key}: ${message}`);

const testParsed = async (key: string, input: any, output: any) =>
expect((await parseConfig({ ...mockConfig, [key]: input }))[key]).toEqual(
output
);
const testParsed = async (key: string, input: any, output: any) => {
const config = await parseConfig({ ...mockConfig, [key]: input });
expect(config[key]).toEqual(output);
};

describe('Config parser', () => {
beforeEach(() => {
checkPathMock.mockClear();
checkPathMock.mockImplementation(() => Promise.resolve(true));
checkPathMock.mockImplementation(async () => true);
});

test('returns correctly parsed input when valid', async () => {
Expand Down Expand Up @@ -93,11 +93,11 @@ describe('Config parser', () => {
});

test('correctly validates existance of input and output paths', async () => {
checkPathMock.mockImplementationOnce(() => Promise.resolve(false));
checkPathMock.mockImplementationOnce(async () => false);

await testError({ inputDir: 'foo' }, 'inputDir', 'foo is not a directory');

checkPathMock.mockImplementation(val => Promise.resolve(val !== 'bar'));
checkPathMock.mockImplementation(async val => val !== 'bar');

await testError(
{ outputDir: 'bar' },
Expand All @@ -107,7 +107,7 @@ describe('Config parser', () => {
});

test('throws expected error when passing an unrecognised option', async () => {
await expect(() =>
await expect(async () =>
parseConfig({ ...mockConfig, foo: 'bar' })
).rejects.toThrow("The option 'foo' is not recognised");
});
Expand Down
14 changes: 7 additions & 7 deletions src/core/__tests__/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,18 @@ jest.mock('../../constants', () => ({
}));

jest.mock('../../generators', () => ({
generateAssets: jest.fn(options =>
Promise.resolve({ mockGenerated: { assets: {}, options } })
)
generateAssets: jest.fn(async options => ({
mockGenerated: { assets: {}, options }
}))
}));

jest.mock('../../generators/generator-options', () => ({
getGeneratorOptions: jest.fn(() => ({ mock: 'generator-options' }))
}));

jest.mock('../../utils/assets', () => ({
writeAssets: jest.fn(() => Promise.resolve([{ mock: 'writeResult' }])),
loadAssets: jest.fn(() => Promise.resolve({ mock: 'assets' }))
writeAssets: jest.fn(async () => [{ mock: 'writeResult' }]),
loadAssets: jest.fn(async () => ({ mock: 'assets' }))
}));

jest.mock('../config-parser', () => ({
Expand Down Expand Up @@ -82,15 +82,15 @@ describe('Runner', () => {
test('`generateFonts` throws error if `outputDir` is not given and `mustWrite` is `true`', async () => {
const optionsIn = { inputDir: 'foo' } as any;

await expect(() => generateFonts(optionsIn, true)).rejects.toThrow(
await expect(async () => generateFonts(optionsIn, true)).rejects.toThrow(
'You must specify an output directory'
);
});

test('`generateFonts` throws error if `inputDir` is not given', async () => {
const optionsIn = {} as any;

await expect(() => generateFonts(optionsIn)).rejects.toThrow(
await expect(async () => generateFonts(optionsIn)).rejects.toThrow(
'You must specify an input directory'
);
});
Expand Down
4 changes: 2 additions & 2 deletions src/core/config-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ export const parseConfig = async (input: object = {}) => {
for (const fn of validators) {
val = await fn(val, val);
}
} catch (err) {
throw new Error(`Invalid option ${key}: ${err.message}`);
} catch (error) {
throw new Error(`Invalid option ${key}: ${error.message}`);
}

out[key] = val;
Expand Down
4 changes: 2 additions & 2 deletions src/core/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import {
import { CodepointsMap } from '../utils/codepoints';
import { getGeneratorOptions } from '../generators/generator-options';
import { GeneratedAssets } from '../generators/generate-assets';
import { parseConfig } from './config-parser';
import { generateAssets } from '../generators';
import { parseConfig } from './config-parser';

export interface RunnerResults {
options: RunnerOptions;
Expand All @@ -20,7 +20,7 @@ export interface RunnerResults {
codepoints: CodepointsMap;
}

export const sanitiseOptions = (userOptions: any) =>
export const sanitiseOptions = async (userOptions: any) =>
parseConfig({
...DEFAULT_OPTIONS,
...userOptions
Expand Down
5 changes: 3 additions & 2 deletions src/generators/asset-types/__tests__/css.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import cssGen from '../css';
import { renderSrcAttribute } from '../../../utils/css';
import { Buffer } from 'buffer';
import { resolve } from 'path';
import { renderSrcAttribute } from '../../../utils/css';
import cssGen from '../css';

const renderSrcMock = renderSrcAttribute as any as jest.Mock;

Expand Down
3 changes: 2 additions & 1 deletion src/generators/asset-types/__tests__/eot.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Buffer } from 'buffer';
import _ttf2eot from 'ttf2eot';
import { FontGeneratorOptions } from '../../../types/generator';
import eotGen from '../eot';
Expand All @@ -9,7 +10,7 @@ jest.mock('ttf2eot', () =>
);

const mockOptions = (eotOptions = { __mock: 'options__' } as any) =>
({}) as unknown as FontGeneratorOptions;
({} as unknown as FontGeneratorOptions);

const ttf = '::ttf::' as unknown as Buffer;

Expand Down
2 changes: 1 addition & 1 deletion src/generators/asset-types/__tests__/html.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import htmlGen from '../html';
import { resolve } from 'path';
import htmlGen from '../html';

const mockOptions = {
name: 'test-font',
Expand Down
6 changes: 3 additions & 3 deletions src/generators/asset-types/__tests__/json.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import jsonGen from '../json';
import { OtherAssetType } from '../../../types/misc';
import { DEFAULT_OPTIONS } from '../../../constants';
import { OtherAssetType } from '../../../types/misc';
import jsonGen from '../json';

const mockCodepoints = { foo: 'oof', bar: 'baz' };

const mockOptions = (jsonOptions: any = {}) =>
({
codepoints: mockCodepoints,
formatOptions: { [OtherAssetType.JSON]: jsonOptions }
}) as any;
} as any);

const renderAndParse = async (jsonOptions?: any) =>
JSON.parse(
Expand Down
5 changes: 3 additions & 2 deletions src/generators/asset-types/__tests__/sass.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import sassGen from '../sass';
import { renderSrcAttribute } from '../../../utils/css';
import { Buffer } from 'buffer';
import { resolve } from 'path';
import { renderSrcAttribute } from '../../../utils/css';
import sassGen from '../sass';

const renderSrcMock = renderSrcAttribute as any as jest.Mock;

Expand Down
5 changes: 3 additions & 2 deletions src/generators/asset-types/__tests__/scss.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import scssGen from '../scss';
import { renderSrcAttribute } from '../../../utils/css';
import { Buffer } from 'buffer';
import { resolve } from 'path';
import { renderSrcAttribute } from '../../../utils/css';
import scssGen from '../scss';

const renderSrcMock = renderSrcAttribute as any as jest.Mock;

Expand Down
8 changes: 4 additions & 4 deletions src/generators/asset-types/__tests__/svg.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Buffer } from 'buffer';
import EventEmitter from 'events';
import * as _SVGIcons2SVGFontStream from 'svgicons2svgfont';
import { FontAssetType } from '../../../types/misc';
import { FontGeneratorOptions } from '../../../types/generator';
import { FontAssetType } from '../../../types/misc';
import svgGen from '../svg';

const SVGIcons2SVGFontStream = _SVGIcons2SVGFontStream as unknown as jest.Mock<
Expand All @@ -14,8 +16,6 @@ jest.mock('fs', () => ({
}));

jest.mock('svgicons2svgfont', () => {
const { EventEmitter } = require('events');

class MockStream {
public events = new EventEmitter();
public content = '';
Expand Down Expand Up @@ -56,7 +56,7 @@ const mockOptions = (svgOptions = { __mock: 'options__' } as any) =>
foo: { id: 'foo', absolutePath: '/root/foo.svg' },
bar: { id: 'bar', absolutePath: '/root/bar.svg' }
}
}) as unknown as FontGeneratorOptions;
} as unknown as FontGeneratorOptions);

describe('`SVG` font generator', () => {
beforeEach(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/generators/asset-types/__tests__/ts.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { dirname, join } from 'path';
import tsGen from '../ts';
import { join, dirname } from 'path';

const mockAssets = {
foo: {
Expand Down
5 changes: 3 additions & 2 deletions src/generators/asset-types/__tests__/ttf.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Buffer } from 'buffer';
import _svg2ttf from 'svg2ttf';
import { FontAssetType } from '../../../types/misc';
import { FontGeneratorOptions } from '../../../types/generator';
import { FontAssetType } from '../../../types/misc';
import ttfGen from '../ttf';

const svg2ttf = _svg2ttf as unknown as jest.Mock<typeof _svg2ttf>;
Expand All @@ -12,7 +13,7 @@ jest.mock('svg2ttf', () =>
const mockOptions = (ttfOptions = { __mock: 'options__' } as any) =>
({
formatOptions: { [FontAssetType.TTF]: ttfOptions }
}) as unknown as FontGeneratorOptions;
} as unknown as FontGeneratorOptions);

const svg = '::svg::';

Expand Down
Loading

0 comments on commit ce2a26f

Please sign in to comment.