Skip to content

Commit a9d851b

Browse files
committed
feat(eslint): add unicorn plugin
1 parent db67e7f commit a9d851b

File tree

16 files changed

+631
-135
lines changed

16 files changed

+631
-135
lines changed

package-lock.json

Lines changed: 504 additions & 33 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

workspaces/adapter/src/log.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ function pad(status: string) {
1818
}
1919

2020
// Borrowed from https://github.com/mikeal/logref/blob/master/main.js#L6-15
21-
function formatter(message: string, ctx: Record<string, string | number>) {
21+
function formatter(message: string, context: Record<string, string | number>) {
2222
while (message.includes('%')) {
2323
const start = message.indexOf('%');
2424
let end = message.indexOf(' ', start);
@@ -27,7 +27,7 @@ function formatter(message: string, ctx: Record<string, string | number>) {
2727
end = message.length;
2828
}
2929

30-
message = `${message.slice(0, start)}${ctx[message.slice(start + 1, end)]}${message.slice(end)}`;
30+
message = `${message.slice(0, start)}${context[message.slice(start + 1, end)]}${message.slice(end)}`;
3131
}
3232

3333
return message;
@@ -91,11 +91,11 @@ export function createLogger<Loggers = any, LoggerCategories extends string | nu
9191
// @param {Object} params.colors status mappings
9292
//
9393
// Returns the logger
94-
function log(message: string, ctx?: Record<string, string | number>) {
94+
function log(message: string, context?: Record<string, string | number>) {
9595
message ??= '';
9696

97-
if (typeof ctx === 'object' && !Array.isArray(ctx)) {
98-
customConsole.error(formatter(message, ctx));
97+
if (typeof context === 'object' && !Array.isArray(context)) {
98+
customConsole.error(formatter(message, context));
9999
} else {
100100
// eslint-disable-next-line prefer-rest-params
101101
customConsole.error(...arguments);
@@ -110,28 +110,28 @@ export function createLogger<Loggers = any, LoggerCategories extends string | nu
110110
// A simple write method, with formatted message.
111111
//
112112
// Returns the logger
113-
log.write = function (...args: Parameters<typeof util.format>) {
114-
stderr.write(util.format(...args));
113+
log.write = function (...arguments_: Parameters<typeof util.format>) {
114+
stderr.write(util.format(...arguments_));
115115
return this;
116116
};
117117

118118
// Same as `log.write()` but automatically appends a `\n` at the end
119119
// of the message.
120-
log.writeln = function (...args: Parameters<typeof util.format>) {
121-
this.write(...args);
120+
log.writeln = function (...arguments_: Parameters<typeof util.format>) {
121+
this.write(...arguments_);
122122
this.write('\n');
123123
return this;
124124
};
125125

126126
// Convenience helper to write sucess status, this simply prepends the
127127
// message with a gren `✔`.
128-
log.ok = function (...args: Parameters<typeof util.format>) {
129-
this.write(`${logSymbols.success} ${util.format(...args)}\n`);
128+
log.ok = function (...arguments_: Parameters<typeof util.format>) {
129+
this.write(`${logSymbols.success} ${util.format(...arguments_)}\n`);
130130
return this;
131131
};
132132

133-
log.error = function (...args: Parameters<typeof util.format>) {
134-
this.write(`${logSymbols.error} ${util.format(...args)}\n`);
133+
log.error = function (...arguments_: Parameters<typeof util.format>) {
134+
this.write(`${logSymbols.error} ${util.format(...arguments_)}\n`);
135135
return this;
136136
};
137137

@@ -169,9 +169,9 @@ export function createLogger<Loggers = any, LoggerCategories extends string | nu
169169
// Returns the logger
170170
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
171171
// @ts-expect-error
172-
log[status] = function (...args: Parameters<typeof util.format>) {
172+
log[status] = function (...arguments_: Parameters<typeof util.format>) {
173173
this.write(color(pad(status))).write(padding);
174-
this.write(`${util.format(...args)}\n`);
174+
this.write(`${util.format(...arguments_)}\n`);
175175
return this;
176176
};
177177
}

workspaces/adapter/src/queued-adapter.ts

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -53,17 +53,17 @@ export class QueuedAdapter implements QueuedAdapterApi {
5353
this.actualAdapter = adapter ?? new TerminalAdapter(adapterOptions);
5454

5555
// Deffered logger
56-
const defferredLogger = (...args: any[]) => {
56+
const defferredLogger = (...arguments_: any[]) => {
5757
this.queueLog(() => {
58-
this.actualAdapter.log(...args);
58+
this.actualAdapter.log(...arguments_);
5959
});
6060
return defferredLogger;
6161
};
6262

6363
Object.assign(defferredLogger, this.actualAdapter.log);
64-
defferredLogger.write = (...args: any[]) => {
64+
defferredLogger.write = (...arguments_: any[]) => {
6565
this.queueLog(() => {
66-
this.actualAdapter.log.write(...args);
66+
this.actualAdapter.log.write(...arguments_);
6767
}).catch(console.error);
6868
return defferredLogger;
6969
};
@@ -115,17 +115,17 @@ export class QueuedAdapter implements QueuedAdapterApi {
115115
* @param fn
116116
* @returns
117117
*/
118-
async queue<TaskResultType>(fn: Task<TaskResultType>): Promise<TaskResultType | void> {
119-
return this.#queue.add(() => fn(this.actualAdapter), { priority: BLOCKING_PRIORITY + this.delta });
118+
async queue<TaskResultType>(function_: Task<TaskResultType>): Promise<TaskResultType | void> {
119+
return this.#queue.add(() => function_(this.actualAdapter), { priority: BLOCKING_PRIORITY + this.delta });
120120
}
121121

122122
/**
123123
* Log has a highest priority and should be not blocking.
124124
* @param fn
125125
* @returns
126126
*/
127-
async queueLog<TaskResultType>(fn: Task<TaskResultType>): Promise<TaskResultType | void> {
128-
return this.#queue.add(() => fn(this.actualAdapter), { priority: LOG_PRIORITY + this.delta });
127+
async queueLog<TaskResultType>(function_: Task<TaskResultType>): Promise<TaskResultType | void> {
128+
return this.#queue.add(() => function_(this.actualAdapter), { priority: LOG_PRIORITY + this.delta });
129129
}
130130

131131
/**
@@ -134,10 +134,10 @@ export class QueuedAdapter implements QueuedAdapterApi {
134134
* @param options
135135
* @returns
136136
*/
137-
async progress<ReturnType>(fn: ProgressCallback<ReturnType>, options?: ProgressOptions): Promise<void | ReturnType> {
137+
async progress<ReturnType>(function_: ProgressCallback<ReturnType>, options?: ProgressOptions): Promise<void | ReturnType> {
138138
if (this.#queue.size > 0 || this.#queue.pending > 0 || options?.disabled || this.#ora.isSpinning) {
139139
// Don't show progress if queue is not empty or already spinning.
140-
return Promise.resolve(fn({ step() {} })).finally(() => {
140+
return Promise.resolve(function_({ step() {} })).finally(() => {
141141
if (options?.name) {
142142
this.log.ok(options.name);
143143
}
@@ -150,13 +150,13 @@ export class QueuedAdapter implements QueuedAdapterApi {
150150
this.#ora.stop();
151151
}
152152

153-
const step = (prefix: string, message: string, ...args: any[]) => {
153+
const step = (prefix: string, message: string, ...arguments_: any[]) => {
154154
if (this.#ora.isSpinning) {
155-
this.#ora.suffixText = `: ${prefix} ${format(message, ...args)}`;
155+
this.#ora.suffixText = `: ${prefix} ${format(message, ...arguments_)}`;
156156
}
157157
};
158158

159-
return this.queue(() => fn({ step })).finally(() => {
159+
return this.queue(() => function_({ step })).finally(() => {
160160
if (this.#ora.isSpinning) {
161161
this.#ora.suffixText = '';
162162
this.#ora.succeed(options?.name);

workspaces/adapter/src/testing/test-adapter.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -144,16 +144,16 @@ export class TestAdapter<LogType extends Logger = Logger, SpyType = any> impleme
144144
}
145145
}
146146

147-
async queue<TaskResultType>(fn: Task<TaskResultType>): Promise<void | TaskResultType> {
148-
return fn(this);
147+
async queue<TaskResultType>(function_: Task<TaskResultType>): Promise<void | TaskResultType> {
148+
return function_(this);
149149
}
150150

151151
async progress<ReturnType>(
152-
fn: (progress: { step: (prefix: string, message: string, ...args: any[]) => void }) => ReturnType,
152+
function_: (progress: { step: (prefix: string, message: string, ...arguments_: any[]) => void }) => ReturnType,
153153

154154
_options?: { disabled?: boolean | undefined; name?: string | undefined } | undefined,
155155
): Promise<void | ReturnType> {
156-
return fn({ step() {} });
156+
return function_({ step() {} });
157157
}
158158

159159
close(): void {

workspaces/conflicter/src/conflicter.ts

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ export type ConflicterOptions = {
4848

4949
type ConflicterTransformOptions = { yoResolveFileName?: string };
5050

51+
const prepareChange = (changes: string, prefix: string) =>
52+
changes
53+
.split('\n')
54+
.map((line, index, array) => (array.length - 1 === index ? line : `${prefix}${line}`))
55+
.join('\n');
56+
5157
/**
5258
* The Conflicter is a module that can be used to detect conflict between files. Each
5359
* Generator file system helpers pass files through this module to make sure they don't
@@ -110,27 +116,27 @@ export class Conflicter {
110116
* @param {Object} file File object respecting this interface: { path, contents }
111117
*/
112118
private async _printDiff({ file, adapter }: { file: ConflictedFile; adapter?: InputOutputAdapter }) {
113-
const destAdapter = adapter ?? this.adapter;
119+
const destinationAdapter = adapter ?? this.adapter;
114120
if (file.binary === undefined) {
115121
file.binary = isBinary(file.path, file.contents ?? undefined);
116122
}
117123

118124
if (file.binary) {
119-
destAdapter.log.writeln(binaryDiff(file.path, file.contents ?? undefined));
125+
destinationAdapter.log.writeln(binaryDiff(file.path, file.contents ?? undefined));
120126
return;
121127
}
122128

123129
const colorLines = (colored: ColoredMessage): ColoredMessage[] => {
124130
if (colored.color) {
125131
const lines = colored.message.split('\n');
126132
const returnValue: ColoredMessage[] = [];
127-
for (const [idx, message] of lines.entries()) {
133+
for (const [index, message] of lines.entries()) {
128134
// Empty message can be ignored
129135
if (message) {
130136
returnValue.push({ message, color: colored.color });
131137
}
132138

133-
if (idx + 1 < lines.length) {
139+
if (index + 1 < lines.length) {
134140
returnValue.push({ message: '\n' });
135141
}
136142
}
@@ -141,12 +147,6 @@ export class Conflicter {
141147
return [colored];
142148
};
143149

144-
const prepareChange = (changes: string, prefix: string) =>
145-
changes
146-
.split('\n')
147-
.map((line, index, array) => (array.length - 1 === index ? line : `${prefix}${line}`))
148-
.join('\n');
149-
150150
const messages: ColoredMessage[][] = file.conflicterChanges
151151
?.map((change: Change): ColoredMessage => {
152152
if (change.added) {
@@ -162,15 +162,15 @@ export class Conflicter {
162162
.map((colored: ColoredMessage): ColoredMessage[] => colorLines(colored));
163163

164164
if (file.fileModeChanges) {
165-
destAdapter.log.colored([
165+
destinationAdapter.log.colored([
166166
{ message: `\nold mode ${file.fileModeChanges[0]}`, color: 'removed' },
167167
{ message: `\nnew mode ${file.fileModeChanges[1]}`, color: 'added' },
168168
{ message: '\n' },
169169
]);
170170
}
171171

172172
if (messages) {
173-
destAdapter.log.colored([
173+
destinationAdapter.log.colored([
174174
{ message: '\n' },
175175
{ message: 'removed', color: 'removed' },
176176
{ message: '' },
@@ -501,7 +501,7 @@ export class Conflicter {
501501

502502
if (file.path === yoResolveFilePath) {
503503
yoResolveFile = file;
504-
return undefined;
504+
return;
505505
}
506506

507507
return conflicterFile;

workspaces/conflicter/src/yo-resolve.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,5 +86,5 @@ export class YoResolve {
8686
}
8787
}
8888

89-
export const createYoResolveTransform = (...args: ConstructorParameters<typeof YoResolve>): FileTransform<MemFsEditorFile> =>
90-
new YoResolve(...args).createTransform();
89+
export const createYoResolveTransform = (...arguments_: ConstructorParameters<typeof YoResolve>): FileTransform<MemFsEditorFile> =>
90+
new YoResolve(...arguments_).createTransform();

workspaces/eslint/index.js

Lines changed: 37 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,42 @@ import eslint from '@eslint/js';
22
import tseslint from 'typescript-eslint';
33
import prettier from 'eslint-config-prettier';
44
import unusedImports from 'eslint-plugin-unused-imports';
5+
import unicorn from 'eslint-plugin-unicorn';
56
import globals from 'globals';
67

8+
const unusedImportsRule = {
9+
plugins: {
10+
'unused-imports': unusedImports,
11+
},
12+
rules: {
13+
'@typescript-eslint/no-unused-vars': 'off',
14+
'no-unused-vars': 'off',
15+
'unused-imports/no-unused-imports': 'error',
16+
'unused-imports/no-unused-vars': [
17+
'warn',
18+
{
19+
vars: 'all',
20+
varsIgnorePattern: '^_',
21+
args: 'after-used',
22+
argsIgnorePattern: '^_',
23+
},
24+
],
25+
},
26+
};
27+
28+
const unicornRules = [
29+
unicorn.configs['flat/recommended'],
30+
{
31+
rules: {
32+
'unicorn/consistent-function-scoping': 'off',
33+
'unicorn/import-style': 'off',
34+
'unicorn/no-null': 'off',
35+
'unicorn/prefer-regexp-test': 'off',
36+
'unicorn/prefer-string-raw': 'off',
37+
},
38+
},
39+
];
40+
741
/**
842
* @type {import('typescript-eslint').ConfigWithExtends[]}
943
*/
@@ -33,26 +67,9 @@ export default [
3367
},
3468
eslint.configs.recommended,
3569
...tseslint.configs.recommended,
36-
{ ignores: ['**/dist/**', '**/fixtures/**'] },
37-
{
38-
plugins: {
39-
'unused-imports': unusedImports,
40-
},
41-
rules: {
42-
'@typescript-eslint/no-unused-vars': 'off',
43-
'no-unused-vars': 'off',
44-
'unused-imports/no-unused-imports': 'error',
45-
'unused-imports/no-unused-vars': [
46-
'warn',
47-
{
48-
vars: 'all',
49-
varsIgnorePattern: '^_',
50-
args: 'after-used',
51-
argsIgnorePattern: '^_',
52-
},
53-
],
54-
},
55-
},
70+
{ ignores: ['**/dist/**', '**/fixtures/**', '**/coverage/**'] },
71+
...unicornRules,
72+
unusedImportsRule,
5673
{
5774
rules: {
5875
'@typescript-eslint/no-explicit-any': 'off',

workspaces/eslint/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
"eslint": "^9.9.1",
2626
"eslint-config-prettier": "^9.1.0",
2727
"eslint-plugin-unused-imports": "^4.1.3",
28+
"eslint-plugin-unicorn": "^55.0.0",
2829
"globals": "^15.9.0",
2930
"typescript-eslint": "^8.2.0"
3031
},

workspaces/namespace/src/namespace/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// ===================== | == @ ======== scope ======== | ===== unscoped ===== | = : ========== generator ======== | = @ ===== semver ===== @ | = # ========= instanceId ======== | == + ======== method ======= |= flags = |
22

33
const NAMESPACE_REGEX =
4-
/^(?:(@[a-z\d-~][a-z\d-._~]*)\/)?([a-z\d-~][a-z\d-._~]*)(?::((?:[a-z\d-~][a-z\d-._~]*:?)*))?(?:@([a-z\d-.~><+=^* ]*)@?)?(?:#((?:[a-z\d-~][a-z\d-._~]*|\*)))?(?:\+((?:[a-zA-Z\d]\w*\+?)*))?(\?)?$/;
4+
/^(?:(@[a-z\d-~][a-z\d-._~]*)\/)?([a-z\d-~][a-z\d-._~]*)(?::((?:[a-z\d-~][a-z\d-._~]*:?)*))?(?:@([a-z\d-. *+<=>^~]*)@?)?(?:#((?:[a-z\d-~][a-z\d-._~]*|\*)))?(?:\+((?:[\dA-Za-z]\w*\+?)*))?(\?)?$/;
55

66
const groups = {
77
complete: 0,

0 commit comments

Comments
 (0)