Skip to content

refactor: Update script version for autofixed file only #596

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

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
- [Options](#options)
- [`--details`](#--details)
- [`--format`](#--format)
- [`--fix`](#--fix)
- [`--ignore-pattern`](#--ignore-pattern)
- [`--config`](#--config)
- [`--ui5-config`](#--ui5-config)
Expand Down Expand Up @@ -151,6 +152,15 @@ Choose the output format. Currently, `stylish` (default), `json` and `markdown`
ui5lint --format json
```

#### `--fix`

Automatically fix linter findings

**Example:**
```sh
ui5lint --fix
```

#### `--ignore-pattern`

Pattern/files that will be ignored during linting. Can also be defined in `ui5lint.config.js`.
Expand Down
2 changes: 1 addition & 1 deletion npm-shrinkwrap.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@
"prepare": "node ./.husky/skip.js || husky",
"test": "npm run lint && npm run build-test && npm run coverage && npm run e2e && npm run depcheck && npm run check-licenses",
"unit": "ava",
"e2e": "npm run build && npm run e2e:ui5lint && npm run e2e:test",
"e2e:ui5lint": "TEST_E2E_TMP=$PWD/test/tmp/e2e && npm run clean-test-tmp && mkdir -p $TEST_E2E_TMP && cd test/fixtures/linter/projects/com.ui5.troublesome.app && npm exec ui5lint -- --format=json > $TEST_E2E_TMP/ui5lint-results.json 2> $TEST_E2E_TMP/stderr.log || true",
"e2e": "npm run clean-test-tmp && npm run build && npm run e2e:ui5lint && npm run e2e:ui5lint-fix && npm run e2e:test",
"e2e:ui5lint": "TEST_E2E_TMP=$PWD/test/tmp/e2e && mkdir -p $TEST_E2E_TMP && cd test/fixtures/linter/projects/com.ui5.troublesome.app && npm exec ui5lint -- --format=json > $TEST_E2E_TMP/ui5lint-results.json 2> $TEST_E2E_TMP/stderr.log || true",
"e2e:ui5lint-fix": "TEST_E2E_TMP=$PWD/test/tmp/e2e && mkdir -p $TEST_E2E_TMP && cp -r test/fixtures/linter/projects/com.ui5.troublesome.app $TEST_E2E_TMP && cd $TEST_E2E_TMP/com.ui5.troublesome.app && npm exec ui5lint -- --fix --format=json > $TEST_E2E_TMP/ui5lint-results-fix.json 2> $TEST_E2E_TMP/stderr-fix.log || true",
"e2e:test": "ava --config ava-e2e.config.js",
"e2e:test-update-snapshots": "ava --config ava-e2e.config.js --update-snapshots",
"unit-debug": "ava debug",
Expand Down Expand Up @@ -81,6 +82,7 @@
"globals": "^16.0.0",
"he": "^1.2.0",
"json-source-map": "^0.6.1",
"magic-string": "^0.30.17",
"minimatch": "^10.0.1",
"sax-wasm": "^3.0.5",
"typescript": "^5.8.2",
Expand Down
248 changes: 248 additions & 0 deletions src/autofix/autofix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
import ts from "typescript";
import MagicString from "magic-string";
import LinterContext, {RawLintMessage, ResourcePath} from "../linter/LinterContext.js";
import {MESSAGE} from "../linter/messages.js";
import {ModuleDeclaration} from "../linter/ui5Types/amdTranspiler/parseModuleDeclaration.js";
import generateSolutionNoGlobals from "./solutions/noGlobals.js";
import {getLogger} from "@ui5/logger";
import {addDependencies} from "./solutions/amdImports.js";

const log = getLogger("linter:autofix");

export interface AutofixResource {
content: string;
messages: RawLintMessage[];
}

export interface AutofixOptions {
rootDir: string;
namespace?: string;
resources: Map<ResourcePath, AutofixResource>;
context: LinterContext;
}

export enum ChangeAction {
INSERT = "insert",
REPLACE = "replace",
DELETE = "delete",
}

export type ChangeSet = InsertChange | ReplaceChange | DeleteChange;

interface AbstractChangeSet {
action: ChangeAction;
start: number;
}

interface InsertChange extends AbstractChangeSet {
action: ChangeAction.INSERT;
value: string;
}

interface ReplaceChange extends AbstractChangeSet {
action: ChangeAction.REPLACE;
end: number;
value: string;
}

interface DeleteChange extends AbstractChangeSet {
action: ChangeAction.DELETE;
end: number;
}

export type AutofixResult = Map<ResourcePath, string>;
type SourceFiles = Map<ResourcePath, ts.SourceFile>;

interface Position {
line: number;
column: number;
pos: number;
}
export interface GlobalPropertyAccessNodeInfo {
globalVariableName: string;
namespace: string;
moduleName: string;
exportName?: string;
propertyAccess?: string;
position: Position;
node?: ts.Identifier | ts.PropertyAccessExpression | ts.ElementAccessExpression;
}

export interface DeprecatedApiAccessNode {
apiName: string;
position: Position;
node?: ts.CallExpression | ts.Identifier | ts.PropertyAccessExpression | ts.ElementAccessExpression;
}

export type ImportRequests = Map<string, {
nodeInfos: (DeprecatedApiAccessNode | GlobalPropertyAccessNodeInfo)[];
identifier?: string;
}>;

// type ModuleDeclarationInfo = ExistingModuleDeclarationInfo | NewModuleDeclarationInfo;

export interface ExistingModuleDeclarationInfo {
moduleDeclaration: ModuleDeclaration;
importRequests: ImportRequests;
}

export interface NewModuleDeclarationInfo {
declareCall: ts.CallExpression;
requireCalls: Map<string, ts.CallExpression[]>;
importRequests: ImportRequests;
endPos?: number;
}

function createCompilerHost(sourceFiles: SourceFiles): ts.CompilerHost {
return {
getSourceFile: (fileName) => sourceFiles.get(fileName),
writeFile: () => undefined,
getDefaultLibFileName: () => "lib.d.ts",
useCaseSensitiveFileNames: () => false,
getCanonicalFileName: (fileName) => fileName,
getCurrentDirectory: () => "",
getNewLine: () => "\n",
fileExists: (fileName): boolean => sourceFiles.has(fileName),
readFile: () => "",
directoryExists: () => true,
getDirectories: () => [],
};
}

const compilerOptions: ts.CompilerOptions = {
checkJs: false,
allowJs: true,
skipLibCheck: true,
noCheck: true,
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ES2022,
isolatedModules: true,
sourceMap: true,
suppressOutputPathCheck: true,
noLib: true,
noResolve: true,
allowNonTsExtensions: true,
};

function createProgram(inputFileNames: string[], host: ts.CompilerHost): ts.Program {
return ts.createProgram(inputFileNames, compilerOptions, host);
}

function getJsErrors(code: string, resourcePath: string) {
const sourceFile = ts.createSourceFile(
resourcePath,
code,
ts.ScriptTarget.ES2022,
true,
ts.ScriptKind.JS
);

const host = createCompilerHost(new Map([[resourcePath, sourceFile]]));
const program = createProgram([resourcePath], host);
const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);

return diagnostics.filter(function (d) {
return d.file === sourceFile && d.category === ts.DiagnosticCategory.Error;
});
}

// eslint-disable-next-line @typescript-eslint/require-await
export default async function ({
rootDir: _unused1,
namespace: _unused2,
resources,
context,
}: AutofixOptions): Promise<AutofixResult> {
const sourceFiles: SourceFiles = new Map();
const resourcePaths = [];
for (const [resourcePath, resource] of resources) {
const sourceFile = ts.createSourceFile(
resourcePath,
resource.content,
{
languageVersion: ts.ScriptTarget.ES2022,
jsDocParsingMode: ts.JSDocParsingMode.ParseNone,
}
);
sourceFiles.set(resourcePath, sourceFile);
resourcePaths.push(resourcePath);
}

const compilerHost = createCompilerHost(sourceFiles);
const program = createProgram(resourcePaths, compilerHost);

const checker = program.getTypeChecker();
const res: AutofixResult = new Map();
for (const [resourcePath, sourceFile] of sourceFiles) {
log.verbose(`Applying autofixes to ${resourcePath}`);
const newContent = applyFixes(checker, sourceFile, resourcePath, resources.get(resourcePath)!);
if (newContent) {
const jsErrors = getJsErrors(newContent, resourcePath);
if (jsErrors.length) {
const message = `Syntax error after applying autofix for '${resourcePath}': ` +
jsErrors.map((d) => d.messageText as string).join(", ");
log.verbose(message);
context.addLintingMessage(resourcePath, MESSAGE.PARSING_ERROR, {message});
} else {
res.set(resourcePath, newContent);
}
}
}

return res;
}

function applyFixes(
checker: ts.TypeChecker, sourceFile: ts.SourceFile, resourcePath: ResourcePath,
resource: AutofixResource
): string | undefined {
const {content} = resource;

// Group messages by id
const messagesById = new Map<MESSAGE, RawLintMessage[]>();
for (const msg of resource.messages) {
if (!messagesById.has(msg.id)) {
messagesById.set(msg.id, []);
}
messagesById.get(msg.id)!.push(msg);
}

const changeSet: ChangeSet[] = [];
let existingModuleDeclarations = new Map<ts.CallExpression, ExistingModuleDeclarationInfo>();
if (messagesById.has(MESSAGE.NO_GLOBALS)) {
existingModuleDeclarations = generateSolutionNoGlobals(
checker, sourceFile, content,
messagesById.get(MESSAGE.NO_GLOBALS) as RawLintMessage<MESSAGE.NO_GLOBALS>[],
changeSet, []);
}

for (const [defineCall, moduleDeclarationInfo] of existingModuleDeclarations) {
addDependencies(defineCall, moduleDeclarationInfo, changeSet);
}

if (changeSet.length === 0) {
// No modifications needed
return undefined;
}
return applyChanges(content, changeSet);
}

function applyChanges(content: string, changeSet: ChangeSet[]): string {
changeSet.sort((a, b) => a.start - b.start);
const s = new MagicString(content);

for (const change of changeSet) {
switch (change.action) {
case ChangeAction.INSERT:
s.appendRight(change.start, change.value);
break;
case ChangeAction.REPLACE:
s.update(change.start, change.end, change.value);
break;
case ChangeAction.DELETE:
s.remove(change.start, change.end);
break;
}
}
return s.toString();
}
Loading