From 9fbed6ddd4690b2b74dd8665a1f3f77cde6e72b4 Mon Sep 17 00:00:00 2001 From: masnagam Date: Sun, 16 Apr 2023 22:06:12 +0900 Subject: [PATCH] remove comment-like strings from `content` before `importUrls()` this fixes hayd/deno-udd#86 partially. --- mod.ts | 9 ++++++++- test.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/mod.ts b/mod.ts index 2ad8f48..81d8a84 100644 --- a/mod.ts +++ b/mod.ts @@ -59,7 +59,14 @@ export class Udd { async run(): Promise { const content: string = await this.content(); - const urls: string[] = importUrls(content, this.registries); + // Remove "comment-like" strings from `content`. + // + // This is a naive way and not a proper way to remove comments from + // JavaScript and TypeScript files, but works well for our purpose. + const contentWithoutComments = + content.replace(/\/\*([^*]|\*[^\/])*\*\/|(?<=[^:])\/\/.*|^\/\/.*/gm, ''); + + const urls: string[] = importUrls(contentWithoutComments, this.registries); this.progress.n = urls.length; // from a url we need to extract the current version diff --git a/test.ts b/test.ts index 6daad6f..8f019eb 100644 --- a/test.ts +++ b/test.ts @@ -159,3 +159,35 @@ import "https://raw.githubusercontent.com/foo/bar/main/mod.ts#="; const results = await testUdd(contents, expected); assertEquals(results.length, 0); }); + +Deno.test("uddIgnoreComments", async () => { + { + const contents = `//import "https://fakeregistry.com/foo@0.0.1/mod.ts";`; + const expected = contents; + const results = await testUdd(contents, expected); + assertEquals(results.length, 0); + } + { + const contents = `/*import "https://fakeregistry.com/foo@0.0.1/mod.ts";*/`; + const expected = contents; + const results = await testUdd(contents, expected); + assertEquals(results.length, 0); + } + // limitations + // + // TODO: probably, we should use a js parser and collect and modify import + // declarations in the AST. Then, serialize the modified AST to the source + // text. + { + const contents = ` +//import "https://fakeregistry.com/foo@0.0.1/mod.ts"; +import "https://fakeregistry.com/foo@0.0.1/mod.ts"; +`; + const expected = ` +//import "https://fakeregistry.com/foo@0.0.2/mod.ts"; +import "https://fakeregistry.com/foo@0.0.2/mod.ts"; +`; + const results = await testUdd(contents, expected); + assertEquals(results.length, 1); + } +});