Skip to content

Commit

Permalink
chore: Small code improvments
Browse files Browse the repository at this point in the history
  • Loading branch information
3y3 committed Dec 18, 2024
1 parent 4260d31 commit 2d859dd
Show file tree
Hide file tree
Showing 15 changed files with 66 additions and 73 deletions.
17 changes: 8 additions & 9 deletions src/commands/build/core/meta/utils.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import {composeFrontMatter, extractFrontMatter} from '@diplodoc/transform/lib/frontmatter';

export function addSourcePath(fileContent: string, sourcePath: string) {
const [frontMatter, strippedContent] = extractFrontMatter(
fileContent,
sourcePath,
);
const [frontMatter, strippedContent] = extractFrontMatter(fileContent, sourcePath);

if (frontMatter.sourcePath) {
return fileContent;
}

return composeFrontMatter({
...frontMatter,
sourcePath,
}, strippedContent);
return composeFrontMatter(
{
...frontMatter,
sourcePath,
},
strippedContent,
);
}

16 changes: 9 additions & 7 deletions src/commands/build/core/vars/VarsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {merge} from 'lodash';
import {dump, load} from 'js-yaml';

import {Run} from '~/commands/build';
import {freeze, own} from '~/utils';
import {freeze, normalizePath, own} from '~/utils';
import {AsyncParallelHook, AsyncSeriesWaterfallHook} from 'tapable';

export type VarsServiceConfig = {
Expand All @@ -31,6 +31,10 @@ type VarsServiceHooks = {
export class VarsService {
hooks: VarsServiceHooks;

get entries() {
return [...Object.entries(this.cache)];
}

private run: Run;

private logger: Run['logger'];
Expand All @@ -50,17 +54,19 @@ export class VarsService {
}

async init() {
const presets = (await this.run.glob('**/presets.yaml', {
const presets = await this.run.glob('**/presets.yaml', {
cwd: this.run.input,
ignore: this.config.ignore,
})) as RelativePath[];
});

for (const preset of presets) {
await this.load(preset);
}
}

async load(path: RelativePath) {
path = normalizePath(path);

const varsPreset = this.config.varsPreset || 'default';
const file = join(dirname(path), 'presets.yaml');

Expand Down Expand Up @@ -107,8 +113,4 @@ export class VarsService {
lineWidth: 120,
});
}

entries() {
return Object.entries(this.cache);
}
}
20 changes: 10 additions & 10 deletions src/commands/build/core/vars/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ function prepare(content: string | Error | Hash<string | Error>, options: Option

async function call(content: string | Error, options: Options = {}) {
const service = prepare(content, options);
const result = await service.load('./presets.yaml' as RelativePath);
const result = await service.load('presets.yaml' as NormalizedPath);

expect(service.dump(result)).toMatchSnapshot();
}
Expand Down Expand Up @@ -158,7 +158,7 @@ describe('vars', () => {
);

const result = await service.load(
'./subfolder/subfolder/subfolder/presets.yaml' as RelativePath,
'subfolder/subfolder/subfolder/presets.yaml' as NormalizedPath,
);

expect(service.dump(result)).toMatchSnapshot();
Expand All @@ -174,7 +174,7 @@ describe('vars', () => {

service.hooks.PresetsLoaded.tap('Test', spy);

await service.load('./presets.yaml' as RelativePath);
await service.load('presets.yaml' as NormalizedPath);

expect(spy).toHaveBeenCalledWith({default: {field1: 'value1'}}, 'presets.yaml');
});
Expand All @@ -189,7 +189,7 @@ describe('vars', () => {

service.hooks.Resolved.tap('Test', spy);

await service.load('./presets.yaml' as RelativePath);
await service.load('presets.yaml' as NormalizedPath);

expect(spy).toHaveBeenCalledWith({field1: 'value1'}, 'presets.yaml');
});
Expand All @@ -206,7 +206,7 @@ describe('vars', () => {
return presets;
});

const result = await service.load('./presets.yaml' as RelativePath);
const result = await service.load('presets.yaml' as NormalizedPath);

expect(service.dump(result)).toMatchSnapshot();
});
Expand All @@ -223,7 +223,7 @@ describe('vars', () => {
return presets;
});

const result = await service.load('./presets.yaml' as RelativePath);
const result = await service.load('presets.yaml' as NormalizedPath);

expect(service.dump(result)).toMatchSnapshot();
});
Expand All @@ -239,7 +239,7 @@ describe('vars', () => {
});

await expect(() =>
service.load('./presets.yaml' as RelativePath),
service.load('presets.yaml' as NormalizedPath),
).rejects.toThrow();
});

Expand All @@ -254,7 +254,7 @@ describe('vars', () => {
});

await expect(() =>
service.load('./presets.yaml' as RelativePath),
service.load('presets.yaml' as NormalizedPath),
).rejects.toThrow();
});

Expand All @@ -270,8 +270,8 @@ describe('vars', () => {
service.hooks.PresetsLoaded.tap('Test', spy1);
service.hooks.Resolved.tap('Test', spy2);

await service.load('./presets.yaml' as RelativePath);
await service.load('./presets.yaml' as RelativePath);
await service.load('presets.yaml' as NormalizedPath);
await service.load('presets.yaml' as NormalizedPath);

expect(spy1).toHaveBeenCalledOnce();
expect(spy2).toHaveBeenCalledOnce();
Expand Down
2 changes: 1 addition & 1 deletion src/commands/build/features/linter/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {Build} from '../..';
import type {Command} from '~/config';

import {resolve} from 'path';
import {resolve} from 'node:path';
import shell from 'shelljs';
import {LogLevels} from '@diplodoc/transform/lib/log';

Expand Down
6 changes: 3 additions & 3 deletions src/commands/build/features/templating/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ describe('Build template feature', () => {
it('should not save presets.yaml for html build', async () => {
const build = setupBuild({
globs: {
'**/presets.yaml': ['./presets.yaml'],
'**/presets.yaml': ['presets.yaml'] as NormalizedPath[],
},
files: {
'./presets.yaml': dedent`
Expand All @@ -238,7 +238,7 @@ describe('Build template feature', () => {
it('should save presets.yaml for md build with disabled templating', async () => {
const build = setupBuild({
globs: {
'**/presets.yaml': ['./presets.yaml'],
'**/presets.yaml': ['presets.yaml'] as NormalizedPath[],
},
files: {
'./presets.yaml': dedent`
Expand All @@ -259,7 +259,7 @@ describe('Build template feature', () => {
it('should filter presets.yaml for md build with disabled templating', async () => {
const build = setupBuild({
globs: {
'**/presets.yaml': ['./presets.yaml'],
'**/presets.yaml': ['presets.yaml'] as NormalizedPath[],
},
files: {
'./presets.yaml': dedent`
Expand Down
3 changes: 3 additions & 0 deletions src/globals.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ type RelativePath = string &
| `./${string}`
);

/**
* This is unix-like relative path with truncated heading ./
*/
type NormalizedPath = string & {
__type: 'path';
__mode: 'relative' & 'normalized';
Expand Down
29 changes: 9 additions & 20 deletions src/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,6 @@ type LoggerOptions = Readonly<{
quiet: boolean;
}>;

type MessageInfo = {
level: LogLevels;
message: string;
};

type Color = typeof red;

const Write = Symbol('write');
Expand Down Expand Up @@ -95,8 +90,6 @@ export class Logger implements LogConsumer {

private consumer: LogConsumer | null = null;

private buffer: MessageInfo[] = [];

private filters: ((level: LogLevels, message: string) => string)[];

constructor(
Expand All @@ -120,6 +113,9 @@ export class Logger implements LogConsumer {
* So if child and parent has the same topic with name 'proc',
* only local topic will be applied to message.
* Message will be decorated by local topic and will be passed to parent as raw string.
*
* @param {LogConsumer} consumer - parent logger
* @returns {Logger}
*/
pipe(consumer: LogConsumer) {
if (this.consumer && this.consumer !== consumer) {
Expand All @@ -128,18 +124,17 @@ export class Logger implements LogConsumer {

this.consumer = consumer;

for (const {level, message} of this.buffer) {
this.consumer[Symbol.for(level) as keyof LogConsumer](message);
}

this.buffer.length = 0;

return this;
}

/**
* Defines new write decorator to one of defined log channeld.
* Each decorator adds colored prefix to messages and apply preconfigured filters.
*
* @param {LogLevels} level
* @param {string} prefix - any bounded text prefix, which will be colored
* @param {Color} [color] - prefix color
* @returns new topic
*/
topic(level: LogLevels, prefix: string, color?: Color) {
const channel = Symbol.for(level) as keyof LogConsumer;
Expand Down Expand Up @@ -177,14 +172,7 @@ export class Logger implements LogConsumer {
return this;
}

clear() {
this.buffer.length = 0;

return this;
}

reset() {
this.clear();
for (const level of Object.values(LogLevel)) {
this[level].count = 0;
}
Expand All @@ -200,6 +188,7 @@ export class Logger implements LogConsumer {
if (this.consumer) {
this.consumer[Symbol.for(level) as keyof LogConsumer](message);
} else {
// eslint-disable-next-line no-console
console[level](message);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,12 +264,12 @@ export interface ResolverOptions {

export interface PathData {
pathToFile: string;
resolvedPathToFile: string;
resolvedPathToFile: AbsolutePath;
filename: string;
fileBaseName: string;
fileExtension: string;
outputDir: string;
outputPath: string;
outputDir: AbsolutePath;
outputPath: AbsolutePath;
outputFormat: string;
outputBundlePath: string;
outputTocDir: string;
Expand Down
4 changes: 2 additions & 2 deletions src/pages/redirect.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {join} from 'path';
import {BUNDLE_FOLDER, Lang, RTL_LANGS} from '../constants';
import {BUNDLE_FOLDER, RTL_LANGS} from '../constants';
import {PluginService} from '../services';

import manifest from '@diplodoc/client/manifest';

export function generateStaticRedirect(lang: Lang, link: string): string {
export function generateStaticRedirect(lang: string, link: string): string {
const isRTL = RTL_LANGS.includes(lang);

return `
Expand Down
2 changes: 1 addition & 1 deletion src/services/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export type PresetStorage = Map<string, YfmPreset>;
let presetStorage: PresetStorage = new Map();

function init(vars: VarsService) {
for (const [path, values] of vars.entries()) {
for (const [path, values] of vars.entries) {
presetStorage.set(dirname(path), values);
}
}
Expand Down
1 change: 0 additions & 1 deletion src/steps/processPages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ export async function processPages(run: Run): Promise<void> {
);

if (singlePage) {

if (outputFormat === 'html') {
await saveTocData(transformTocForSinglePage, 'single-page-toc');
}
Expand Down
7 changes: 4 additions & 3 deletions src/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function modifyValuesByKeys(
modifyFn: (value: string) => string,
) {
// Clone the object deeply with a customizer function that modifies matching keys
return cloneDeepWith(originalObj, function (value: unknown, key) {
return cloneDeepWith(originalObj, (value: unknown, key) => {
if (keysToFind.includes(key as string) && isString(value)) {
return modifyFn(value);
}
Expand Down Expand Up @@ -87,6 +87,7 @@ export type HookMeta = {
type: string;
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function intercept<T extends Hash<Hook<any, any> | HookMap<any>>>(
service: string,
hooks: T,
Expand All @@ -98,7 +99,7 @@ export function intercept<T extends Hash<Hook<any, any> | HookMap<any>>>(
const meta = {service, hook, name, type};

if (type === 'promise') {
info.fn = async (...args: any[]) => {
info.fn = async (...args: unknown[]) => {
try {
return await fn(...args);
} catch (error) {
Expand All @@ -110,7 +111,7 @@ export function intercept<T extends Hash<Hook<any, any> | HookMap<any>>>(
}
};
} else if (type === 'sync') {
info.fn = (...args: any[]) => {
info.fn = (...args: unknown[]) => {
try {
return fn(...args);
} catch (error) {
Expand Down
12 changes: 6 additions & 6 deletions tests/integrations/services/metadataAuthors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ describe('getContentWithUpdatedMetadata (Authors)', () => {
metadataOptions = {
pathData: {
pathToFile: '',
resolvedPathToFile: '',
resolvedPathToFile: '' as AbsolutePath,
filename: '',
fileBaseName: '',
fileExtension: '',
outputDir: '',
outputPath: '',
outputDir: '' as AbsolutePath,
outputPath: '' as AbsolutePath,
outputFormat: '',
outputBundlePath: '',
outputTocDir: '',
Expand Down Expand Up @@ -94,12 +94,12 @@ describe('getContentWithUpdatedMetadata (Authors)', () => {
const metadataOptions: MetaDataOptions = {
pathData: {
pathToFile: '',
resolvedPathToFile: '',
resolvedPathToFile: '' as AbsolutePath,
filename: '',
fileBaseName: '',
fileExtension: '',
outputDir: '',
outputPath: '',
outputDir: '' as AbsolutePath,
outputPath: '' as AbsolutePath,
outputFormat: '',
outputBundlePath: '',
outputTocDir: '',
Expand Down
Loading

0 comments on commit 2d859dd

Please sign in to comment.