2024-08-19 07:15:27 -06:00
|
|
|
import type { KnownProps } from 'editorconfig';
|
|
|
|
import { parse } from 'editorconfig';
|
2021-12-22 01:37:47 -07:00
|
|
|
import upath from 'upath';
|
2021-11-23 13:10:45 -07:00
|
|
|
import { GlobalConfig } from '../../config/global';
|
2022-10-25 09:47:17 -06:00
|
|
|
import { logger } from '../../logger';
|
2021-11-05 07:25:50 -06:00
|
|
|
import type { CodeFormat } from './code-format';
|
2022-11-05 03:12:03 -06:00
|
|
|
import type { IndentationType } from './indentation-type';
|
2021-11-05 07:25:50 -06:00
|
|
|
|
|
|
|
export class EditorConfig {
|
|
|
|
public static async getCodeFormat(fileName: string): Promise<CodeFormat> {
|
2023-07-12 13:57:09 -06:00
|
|
|
const localDir = GlobalConfig.get('localDir', '');
|
2022-10-25 09:47:17 -06:00
|
|
|
try {
|
|
|
|
const knownProps = await parse(upath.join(localDir, fileName));
|
|
|
|
return {
|
|
|
|
indentationSize: EditorConfig.getIndentationSize(knownProps),
|
|
|
|
indentationType: EditorConfig.getIndentationType(knownProps),
|
2024-01-05 02:40:37 -07:00
|
|
|
maxLineLength: knownProps.max_line_length as number | 'off' | undefined,
|
2022-10-25 09:47:17 -06:00
|
|
|
};
|
|
|
|
} catch (err) {
|
|
|
|
logger.warn({ err }, 'Failed to parse editor config');
|
|
|
|
return {};
|
|
|
|
}
|
2021-11-05 07:25:50 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
private static getIndentationType(
|
2023-11-07 08:50:29 -07:00
|
|
|
knownProps: KnownProps,
|
2021-11-05 07:25:50 -06:00
|
|
|
): IndentationType | undefined {
|
|
|
|
const { indent_style: indentStyle } = knownProps;
|
|
|
|
|
|
|
|
if (indentStyle === 'tab') {
|
2022-11-05 03:12:03 -06:00
|
|
|
return 'tab';
|
2021-11-05 07:25:50 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
if (indentStyle === 'space') {
|
2022-11-05 03:12:03 -06:00
|
|
|
return 'space';
|
2021-11-05 07:25:50 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
private static getIndentationSize(
|
2023-11-07 08:50:29 -07:00
|
|
|
knownProps: KnownProps,
|
2021-11-05 07:25:50 -06:00
|
|
|
): number | undefined {
|
|
|
|
const indentSize = Number(knownProps.indent_size);
|
|
|
|
|
|
|
|
if (!Number.isNaN(indentSize) && Number.isInteger(indentSize)) {
|
|
|
|
return indentSize;
|
|
|
|
}
|
|
|
|
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
}
|