Skip to content

Commit

Permalink
refactor(using): use using keyword for Explicit Resource Management (
Browse files Browse the repository at this point in the history
…#4143)

* refactor(using): add using keyword for Explicit Resource Management

* refactor(using): fix fmt

* refactor(using): add more fixes

* refactor(using): fix fmt

* refactor: add more `using` cases

---------

Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
  • Loading branch information
muddlebee and iuioiua authored Jan 14, 2024
1 parent aa3f026 commit 3fcb0a8
Showing 17 changed files with 46 additions and 108 deletions.
6 changes: 2 additions & 4 deletions archive/tar_test.ts
Original file line number Diff line number Diff line change
@@ -110,17 +110,15 @@ Deno.test("Tar() checks directory entry type", async function () {
});

const outputFile = resolve(testdataDir, "directory_type_test.tar");
const file = await Deno.open(outputFile, { create: true, write: true });
using file = await Deno.open(outputFile, { create: true, write: true });
await copy(tar.getReader(), file);
file.close();

const reader = await Deno.open(outputFile, { read: true });
using reader = await Deno.open(outputFile, { read: true });
const untar = new Untar(reader);
await Array.fromAsync(
untar,
(entry) => assertEquals(entry.type, "directory"),
);

reader.close();
await Deno.remove(outputFile);
});
5 changes: 2 additions & 3 deletions archive/untar.ts
Original file line number Diff line number Diff line change
@@ -187,7 +187,7 @@ export class TarEntry implements Reader {
* import { ensureDir } from "https://deno.land/std@$STD_VERSION/fs/ensure_dir.ts";
* import { copy } from "https://deno.land/std@$STD_VERSION/streams/copy.ts";
*
* const reader = await Deno.open("./out.tar", { read: true });
* using reader = await Deno.open("./out.tar", { read: true });
* const untar = new Untar(reader);
*
* for await (const entry of untar) {
@@ -199,11 +199,10 @@ export class TarEntry implements Reader {
* }
*
* await ensureFile(entry.fileName);
* const file = await Deno.open(entry.fileName, { write: true });
* using file = await Deno.open(entry.fileName, { write: true });
* // <entry> is a reader.
* await copy(entry, file);
* }
* reader.close();
* ```
*/
export class Untar {
20 changes: 6 additions & 14 deletions archive/untar_test.ts
Original file line number Diff line number Diff line change
@@ -120,11 +120,10 @@ Deno.test(
const outputFile = resolve(testdataDir, "test.tar");

const tar = await createTar(entries);
const file = await Deno.open(outputFile, { create: true, write: true });
using file = await Deno.open(outputFile, { create: true, write: true });
await copy(tar.getReader(), file);
file.close();

const reader = await Deno.open(outputFile, { read: true });
using reader = await Deno.open(outputFile, { read: true });
// read data from a tar archive
const untar = new Untar(reader);

@@ -134,7 +133,6 @@ Deno.test(
assertEquals(expected.name, entry.fileName);
}

reader.close();
await Deno.remove(outputFile);
assertEquals(entries.length, 0);
},
@@ -155,11 +153,10 @@ Deno.test("Untar() reads from FileReader", async () => {
const outputFile = resolve(testdataDir, "test.tar");

const tar = await createTar(entries);
const file = await Deno.open(outputFile, { create: true, write: true });
using file = await Deno.open(outputFile, { create: true, write: true });
await copy(tar.getReader(), file);
file.close();

const reader = await Deno.open(outputFile, { read: true });
using reader = await Deno.open(outputFile, { read: true });
// read data from a tar archive
const untar = new Untar(reader);

@@ -176,7 +173,6 @@ Deno.test("Untar() reads from FileReader", async () => {
assertEquals(expected.name, entry.fileName);
}

reader.close();
await Deno.remove(outputFile);
assertEquals(entries.length, 0);
});
@@ -229,7 +225,7 @@ Deno.test(

Deno.test("Untar() works with Linux generated tar", async () => {
const filePath = resolve(testdataDir, "deno.tar");
const file = await Deno.open(filePath, { read: true });
using file = await Deno.open(filePath, { read: true });

type ExpectedEntry = TarMeta & { content?: Uint8Array };

@@ -319,8 +315,6 @@ Deno.test("Untar() works with Linux generated tar", async () => {
assertEquals(content, await readAll(entry));
}
}

file.close();
});

Deno.test({
@@ -369,7 +363,7 @@ Deno.test({

Deno.test("Untar() handles archive with link", async function () {
const filePath = resolve(testdataDir, "with_link.tar");
const file = await Deno.open(filePath, { read: true });
using file = await Deno.open(filePath, { read: true });

type ExpectedEntry = TarMetaWithLinkName & { content?: Uint8Array };

@@ -414,6 +408,4 @@ Deno.test("Untar() handles archive with link", async function () {
assertEquals(content, await readAll(entry));
}
}

file.close();
});
12 changes: 4 additions & 8 deletions fs/exists_test.ts
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@ Deno.test("existsSync() returns false for a non-existent path", function () {
Deno.test("exists() returns true for an existing file", async function () {
const tempDirPath = await Deno.makeTempDir();
const tempFilePath = path.join(tempDirPath, "0.ts");
const tempFile = await Deno.create(tempFilePath);
using _tempFile = await Deno.create(tempFilePath);
try {
assertEquals(await exists(tempFilePath), true);
assertEquals(await exists(tempFilePath, {}), true);
@@ -54,7 +54,6 @@ Deno.test("exists() returns true for an existing file", async function () {
if (Deno.build.os !== "windows") {
await Deno.chmod(tempFilePath, 0o644);
}
tempFile.close();
await Deno.remove(tempDirPath, { recursive: true });
}
});
@@ -63,7 +62,7 @@ Deno.test("exists() returns true for an existing file symlink", async function (
const tempDirPath = await Deno.makeTempDir();
const tempFilePath = path.join(tempDirPath, "0.ts");
const tempLinkFilePath = path.join(tempDirPath, "0-link.ts");
const tempFile = await Deno.create(tempFilePath);
using _tempFile = await Deno.create(tempFilePath);
try {
await Deno.symlink(tempFilePath, tempLinkFilePath);
assertEquals(await exists(tempLinkFilePath), true);
@@ -95,15 +94,14 @@ Deno.test("exists() returns true for an existing file symlink", async function (
if (Deno.build.os !== "windows") {
await Deno.chmod(tempFilePath, 0o644);
}
tempFile.close();
await Deno.remove(tempDirPath, { recursive: true });
}
});

Deno.test("existsSync() returns true for an existing file", function () {
const tempDirPath = Deno.makeTempDirSync();
const tempFilePath = path.join(tempDirPath, "0.ts");
const tempFile = Deno.createSync(tempFilePath);
using _tempFile = Deno.createSync(tempFilePath);
try {
assertEquals(existsSync(tempFilePath), true);
assertEquals(existsSync(tempFilePath, {}), true);
@@ -133,7 +131,6 @@ Deno.test("existsSync() returns true for an existing file", function () {
if (Deno.build.os !== "windows") {
Deno.chmodSync(tempFilePath, 0o644);
}
tempFile.close();
Deno.removeSync(tempDirPath, { recursive: true });
}
});
@@ -142,7 +139,7 @@ Deno.test("existsSync() returns true for an existing file symlink", function ()
const tempDirPath = Deno.makeTempDirSync();
const tempFilePath = path.join(tempDirPath, "0.ts");
const tempLinkFilePath = path.join(tempDirPath, "0-link.ts");
const tempFile = Deno.createSync(tempFilePath);
using _tempFile = Deno.createSync(tempFilePath);
try {
Deno.symlinkSync(tempFilePath, tempLinkFilePath);
assertEquals(existsSync(tempLinkFilePath), true);
@@ -174,7 +171,6 @@ Deno.test("existsSync() returns true for an existing file symlink", function ()
if (Deno.build.os !== "windows") {
Deno.chmodSync(tempFilePath, 0o644);
}
tempFile.close();
Deno.removeSync(tempDirPath, { recursive: true });
}
});
6 changes: 2 additions & 4 deletions fs/walk_test.ts
Original file line number Diff line number Diff line change
@@ -169,11 +169,10 @@ Deno.test({
async fn() {
const path = resolve(testdataDir, "socket", "a.sock");
try {
const listener = Deno.listen({ path, transport: "unix" });
using _listener = Deno.listen({ path, transport: "unix" });
await assertWalkPaths("socket", [".", "a.sock", ".gitignore"], {
followSymlinks: true,
});
listener.close();
} finally {
await Deno.remove(path);
}
@@ -187,11 +186,10 @@ Deno.test({
async fn() {
const path = resolve(testdataDir, "socket", "a.sock");
try {
const listener = Deno.listen({ path, transport: "unix" });
using _listener = Deno.listen({ path, transport: "unix" });
assertWalkSyncPaths("socket", [".", "a.sock", ".gitignore"], {
followSymlinks: true,
});
listener.close();
} finally {
await Deno.remove(path);
}
3 changes: 1 addition & 2 deletions http/file_server_test.ts
Original file line number Diff line number Diff line change
@@ -299,8 +299,7 @@ Deno.test("serveDir() traverses encoded URI path", async () => {

Deno.test("serveDir() serves unusual filename", async () => {
const filePath = join(testdataDir, "%");
const file = await Deno.create(filePath);
file.close();
using _file = await Deno.create(filePath);

const req1 = new Request("http://localhost/%25");
const res1 = await serveDir(req1, serveDirOptions);
47 changes: 11 additions & 36 deletions http/server_test.ts
Original file line number Diff line number Diff line change
@@ -218,21 +218,13 @@ Deno.test(
hostname: "localhost",
port: getPort(),
};
const listener = Deno.listen(listenOptions);
using listener = Deno.listen(listenOptions);

await assertRejects(
() => server.serve(listener),
Deno.errors.Http,
"Server closed",
);

try {
listener.close();
} catch (error) {
if (!(error instanceof Deno.errors.BadResource)) {
throw error;
}
}
},
);

@@ -548,7 +540,7 @@ Deno.test(`Server.listenAndServeTls should handle requests`, async () => {
try {
// Invalid certificate, connection should throw on first read or write
// but should not crash the server.
const badConn = await Deno.connectTls({
using badConn = await Deno.connectTls({
hostname,
port,
// missing certFile
@@ -561,10 +553,8 @@ Deno.test(`Server.listenAndServeTls should handle requests`, async () => {
"Read with missing certFile didn't throw an InvalidData error when it should have.",
);

badConn.close();

// Valid request after invalid
const conn = await Deno.connectTls({
using conn = await Deno.connectTls({
hostname,
port,
certFile: join(testdataDir, "tls/RootCA.pem"),
@@ -577,8 +567,6 @@ Deno.test(`Server.listenAndServeTls should handle requests`, async () => {

const response = new TextDecoder().decode(await readAll(conn));

conn.close();

assert(response.includes(`HTTP/1.0 ${status}`), "Status code not correct");
assert(response.includes(body), "Response body not correct");
} finally {
@@ -612,7 +600,7 @@ Deno.test({
try {
// Invalid certificate, connection should throw on first read or write
// but should not crash the server.
const badConn = await Deno.connectTls({
using badConn = await Deno.connectTls({
hostname,
port,
// missing certFile
@@ -625,10 +613,8 @@ Deno.test({
"Read with missing certFile didn't throw an InvalidData error when it should have.",
);

badConn.close();

// Valid request after invalid
const conn = await Deno.connectTls({
using conn = await Deno.connectTls({
hostname,
port,
certFile: join(testdataDir, "tls/RootCA.pem"),
@@ -641,8 +627,6 @@ Deno.test({

const response = new TextDecoder().decode(await readAll(conn));

conn.close();

assert(
response.includes(`HTTP/1.0 ${status}`),
"Status code not correct",
@@ -797,7 +781,7 @@ Deno.test(`Server.listenAndServeTls should handle requests`, async () => {
try {
// Invalid certificate, connection should throw on first read or write
// but should not crash the server.
const badConn = await Deno.connectTls({
using badConn = await Deno.connectTls({
hostname,
port,
// missing certFile
@@ -810,10 +794,8 @@ Deno.test(`Server.listenAndServeTls should handle requests`, async () => {
"Read with missing certFile didn't throw an InvalidData error when it should have.",
);

badConn.close();

// Valid request after invalid
const conn = await Deno.connectTls({
using conn = await Deno.connectTls({
hostname,
port,
certFile: join(testdataDir, "tls/RootCA.pem"),
@@ -826,8 +808,6 @@ Deno.test(`Server.listenAndServeTls should handle requests`, async () => {

const response = new TextDecoder().decode(await readAll(conn));

conn.close();

assert(response.includes(`HTTP/1.0 ${status}`), "Status code not correct");
assert(response.includes(body), "Response body not correct");
} finally {
@@ -839,10 +819,9 @@ Deno.test(`Server.listenAndServeTls should handle requests`, async () => {
Deno.test(
"Server should not reject when the listener is closed (though the server will continually try and fail to accept connections on the listener until it is closed)",
async () => {
const listener = Deno.listen({ port: getPort() });
using listener = Deno.listen({ port: getPort() });
const handler = () => new Response();
const server = new Server({ handler });
listener.close();

let servePromise;

@@ -1099,12 +1078,11 @@ Deno.test(
const server = new Server({ handler });
const servePromise = server.serve(listener);

const conn = await Deno.connect(listenOptions);
using conn = await Deno.connect(listenOptions);

await writeAll(conn, new TextEncoder().encode(`GET / HTTP/1.0\r\n\r\n`));

await onRequest.promise;
conn.close();

await postRespondWith.promise;
server.close();
@@ -1133,12 +1111,11 @@ Deno.test("Server should not reject when the handler throws", async () => {
const server = new Server({ handler });
const servePromise = server.serve(listener);

const conn = await Deno.connect(listenOptions);
using conn = await Deno.connect(listenOptions);

await writeAll(conn, new TextEncoder().encode(`GET / HTTP/1.0\r\n\r\n`));

await postRespondWith.promise;
conn.close();
server.close();
await servePromise;
});
@@ -1476,7 +1453,7 @@ Deno.test("Server.listenAndServeTls should support custom onError", async () =>
});

try {
const conn = await Deno.connectTls({
using conn = await Deno.connectTls({
hostname,
port,
certFile: join(testdataDir, "tls/RootCA.pem"),
@@ -1491,8 +1468,6 @@ Deno.test("Server.listenAndServeTls should support custom onError", async () =>

const response = new TextDecoder().decode(await readAll(conn));

conn.close();

assert(
response.includes(`HTTP/1.0 ${status}`),
"Status code not correct",
Loading

0 comments on commit 3fcb0a8

Please sign in to comment.