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

feat(config-migration): support editorconfig max_line_length #26513

Merged
merged 2 commits into from
Jan 5, 2024
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
1 change: 1 addition & 0 deletions lib/util/json-writer/__fixtures__/.global_editorconfig
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[*]
indent_style = space
indent_size = 6
max_line_length = 160
3 changes: 3 additions & 0 deletions lib/util/json-writer/__fixtures__/.json_editorconfig
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
[*]
max_line_length = off

[*.json]
indent_style = tab
1 change: 1 addition & 0 deletions lib/util/json-writer/code-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ import type { IndentationType } from './indentation-type';
export interface CodeFormat {
indentationSize?: number;
indentationType?: IndentationType;
maxLineLength?: number | 'off';
}
8 changes: 3 additions & 5 deletions lib/util/json-writer/editor-config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,28 +33,27 @@ describe('util/json-writer/editor-config', () => {
});

it('should handle empty .editorconfig file', async () => {
expect.assertions(2);
Fixtures.mock({
'.editorconfig': '',
});
const format = await EditorConfig.getCodeFormat(defaultConfigFile);

expect(format.indentationSize).toBeUndefined();
expect(format.indentationType).toBeUndefined();
expect(format.maxLineLength).toBeUndefined();
});

it('should handle global config from .editorconfig', async () => {
expect.assertions(2);
Fixtures.mock({
'.editorconfig': Fixtures.get('.global_editorconfig'),
});
const format = await EditorConfig.getCodeFormat(defaultConfigFile);
expect(format.indentationSize).toBe(6);
expect(format.indentationType).toBe('space');
expect(format.maxLineLength).toBe(160);
});

it('should return undefined in case of exception', async () => {
expect.assertions(2);
Fixtures.mock({
'.editorconfig': Fixtures.get('.global_editorconfig'),
});
Expand All @@ -70,7 +69,6 @@ describe('util/json-writer/editor-config', () => {
});

it('should not handle non json config from .editorconfig', async () => {
expect.assertions(2);
Fixtures.mock({
'.editorconfig': Fixtures.get('.non_json_editorconfig'),
});
Expand All @@ -81,12 +79,12 @@ describe('util/json-writer/editor-config', () => {
});

it('should handle json config from .editorconfig', async () => {
expect.assertions(1);
Fixtures.mock({
'.editorconfig': Fixtures.get('.json_editorconfig'),
});
const format = await EditorConfig.getCodeFormat(defaultConfigFile);

expect(format.indentationType).toBe('tab');
expect(format.maxLineLength).toBe('off');
});
});
1 change: 1 addition & 0 deletions lib/util/json-writer/editor-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export class EditorConfig {
return {
indentationSize: EditorConfig.getIndentationSize(knownProps),
indentationType: EditorConfig.getIndentationType(knownProps),
maxLineLength: knownProps.max_line_length as number | 'off' | undefined,
};
} catch (err) {
logger.warn({ err }, 'Failed to parse editor config');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import { mockedFunction, scm } from '../../../../../test/util';
import { migrateConfig } from '../../../../config/migration';
import { logger } from '../../../../logger';
import { readLocalFile } from '../../../../util/fs';
import { EditorConfig } from '../../../../util/json-writer';
import { detectRepoFileConfig } from '../../init/merge';
import { MigratedDataFactory, applyPrettierFormatting } from './migrated-data';

jest.mock('../../../../config/migration');
jest.mock('../../../../util/git');
jest.mock('../../../../util/fs');
jest.mock('../../../../util/json-writer');
jest.mock('../../init/merge');
jest.mock('detect-indent');

Expand Down Expand Up @@ -191,13 +193,42 @@ describe('workers/repository/config-migration/branch/migrated-data', () => {
});

it('formats with default 2 spaces', async () => {
mockedFunction(scm.getFileList).mockResolvedValue(['.prettierrc']);
mockedFunction(scm.getFileList).mockResolvedValue([
'.prettierrc',
'.editorconfig',
]);
mockedFunction(EditorConfig.getCodeFormat).mockResolvedValueOnce({
maxLineLength: 80,
});
await expect(
applyPrettierFormatting(migratedData.content, 'json', {
applyPrettierFormatting('.prettierrc', migratedData.content, 'json', {
amount: 0,
indent: ' ',
}),
).resolves.toEqual(formattedMigratedData.content);
});

it('formats with printWith=Infinity', async () => {
mockedFunction(scm.getFileList).mockResolvedValue([
'.prettierrc',
'.editorconfig',
]);
mockedFunction(EditorConfig.getCodeFormat).mockResolvedValueOnce({
maxLineLength: 'off',
});
await expect(
applyPrettierFormatting(
'.prettierrc',
`{\n"extends":[":separateMajorReleases",":prImmediately",":renovatePrefix",":semanticPrefixFixDepsChoreOthers"]}`,
'json',
{
amount: 0,
indent: ' ',
},
),
).resolves.toBe(
`{\n "extends": [":separateMajorReleases", ":prImmediately", ":renovatePrefix", ":semanticPrefixFixDepsChoreOthers"]\n}\n`,
);
});
});
});
27 changes: 24 additions & 3 deletions lib/workers/repository/config-migration/branch/migrated-data.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import is from '@sindresorhus/is';
import detectIndent from 'detect-indent';
import JSON5 from 'json5';
import type { BuiltInParserName } from 'prettier';
import type { BuiltInParserName, Options } from 'prettier';
import upath from 'upath';
import { migrateConfig } from '../../../../config/migration';
import { prettier } from '../../../../expose.cjs';
import { logger } from '../../../../logger';
import { scm } from '../../../../modules/platform/scm';
import { readLocalFile } from '../../../../util/fs';
import { EditorConfig } from '../../../../util/json-writer';
import { detectRepoFileConfig } from '../../init/merge';

export interface MigratedData {
Expand Down Expand Up @@ -37,6 +39,7 @@ const prettierConfigFilenames = new Set([
export type PrettierParser = BuiltInParserName;

export async function applyPrettierFormatting(
filename: string,
content: string,
parser: PrettierParser,
indent?: Indent,
Expand All @@ -48,6 +51,10 @@ export async function applyPrettierFormatting(
prettierConfigFilenames.has(file),
);

const editorconfigExists = fileList.some(
(file) => file === '.editorconfig',
);

if (!prettierExists) {
try {
const packageJsonContent = await readLocalFile('package.json', 'utf8');
Expand All @@ -63,12 +70,26 @@ export async function applyPrettierFormatting(
if (!prettierExists) {
return content;
}
const options = {

const options: Options = {
parser,
tabWidth: indent?.amount === 0 ? 2 : indent?.amount,
useTabs: indent?.type === 'tab',
};

if (editorconfigExists) {
const editorconf = await EditorConfig.getCodeFormat(filename);

// https://github.com/prettier/prettier/blob/bab892242a1f9d8fcae50514b9304bf03f2e25ab/src/config/editorconfig/editorconfig-to-prettier.js#L47
if (editorconf.maxLineLength) {
options.printWidth = is.number(editorconf.maxLineLength)
? editorconf.maxLineLength
: Number.POSITIVE_INFINITY;
}

// TODO: support editor config `indent_style` and `indent_size`
}

return prettier().format(content, options);
} finally {
logger.trace('applyPrettierFormatting - END');
Expand Down Expand Up @@ -103,7 +124,7 @@ export class MigratedDataFactory {
indent,
}: MigratedData): Promise<string> {
const parser = upath.extname(filename).replace('.', '') as PrettierParser;
return applyPrettierFormatting(content, parser, indent);
return applyPrettierFormatting(filename, content, parser, indent);
}

private static async build(): Promise<MigratedData | null> {
Expand Down