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

refactor: move manifest diagnostics to dedicated provider #145

Merged
merged 6 commits into from
Oct 29, 2022
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
104 changes: 104 additions & 0 deletions src/__tests__/manifestDiagnostics.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { DiagnosticSeverity, languages, TextEditor, window } from 'vscode';

import { ManifestDiagnosticsProvider } from '../manifestDiagnostics';
import { findContentRange, getWorkspaceUri, storeOriginalContent } from './utils/vscode';
import { waitFor } from './utils/wait';

describe(ManifestDiagnosticsProvider, () => {
// Based on: https://github.com/microsoft/vscode-extension-samples/blob/fdd3bb95ce8e38ffe58fc9158797239fdf5017f1/lsp-sample/client/src/test/diagnostics.test.ts#L31

let app: TextEditor;
let restoreContent: ReturnType<typeof storeOriginalContent>;

beforeAll(async () => {
app = await window.showTextDocument(getWorkspaceUri('manifest-diagnostics/app.json'));
restoreContent = storeOriginalContent(app);
});

afterEach(async () => {
await restoreContent();
});

it('diagnoses non-existing asset file reference', async () => {
const range = findContentRange(app, './assets/splash.png');
await app.edit((builder) => builder.replace(range, './assets/doesnt-exist.png'));
await app.document.save();

await waitFor();
const diagnostics = await languages.getDiagnostics(app.document.uri);

expect(diagnostics).toHaveLength(1);
expect(diagnostics[0]).toMatchObject({
code: 'FILE_NOT_FOUND',
message: 'File not found: ./assets/doesnt-exist.png',
severity: DiagnosticSeverity.Warning,
});
});

it('diagnoses asset directory reference', async () => {
const range = findContentRange(app, './assets/adaptive-icon.png');
await app.edit((builder) => builder.replace(range, './assets'));
await app.document.save();

await waitFor();
const diagnostics = await languages.getDiagnostics(app.document.uri);

expect(diagnostics).toHaveLength(1);
expect(diagnostics[0]).toMatchObject({
code: 'FILE_IS_DIRECTORY',
message: 'File is a directory: ./assets',
severity: DiagnosticSeverity.Warning,
});
});

it('diagnoses non-existing plugin definition', async () => {
const range = findContentRange(app, '"plugins": ["expo-system-ui"]');
await app.edit((builder) => builder.replace(range, '"plugins": ["doesnt-exists"]'));
await app.document.save();

await waitFor();
const diagnostics = await languages.getDiagnostics(app.document.uri);

expect(diagnostics).toHaveLength(1);
expect(diagnostics[0]).toMatchObject({
code: 'PLUGIN_NOT_FOUND',
message: 'Plugin not found: doesnt-exists',
severity: DiagnosticSeverity.Warning,
});
});

it('diagnoses empty string plugin definition', async () => {
const range = findContentRange(app, '"plugins": ["expo-system-ui"]');
await app.edit((builder) => builder.replace(range, `"plugins": ["expo-system-ui", ""]`));
await app.document.save();

await waitFor();
const diagnostics = await languages.getDiagnostics(app.document.uri);

expect(diagnostics).toHaveLength(1);
expect(diagnostics[0]).toMatchObject({
code: `PLUGIN_INVALID`,
message: 'Plugin definition is empty, expected a file or dependency name',
severity: DiagnosticSeverity.Warning,
});
});

it('diagnoses empty array plugin definition', async () => {
const range = findContentRange(app, '"plugins": ["expo-system-ui"]');
await app.edit((builder) => builder.replace(range, `"plugins": ["expo-system-ui", []]`));
await app.document.save();

await waitFor();
const diagnostics = await languages.getDiagnostics(app.document.uri);

expect(diagnostics).toHaveLength(1);
expect(diagnostics[0]).toMatchObject({
code: `PLUGIN_INVALID`,
message: 'Plugin definition is empty, expected a file or dependency name',
severity: DiagnosticSeverity.Warning,
});
});

// Note, we don't test for plugin definitions with more than 2 array items.
// That's handled by JSON Schema and out of scope for this test.
});
22 changes: 19 additions & 3 deletions src/expo/manifest.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { resolveConfigPluginFunctionWithInfo } from '@expo/config-plugins/build/utils/plugin-resolver';
import {
resolveConfigPluginFunction,
resolveConfigPluginFunctionWithInfo,
} from '@expo/config-plugins/build/utils/plugin-resolver';
import { Node, Range } from 'jsonc-parser';
import { DocumentFilter } from 'vscode';

import { resetModuleFrom } from '../utils/module';

type FileReference = {
export type FileReference = {
filePath: string;
fileRange: Range;
};
Expand Down Expand Up @@ -70,7 +73,12 @@ export function getPluginDefinition(plugin: Node): PluginDefiniton {
};
}

export function resolvePlugin(dir: string, name: string) {
/**
* Try to resolve the config plugin information.
* This resets previously imported modules to reload this information.
* When it fails to resolve the config plugin, undefined is returned.
*/
export function resolvePluginInfo(dir: string, name: string) {
resetModuleFrom(dir, name);

try {
Expand All @@ -79,3 +87,11 @@ export function resolvePlugin(dir: string, name: string) {
return undefined;
}
}

/**
* Try to resolve the actual config plugin function.
* When it fails to resolve the config plugin, an error is thrown.
*/
export function resolvePluginFunctionUnsafe(dir: string, name: string) {
return resolveConfigPluginFunction(dir, name);
}
9 changes: 3 additions & 6 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as vscode from 'vscode';

import { setupCompletionItemProvider } from './completion/setupCompletionItemProvider';
import { ExpoProjectCache } from './expo/project';
import { setupXdlManifest } from './manifest';
import { ManifestDiagnosticsProvider } from './manifestDiagnostics';
import { ManifestLinksProvider } from './manifestLinks';
import { setupPreview } from './preview/setupPreview';
import { reporter, setupTelemetry, TelemetryEvent } from './utils/telemetry';
Expand All @@ -17,13 +17,10 @@ export async function activate(context: vscode.ExtensionContext) {
const projects = new ExpoProjectCache(context);

await setupTelemetry(context);
await Promise.all([
setupXdlManifest(context),
setupCompletionItemProvider(context),
setupPreview(context),
]);
await Promise.all([setupCompletionItemProvider(context), setupPreview(context)]);

new ManifestLinksProvider(context, projects);
new ManifestDiagnosticsProvider(context, projects);

reporter?.sendTelemetryEvent(TelemetryEvent.ACTIVATED, undefined, {
duration: Date.now() - start,
Expand Down
139 changes: 139 additions & 0 deletions src/manifestDiagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { findNodeAtLocation, Node } from 'jsonc-parser';
import path from 'path';
import vscode from 'vscode';

import {
FileReference,
getFileReferences,
getPluginDefinition,
manifestPattern,
resolvePluginFunctionUnsafe,
} from './expo/manifest';
import { ExpoProject, ExpoProjectCache } from './expo/project';
import { isManifestPluginValidationEnabled } from './settings';
import { debug } from './utils/debug';
import { getDocumentRange } from './utils/json';
import { ExpoDiagnosticsProvider } from './utils/vscode';

const log = debug.extend('manifest-diagnostics');

enum AssetIssueCode {
notFound = 'FILE_NOT_FOUND',
isDirectory = 'FILE_IS_DIRECTORY',
}

enum PluginIssueCode {
invalid = 'PLUGIN_INVALID',
}

export class ManifestDiagnosticsProvider extends ExpoDiagnosticsProvider {
private isEnabled = true;

constructor(extension: vscode.ExtensionContext, projects: ExpoProjectCache) {
super(extension, projects, manifestPattern, 'expo-manifest');
this.isEnabled = isManifestPluginValidationEnabled();

extension.subscriptions.push(
vscode.workspace.onDidChangeConfiguration(() => {
this.isEnabled = isManifestPluginValidationEnabled();
})
);
}

public async provideDiagnostics(document: vscode.TextDocument): Promise<vscode.Diagnostic[]> {
const issues: vscode.Diagnostic[] = [];

if (!this.isEnabled) return issues;

const project = this.projects.fromManifest(document);
if (!project?.manifest) {
log('Could not resolve project from manifest "%s"', document.fileName);
return issues;
}

const plugins = findNodeAtLocation(project.manifest.tree, ['plugins']);
const pluginsRange = plugins && getDocumentRange(document, plugins);

for (const pluginNode of plugins?.children ?? []) {
const issue = diagnosePlugin(document, project, pluginNode);
if (issue) issues.push(issue);
}

for (const reference of getFileReferences(project.manifest.content)) {
const range = getDocumentRange(document, reference.fileRange);

if (!pluginsRange?.contains(range)) {
const issue = await diagnoseAsset(document, project, reference);
if (issue) issues.push(issue);
}
}

return issues;
}
}

function diagnosePlugin(document: vscode.TextDocument, project: ExpoProject, plugin: Node) {
const { nameValue, nameRange } = getPluginDefinition(plugin);

if ((plugin.children && plugin.children.length === 0) || !nameValue) {
const issue = new vscode.Diagnostic(
getDocumentRange(document, nameRange ?? plugin),
`Plugin definition is empty, expected a file or dependency name`,
vscode.DiagnosticSeverity.Warning
);
issue.code = PluginIssueCode.invalid;
return issue;
}

try {
resolvePluginFunctionUnsafe(project.root, nameValue);
} catch (error) {
const issue = new vscode.Diagnostic(
getDocumentRange(document, nameRange),
error.message,
vscode.DiagnosticSeverity.Warning
);

if (error.code === 'PLUGIN_NOT_FOUND') {
issue.message = `Plugin not found: ${nameValue}`;
}

issue.code = error.code;
return issue;
}
}

async function diagnoseAsset(
document: vscode.TextDocument,
project: ExpoProject,
reference: FileReference
) {
try {
const uri = vscode.Uri.file(path.join(project.root, reference.filePath));
const asset = await vscode.workspace.fs.stat(uri);

if (asset.type === vscode.FileType.Directory) {
const issue = new vscode.Diagnostic(
getDocumentRange(document, reference.fileRange),
`File is a directory: ${reference.filePath}`,
vscode.DiagnosticSeverity.Warning
);

issue.code = AssetIssueCode.isDirectory;
return issue;
}
} catch (error) {
const issue = new vscode.Diagnostic(
getDocumentRange(document, reference.fileRange),
error.message,
vscode.DiagnosticSeverity.Warning
);

if (error.code === 'FileNotFound') {
issue.message = `File not found: ${reference.filePath}`;
issue.code = AssetIssueCode.notFound;
}

return issue;
}
}
4 changes: 2 additions & 2 deletions src/manifestLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
getFileReferences,
getPluginDefinition,
manifestPattern,
resolvePlugin,
resolvePluginInfo,
} from './expo/manifest';
import { ExpoProjectCache } from './expo/project';
import { isManifestFileReferencesEnabled } from './settings';
Expand Down Expand Up @@ -48,7 +48,7 @@ export class ManifestLinksProvider extends ExpoLinkProvider {
if (token.isCancellationRequested) return links;

const { nameValue, nameRange } = getPluginDefinition(pluginNode);
const plugin = resolvePlugin(project.root, nameValue);
const plugin = resolvePluginInfo(project.root, nameValue);

if (plugin) {
const link = new vscode.DocumentLink(
Expand Down
41 changes: 37 additions & 4 deletions src/utils/vscode.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,51 @@
import vscode, { DocumentSelector, ExtensionContext, languages } from 'vscode';
import vscode from 'vscode';

import { ExpoProjectCache } from '../expo/project';

export abstract class ExpoLinkProvider implements vscode.DocumentLinkProvider {
constructor(
{ subscriptions }: ExtensionContext,
{ subscriptions }: vscode.ExtensionContext,
protected projects: ExpoProjectCache,
selector: DocumentSelector
selector: vscode.DocumentSelector
) {
subscriptions.push(languages.registerDocumentLinkProvider(selector, this));
subscriptions.push(vscode.languages.registerDocumentLinkProvider(selector, this));
}

abstract provideDocumentLinks(
document: vscode.TextDocument,
token: vscode.CancellationToken
): vscode.ProviderResult<vscode.DocumentLink[]>;
}

export abstract class ExpoDiagnosticsProvider {
protected diagnostics: vscode.DiagnosticCollection;

constructor(
{ subscriptions }: vscode.ExtensionContext,
protected projects: ExpoProjectCache,
private selector: vscode.DocumentSelector,
diagnosticsName?: string
) {
this.diagnostics = vscode.languages.createDiagnosticCollection(diagnosticsName);

subscriptions.push(this.diagnostics);
subscriptions.push(
vscode.workspace.onDidSaveTextDocument((document) => this.diagnose(document))
);
subscriptions.push(
vscode.window.onDidChangeActiveTextEditor((editor) => this.diagnose(editor?.document))
);
}

public async diagnose(document?: vscode.TextDocument) {
if (document && vscode.languages.match(this.selector, document)) {
this.diagnostics.set(document.uri, await this.provideDiagnostics(document));
} else if (document) {
this.diagnostics.delete(document.uri);
}
}

public abstract provideDiagnostics(
document: vscode.TextDocument
): vscode.Diagnostic[] | Promise<vscode.Diagnostic[]>;
}
4 changes: 4 additions & 0 deletions test/fixture/manifest-diagnostics/.expo-shared/assets.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true,
"40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true
}
Loading