diff options
Diffstat (limited to 'std')
39 files changed, 432 insertions, 500 deletions
diff --git a/std/archive/tar.ts b/std/archive/tar.ts index f33ea69a4..8ebfa7fb5 100644 --- a/std/archive/tar.ts +++ b/std/archive/tar.ts @@ -384,28 +384,26 @@ export class Tar { */ getReader(): Deno.Reader { const readers: Deno.Reader[] = []; - this.data.forEach( - (tarData): void => { - let { reader } = tarData; - const { filePath } = tarData; - const headerArr = formatHeader(tarData); - readers.push(new Deno.Buffer(headerArr)); - if (!reader) { - reader = new FileReader(filePath!); - } - readers.push(reader); - - // to the nearest multiple of recordSize - readers.push( - new Deno.Buffer( - clean( - recordSize - - (parseInt(tarData.fileSize!, 8) % recordSize || recordSize) - ) - ) - ); + this.data.forEach((tarData): void => { + let { reader } = tarData; + const { filePath } = tarData; + const headerArr = formatHeader(tarData); + readers.push(new Deno.Buffer(headerArr)); + if (!reader) { + reader = new FileReader(filePath!); } - ); + readers.push(reader); + + // to the nearest multiple of recordSize + readers.push( + new Deno.Buffer( + clean( + recordSize - + (parseInt(tarData.fileSize!, 8) % recordSize || recordSize) + ) + ) + ); + }); // append 2 empty records readers.push(new Deno.Buffer(clean(recordSize * 2))); @@ -462,22 +460,18 @@ export class Untar { "mtime", "uid", "gid" - ]).forEach( - (key): void => { - const arr = trim(header[key]); - if (arr.byteLength > 0) { - meta[key] = parseInt(decoder.decode(arr), 8); - } + ]).forEach((key): void => { + const arr = trim(header[key]); + if (arr.byteLength > 0) { + meta[key] = parseInt(decoder.decode(arr), 8); } - ); - (["owner", "group"] as ["owner", "group"]).forEach( - (key): void => { - const arr = trim(header[key]); - if (arr.byteLength > 0) { - meta[key] = decoder.decode(arr); - } + }); + (["owner", "group"] as ["owner", "group"]).forEach((key): void => { + const arr = trim(header[key]); + if (arr.byteLength > 0) { + meta[key] = decoder.decode(arr); } - ); + }); // read the file content const len = parseInt(decoder.decode(header.fileSize), 8); diff --git a/std/encoding/csv.ts b/std/encoding/csv.ts index ec2609f6c..10d72a8a5 100644 --- a/std/encoding/csv.ts +++ b/std/encoding/csv.ts @@ -84,25 +84,23 @@ async function read( result = line.split(opt.comma!); let quoteError = false; - result = result.map( - (r): string => { - if (opt.trimLeadingSpace) { - r = r.trimLeft(); - } - if (r[0] === '"' && r[r.length - 1] === '"') { - r = r.substring(1, r.length - 1); - } else if (r[0] === '"') { - r = r.substring(1, r.length); - } + result = result.map((r): string => { + if (opt.trimLeadingSpace) { + r = r.trimLeft(); + } + if (r[0] === '"' && r[r.length - 1] === '"') { + r = r.substring(1, r.length - 1); + } else if (r[0] === '"') { + r = r.substring(1, r.length); + } - if (!opt.lazyQuotes) { - if (r[0] !== '"' && r.indexOf('"') !== -1) { - quoteError = true; - } + if (!opt.lazyQuotes) { + if (r[0] !== '"' && r.indexOf('"') !== -1) { + quoteError = true; } - return r; } - ); + return r; + }); if (quoteError) { throw new ParseError(Startline, lineIndex, 'bare " in non-quoted-field'); } @@ -226,27 +224,25 @@ export async function parse( ); i++; } - return r.map( - (e): unknown => { - if (e.length !== headers.length) { - throw `Error number of fields line:${i}`; - } - i++; - const out: Record<string, unknown> = {}; - for (let j = 0; j < e.length; j++) { - const h = headers[j]; - if (h.parse) { - out[h.name] = h.parse(e[j]); - } else { - out[h.name] = e[j]; - } - } - if (opt.parse) { - return opt.parse(out); + return r.map((e): unknown => { + if (e.length !== headers.length) { + throw `Error number of fields line:${i}`; + } + i++; + const out: Record<string, unknown> = {}; + for (let j = 0; j < e.length; j++) { + const h = headers[j]; + if (h.parse) { + out[h.name] = h.parse(e[j]); + } else { + out[h.name] = e[j]; } - return out; } - ); + if (opt.parse) { + return opt.parse(out); + } + return out; + }); } if (opt.parse) { return r.map((e: string[]): unknown => opt.parse!(e)); diff --git a/std/encoding/csv_test.ts b/std/encoding/csv_test.ts index 88a3a24d7..65a86a353 100644 --- a/std/encoding/csv_test.ts +++ b/std/encoding/csv_test.ts @@ -20,7 +20,10 @@ const testCases = [ { Name: "CRLF", Input: "a,b\r\nc,d\r\n", - Output: [["a", "b"], ["c", "d"]] + Output: [ + ["a", "b"], + ["c", "d"] + ] }, { Name: "BareCR", @@ -64,12 +67,18 @@ const testCases = [ { Name: "BlankLine", Input: "a,b,c\n\nd,e,f\n\n", - Output: [["a", "b", "c"], ["d", "e", "f"]] + Output: [ + ["a", "b", "c"], + ["d", "e", "f"] + ] }, { Name: "BlankLineFieldCount", Input: "a,b,c\n\nd,e,f\n\n", - Output: [["a", "b", "c"], ["d", "e", "f"]], + Output: [ + ["a", "b", "c"], + ["d", "e", "f"] + ], UseFieldsPerRecord: true, FieldsPerRecord: 0 }, @@ -93,7 +102,10 @@ const testCases = [ { Name: "NoComment", Input: "#1,2,3\na,b,c", - Output: [["#1", "2", "3"], ["a", "b", "c"]] + Output: [ + ["#1", "2", "3"], + ["a", "b", "c"] + ] }, { Name: "LazyQuotes", @@ -159,7 +171,10 @@ const testCases = [ { Name: "FieldCount", Input: "a,b,c\nd,e", - Output: [["a", "b", "c"], ["d", "e"]] + Output: [ + ["a", "b", "c"], + ["d", "e"] + ] }, { Name: "TrailingCommaEOF", @@ -186,7 +201,11 @@ const testCases = [ { Name: "TrailingCommaLine3", Input: "a,b,c\nd,e,f\ng,hi,", - Output: [["a", "b", "c"], ["d", "e", "f"], ["g", "hi", ""]], + Output: [ + ["a", "b", "c"], + ["d", "e", "f"], + ["g", "hi", ""] + ], TrimLeadingSpace: true }, { @@ -223,13 +242,19 @@ x,,, { Name: "TrailingCommaIneffective1", Input: "a,b,\nc,d,e", - Output: [["a", "b", ""], ["c", "d", "e"]], + Output: [ + ["a", "b", ""], + ["c", "d", "e"] + ], TrimLeadingSpace: true }, { Name: "ReadAllReuseRecord", Input: "a,b\nc,d", - Output: [["a", "b"], ["c", "d"]], + Output: [ + ["a", "b"], + ["c", "d"] + ], ReuseRecord: true }, // { @@ -496,7 +521,10 @@ const parseTestCases = [ name: "multiline", in: "a,b,c\ne,f,g\n", header: false, - result: [["a", "b", "c"], ["e", "f", "g"]] + result: [ + ["a", "b", "c"], + ["e", "f", "g"] + ] }, { name: "header mapping boolean", diff --git a/std/encoding/toml.ts b/std/encoding/toml.ts index 3b4b03d20..0cbd51ba0 100644 --- a/std/encoding/toml.ts +++ b/std/encoding/toml.ts @@ -393,11 +393,9 @@ function joinKeys(keys: string[]): string { // Dotted keys are a sequence of bare or quoted keys joined with a dot. // This allows for grouping similar properties together: return keys - .map( - (str: string): string => { - return str.match(/[^A-Za-z0-9_-]/) ? `"${str}"` : str; - } - ) + .map((str: string): string => { + return str.match(/[^A-Za-z0-9_-]/) ? `"${str}"` : str; + }) .join("."); } @@ -417,24 +415,20 @@ class Dumper { _parse(obj: Record<string, unknown>, keys: string[] = []): string[] { const out = []; const props = Object.keys(obj); - const propObj = props.filter( - (e: string): boolean => { - if (obj[e] instanceof Array) { - const d: unknown[] = obj[e] as unknown[]; - return !this._isSimplySerializable(d[0]); - } - return !this._isSimplySerializable(obj[e]); + const propObj = props.filter((e: string): boolean => { + if (obj[e] instanceof Array) { + const d: unknown[] = obj[e] as unknown[]; + return !this._isSimplySerializable(d[0]); } - ); - const propPrim = props.filter( - (e: string): boolean => { - if (obj[e] instanceof Array) { - const d: unknown[] = obj[e] as unknown[]; - return this._isSimplySerializable(d[0]); - } - return this._isSimplySerializable(obj[e]); + return !this._isSimplySerializable(obj[e]); + }); + const propPrim = props.filter((e: string): boolean => { + if (obj[e] instanceof Array) { + const d: unknown[] = obj[e] as unknown[]; + return this._isSimplySerializable(d[0]); } - ); + return this._isSimplySerializable(obj[e]); + }); const k = propPrim.concat(propObj); for (let i = 0; i < k.length; i++) { const prop = k[i]; diff --git a/std/encoding/toml_test.ts b/std/encoding/toml_test.ts index 633ccd1db..065ab506c 100644 --- a/std/encoding/toml_test.ts +++ b/std/encoding/toml_test.ts @@ -112,7 +112,10 @@ test({ fn(): void { const expected = { arrays: { - data: [["gamma", "delta"], [1, 2]], + data: [ + ["gamma", "delta"], + [1, 2] + ], hosts: ["alpha", "omega"] } }; @@ -344,7 +347,10 @@ test({ sf4: NaN, sf5: NaN, sf6: NaN, - data: [["gamma", "delta"], [1, 2]], + data: [ + ["gamma", "delta"], + [1, 2] + ], hosts: ["alpha", "omega"] }; const expected = `deno = "is" diff --git a/std/flags/mod.ts b/std/flags/mod.ts index 952315319..19defd1ed 100644 --- a/std/flags/mod.ts +++ b/std/flags/mod.ts @@ -79,11 +79,9 @@ export function parse( ? [options.boolean] : options.boolean; - booleanArgs.filter(Boolean).forEach( - (key: string): void => { - flags.bools[key] = true; - } - ); + booleanArgs.filter(Boolean).forEach((key: string): void => { + flags.bools[key] = true; + }); } } @@ -114,11 +112,9 @@ export function parse( flags.strings[key] = true; const alias = get(aliases, key); if (alias) { - alias.forEach( - (alias: string): void => { - flags.strings[alias] = true; - } - ); + alias.forEach((alias: string): void => { + flags.strings[alias] = true; + }); } }); } diff --git a/std/fmt/sprintf_test.ts b/std/fmt/sprintf_test.ts index 4d3a48c68..26757c3cc 100644 --- a/std/fmt/sprintf_test.ts +++ b/std/fmt/sprintf_test.ts @@ -587,18 +587,16 @@ const tests: Array<[string, any, string]> = [ ]; test(function testThorough(): void { - tests.forEach( - (t, i): void => { - // p(t) - const is = S(t[0], t[1]); - const should = t[2]; - assertEquals( - is, - should, - `failed case[${i}] : is >${is}< should >${should}<` - ); - } - ); + tests.forEach((t, i): void => { + // p(t) + const is = S(t[0], t[1]); + const should = t[2]; + assertEquals( + is, + should, + `failed case[${i}] : is >${is}< should >${should}<` + ); + }); }); test(function testWeirdos(): void { diff --git a/std/fs/copy_test.ts b/std/fs/copy_test.ts index 46b3418ac..da84e252c 100644 --- a/std/fs/copy_test.ts +++ b/std/fs/copy_test.ts @@ -317,11 +317,9 @@ testCopySync( (tempDir: string): void => { const srcFile = path.join(testdataDir, "copy_file_not_exists_sync.txt"); const destFile = path.join(tempDir, "copy_file_not_exists_1_sync.txt"); - assertThrows( - (): void => { - copySync(srcFile, destFile); - } - ); + assertThrows((): void => { + copySync(srcFile, destFile); + }); } ); @@ -367,50 +365,47 @@ testCopySync( } ); -testCopySync( - "[fs] copy file synchronously", - (tempDir: string): void => { - const srcFile = path.join(testdataDir, "copy_file.txt"); - const destFile = path.join(tempDir, "copy_file_copy_sync.txt"); +testCopySync("[fs] copy file synchronously", (tempDir: string): void => { + const srcFile = path.join(testdataDir, "copy_file.txt"); + const destFile = path.join(tempDir, "copy_file_copy_sync.txt"); - const srcContent = new TextDecoder().decode(Deno.readFileSync(srcFile)); + const srcContent = new TextDecoder().decode(Deno.readFileSync(srcFile)); - assertEquals(existsSync(srcFile), true); - assertEquals(existsSync(destFile), false); + assertEquals(existsSync(srcFile), true); + assertEquals(existsSync(destFile), false); - copySync(srcFile, destFile); + copySync(srcFile, destFile); - assertEquals(existsSync(srcFile), true); - assertEquals(existsSync(destFile), true); + assertEquals(existsSync(srcFile), true); + assertEquals(existsSync(destFile), true); - const destContent = new TextDecoder().decode(Deno.readFileSync(destFile)); + const destContent = new TextDecoder().decode(Deno.readFileSync(destFile)); - assertEquals(srcContent, destContent); + assertEquals(srcContent, destContent); - // Copy again without overwrite option and it should throw an error. - assertThrows( - (): void => { - copySync(srcFile, destFile); - }, - Error, - `'${destFile}' already exists.` - ); + // Copy again without overwrite option and it should throw an error. + assertThrows( + (): void => { + copySync(srcFile, destFile); + }, + Error, + `'${destFile}' already exists.` + ); - // Modify destination file. - Deno.writeFileSync(destFile, new TextEncoder().encode("txt copy")); + // Modify destination file. + Deno.writeFileSync(destFile, new TextEncoder().encode("txt copy")); - assertEquals( - new TextDecoder().decode(Deno.readFileSync(destFile)), - "txt copy" - ); + assertEquals( + new TextDecoder().decode(Deno.readFileSync(destFile)), + "txt copy" + ); - // Copy again with overwrite option. - copySync(srcFile, destFile, { overwrite: true }); + // Copy again with overwrite option. + copySync(srcFile, destFile, { overwrite: true }); - // Make sure the file has been overwritten. - assertEquals(new TextDecoder().decode(Deno.readFileSync(destFile)), "txt"); - } -); + // Make sure the file has been overwritten. + assertEquals(new TextDecoder().decode(Deno.readFileSync(destFile)), "txt"); +}); testCopySync( "[fs] copy directory synchronously to its subdirectory", @@ -450,57 +445,54 @@ testCopySync( } ); -testCopySync( - "[fs] copy directory synchronously", - (tempDir: string): void => { - const srcDir = path.join(testdataDir, "copy_dir"); - const destDir = path.join(tempDir, "copy_dir_copy_sync"); - const srcFile = path.join(srcDir, "0.txt"); - const destFile = path.join(destDir, "0.txt"); - const srcNestFile = path.join(srcDir, "nest", "0.txt"); - const destNestFile = path.join(destDir, "nest", "0.txt"); - - copySync(srcDir, destDir); - - assertEquals(existsSync(destFile), true); - assertEquals(existsSync(destNestFile), true); - - // After copy. The source and destination should have the same content. - assertEquals( - new TextDecoder().decode(Deno.readFileSync(srcFile)), - new TextDecoder().decode(Deno.readFileSync(destFile)) - ); - assertEquals( - new TextDecoder().decode(Deno.readFileSync(srcNestFile)), - new TextDecoder().decode(Deno.readFileSync(destNestFile)) - ); - - // Copy again without overwrite option and it should throw an error. - assertThrows( - (): void => { - copySync(srcDir, destDir); - }, - Error, - `'${destDir}' already exists.` - ); - - // Modify the file in the destination directory. - Deno.writeFileSync(destNestFile, new TextEncoder().encode("nest copy")); - assertEquals( - new TextDecoder().decode(Deno.readFileSync(destNestFile)), - "nest copy" - ); - - // Copy again with overwrite option. - copySync(srcDir, destDir, { overwrite: true }); - - // Make sure the file has been overwritten. - assertEquals( - new TextDecoder().decode(Deno.readFileSync(destNestFile)), - "nest" - ); - } -); +testCopySync("[fs] copy directory synchronously", (tempDir: string): void => { + const srcDir = path.join(testdataDir, "copy_dir"); + const destDir = path.join(tempDir, "copy_dir_copy_sync"); + const srcFile = path.join(srcDir, "0.txt"); + const destFile = path.join(destDir, "0.txt"); + const srcNestFile = path.join(srcDir, "nest", "0.txt"); + const destNestFile = path.join(destDir, "nest", "0.txt"); + + copySync(srcDir, destDir); + + assertEquals(existsSync(destFile), true); + assertEquals(existsSync(destNestFile), true); + + // After copy. The source and destination should have the same content. + assertEquals( + new TextDecoder().decode(Deno.readFileSync(srcFile)), + new TextDecoder().decode(Deno.readFileSync(destFile)) + ); + assertEquals( + new TextDecoder().decode(Deno.readFileSync(srcNestFile)), + new TextDecoder().decode(Deno.readFileSync(destNestFile)) + ); + + // Copy again without overwrite option and it should throw an error. + assertThrows( + (): void => { + copySync(srcDir, destDir); + }, + Error, + `'${destDir}' already exists.` + ); + + // Modify the file in the destination directory. + Deno.writeFileSync(destNestFile, new TextEncoder().encode("nest copy")); + assertEquals( + new TextDecoder().decode(Deno.readFileSync(destNestFile)), + "nest copy" + ); + + // Copy again with overwrite option. + copySync(srcDir, destDir, { overwrite: true }); + + // Make sure the file has been overwritten. + assertEquals( + new TextDecoder().decode(Deno.readFileSync(destNestFile)), + "nest" + ); +}); testCopySync( "[fs] copy symlink file synchronously", diff --git a/std/fs/empty_dir_test.ts b/std/fs/empty_dir_test.ts index 26e751c74..ac5b13476 100644 --- a/std/fs/empty_dir_test.ts +++ b/std/fs/empty_dir_test.ts @@ -110,18 +110,14 @@ test(function emptyDirSyncIfItExist(): void { assertEquals(stat.isDirectory(), true); // nest directory have been remove - assertThrows( - (): void => { - Deno.statSync(testNestDir); - } - ); + assertThrows((): void => { + Deno.statSync(testNestDir); + }); // test file have been remove - assertThrows( - (): void => { - Deno.statSync(testDirFile); - } - ); + assertThrows((): void => { + Deno.statSync(testDirFile); + }); } finally { // remote test dir Deno.removeSync(testDir, { recursive: true }); diff --git a/std/fs/ensure_dir_test.ts b/std/fs/ensure_dir_test.ts index 068ec8693..c0a06749b 100644 --- a/std/fs/ensure_dir_test.ts +++ b/std/fs/ensure_dir_test.ts @@ -15,11 +15,9 @@ test(async function ensureDirIfItNotExist(): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { - await Deno.stat(testDir).then( - (): void => { - throw new Error("test dir should exists."); - } - ); + await Deno.stat(testDir).then((): void => { + throw new Error("test dir should exists."); + }); } ); @@ -48,11 +46,9 @@ test(async function ensureDirIfItExist(): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { - await Deno.stat(testDir).then( - (): void => { - throw new Error("test dir should still exists."); - } - ); + await Deno.stat(testDir).then((): void => { + throw new Error("test dir should still exists."); + }); } ); @@ -68,12 +64,10 @@ test(function ensureDirSyncIfItExist(): void { ensureDirSync(testDir); - assertThrows( - (): void => { - Deno.statSync(testDir); - throw new Error("test dir should still exists."); - } - ); + assertThrows((): void => { + Deno.statSync(testDir); + throw new Error("test dir should still exists."); + }); Deno.removeSync(baseDir, { recursive: true }); }); diff --git a/std/fs/ensure_file_test.ts b/std/fs/ensure_file_test.ts index bb23084a8..efd88d983 100644 --- a/std/fs/ensure_file_test.ts +++ b/std/fs/ensure_file_test.ts @@ -14,11 +14,9 @@ test(async function ensureFileIfItNotExist(): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { - await Deno.stat(testFile).then( - (): void => { - throw new Error("test file should exists."); - } - ); + await Deno.stat(testFile).then((): void => { + throw new Error("test file should exists."); + }); } ); @@ -31,12 +29,10 @@ test(function ensureFileSyncIfItNotExist(): void { ensureFileSync(testFile); - assertThrows( - (): void => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - } - ); + assertThrows((): void => { + Deno.statSync(testFile); + throw new Error("test file should exists."); + }); Deno.removeSync(testDir, { recursive: true }); }); @@ -52,11 +48,9 @@ test(async function ensureFileIfItExist(): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { - await Deno.stat(testFile).then( - (): void => { - throw new Error("test file should exists."); - } - ); + await Deno.stat(testFile).then((): void => { + throw new Error("test file should exists."); + }); } ); @@ -72,12 +66,10 @@ test(function ensureFileSyncIfItExist(): void { ensureFileSync(testFile); - assertThrows( - (): void => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - } - ); + assertThrows((): void => { + Deno.statSync(testFile); + throw new Error("test file should exists."); + }); Deno.removeSync(testDir, { recursive: true }); }); diff --git a/std/fs/ensure_link_test.ts b/std/fs/ensure_link_test.ts index 044f80f8d..d15e5c1f6 100644 --- a/std/fs/ensure_link_test.ts +++ b/std/fs/ensure_link_test.ts @@ -31,11 +31,9 @@ test(function ensureLinkSyncIfItNotExist(): void { const testFile = path.join(testDir, "test.txt"); const linkFile = path.join(testDir, "link.txt"); - assertThrows( - (): void => { - ensureLinkSync(testFile, linkFile); - } - ); + assertThrows((): void => { + ensureLinkSync(testFile, linkFile); + }); Deno.removeSync(testDir, { recursive: true }); }); diff --git a/std/fs/ensure_symlink_test.ts b/std/fs/ensure_symlink_test.ts index 0c2c53e5d..6c1fe5fb5 100644 --- a/std/fs/ensure_symlink_test.ts +++ b/std/fs/ensure_symlink_test.ts @@ -24,11 +24,9 @@ test(async function ensureSymlinkIfItNotExist(): Promise<void> { assertThrowsAsync( async (): Promise<void> => { - await Deno.stat(testFile).then( - (): void => { - throw new Error("test file should exists."); - } - ); + await Deno.stat(testFile).then((): void => { + throw new Error("test file should exists."); + }); } ); }); @@ -37,18 +35,14 @@ test(function ensureSymlinkSyncIfItNotExist(): void { const testDir = path.join(testdataDir, "link_file_2"); const testFile = path.join(testDir, "test.txt"); - assertThrows( - (): void => { - ensureSymlinkSync(testFile, path.join(testDir, "test1.txt")); - } - ); + assertThrows((): void => { + ensureSymlinkSync(testFile, path.join(testDir, "test1.txt")); + }); - assertThrows( - (): void => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - } - ); + assertThrows((): void => { + Deno.statSync(testFile); + throw new Error("test file should exists."); + }); }); test(async function ensureSymlinkIfItExist(): Promise<void> { diff --git a/std/fs/expand_glob.ts b/std/fs/expand_glob.ts index c43e09d40..8965773a7 100644 --- a/std/fs/expand_glob.ts +++ b/std/fs/expand_glob.ts @@ -136,8 +136,8 @@ export async function* expandGlob( ); } if (hasTrailingSep) { - currentMatches = currentMatches.filter( - ({ info }): boolean => info.isDirectory() + currentMatches = currentMatches.filter(({ info }): boolean => + info.isDirectory() ); } if (!includeDirs) { @@ -238,8 +238,8 @@ export function* expandGlobSync( ); } if (hasTrailingSep) { - currentMatches = currentMatches.filter( - ({ info }): boolean => info.isDirectory() + currentMatches = currentMatches.filter(({ info }): boolean => + info.isDirectory() ); } if (!includeDirs) { diff --git a/std/fs/move_test.ts b/std/fs/move_test.ts index fc0141d8e..d45ae1cf5 100644 --- a/std/fs/move_test.ts +++ b/std/fs/move_test.ts @@ -182,11 +182,9 @@ test(function moveSyncDirectoryIfSrcNotExists(): void { const srcDir = path.join(testdataDir, "move_sync_test_src_1"); const destDir = path.join(testdataDir, "move_sync_test_dest_1"); // if src directory not exist - assertThrows( - (): void => { - moveSync(srcDir, destDir); - } - ); + assertThrows((): void => { + moveSync(srcDir, destDir); + }); }); test(function moveSyncDirectoryIfDestNotExists(): void { @@ -213,11 +211,9 @@ test(function moveSyncFileIfSrcNotExists(): void { const destFile = path.join(testdataDir, "move_sync_test_dest_3", "test.txt"); // if src directory not exist - assertThrows( - (): void => { - moveSync(srcFile, destFile); - } - ); + assertThrows((): void => { + moveSync(srcFile, destFile); + }); }); test(function moveSyncFileIfDestExists(): void { diff --git a/std/fs/read_json_test.ts b/std/fs/read_json_test.ts index a9362b0ac..c4c8d67d8 100644 --- a/std/fs/read_json_test.ts +++ b/std/fs/read_json_test.ts @@ -65,31 +65,25 @@ test(async function readValidObjJsonFileWithRelativePath(): Promise<void> { test(function readJsonFileNotExistsSync(): void { const emptyJsonFile = path.join(testdataDir, "json_not_exists.json"); - assertThrows( - (): void => { - readJsonSync(emptyJsonFile); - } - ); + assertThrows((): void => { + readJsonSync(emptyJsonFile); + }); }); test(function readEmptyJsonFileSync(): void { const emptyJsonFile = path.join(testdataDir, "json_empty.json"); - assertThrows( - (): void => { - readJsonSync(emptyJsonFile); - } - ); + assertThrows((): void => { + readJsonSync(emptyJsonFile); + }); }); test(function readInvalidJsonFile(): void { const invalidJsonFile = path.join(testdataDir, "json_invalid.json"); - assertThrows( - (): void => { - readJsonSync(invalidJsonFile); - } - ); + assertThrows((): void => { + readJsonSync(invalidJsonFile); + }); }); test(function readValidArrayJsonFileSync(): void { diff --git a/std/fs/walk.ts b/std/fs/walk.ts index efc54bc23..60eb9b483 100644 --- a/std/fs/walk.ts +++ b/std/fs/walk.ts @@ -21,13 +21,11 @@ function patternTest(patterns: RegExp[], path: string): boolean { // Forced to reset last index on regex while iterating for have // consistent results. // See: https://stackoverflow.com/a/1520853 - return patterns.some( - (pattern): boolean => { - const r = pattern.test(path); - pattern.lastIndex = 0; - return r; - } - ); + return patterns.some((pattern): boolean => { + const r = pattern.test(path); + pattern.lastIndex = 0; + return r; + }); } function include(filename: string, options: WalkOptions): boolean { diff --git a/std/http/file_server.ts b/std/http/file_server.ts index a2de5eecd..8dc2ee87a 100755 --- a/std/http/file_server.ts +++ b/std/http/file_server.ts @@ -75,11 +75,9 @@ function modeToString(isDir: boolean, maybeMode: number | null): string { .split("") .reverse() .slice(0, 3) - .forEach( - (v): void => { - output = modeMap[+v] + output; - } - ); + .forEach((v): void => { + output = modeMap[+v] + output; + }); output = `(${isDir ? "d" : "-"}${output})`; return output; } @@ -179,9 +177,8 @@ async function serveDir( dirViewerTemplate.replace("<%DIRNAME%>", formattedDirUrl).replace( "<%CONTENTS%>", listEntry - .sort( - (a, b): number => - a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1 + .sort((a, b): number => + a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1 ) .map((v): string => v.template) .join("") diff --git a/std/http/server_test.ts b/std/http/server_test.ts index c8d4080ca..525e40d6f 100644 --- a/std/http/server_test.ts +++ b/std/http/server_test.ts @@ -505,11 +505,9 @@ test({ let serverIsRunning = true; p.status() - .then( - (): void => { - serverIsRunning = false; - } - ) + .then((): void => { + serverIsRunning = false; + }) .catch((_): void => {}); // Ignores the error when closing the process. await delay(100); @@ -551,11 +549,9 @@ test({ let serverIsRunning = true; p.status() - .then( - (): void => { - serverIsRunning = false; - } - ) + .then((): void => { + serverIsRunning = false; + }) .catch((_): void => {}); // Ignores the error when closing the process. // Requests to the server and immediately closes the connection diff --git a/std/io/bufio.ts b/std/io/bufio.ts index b287ef3c1..5f0d53eb8 100644 --- a/std/io/bufio.ts +++ b/std/io/bufio.ts @@ -23,6 +23,7 @@ export class BufferFullError extends Error { export class UnexpectedEOFError extends Error { name = "UnexpectedEOFError"; + partial?: Uint8Array; constructor() { super("Unexpected EOF"); } diff --git a/std/log/handlers.ts b/std/log/handlers.ts index 5dfd0caa4..93bdd3edd 100644 --- a/std/log/handlers.ts +++ b/std/log/handlers.ts @@ -37,19 +37,16 @@ export class BaseHandler { return this.formatter(logRecord); } - return this.formatter.replace( - /{(\S+)}/g, - (match, p1): string => { - const value = logRecord[p1 as keyof LogRecord]; + return this.formatter.replace(/{(\S+)}/g, (match, p1): string => { + const value = logRecord[p1 as keyof LogRecord]; - // do not interpolate missing values - if (!value) { - return match; - } - - return String(value); + // do not interpolate missing values + if (!value) { + return match; } - ); + + return String(value); + }); } log(_msg: string): void {} diff --git a/std/log/logger.ts b/std/log/logger.ts index 7ef96e15a..482743b23 100644 --- a/std/log/logger.ts +++ b/std/log/logger.ts @@ -36,11 +36,9 @@ export class Logger { level: level, levelName: getLevelName(level) }; - this.handlers.forEach( - (handler): void => { - handler.handle(record); - } - ); + this.handlers.forEach((handler): void => { + handler.handle(record); + }); } debug(msg: string, ...args: unknown[]): void { diff --git a/std/log/mod.ts b/std/log/mod.ts index cb166376e..3f34d7f1d 100644 --- a/std/log/mod.ts +++ b/std/log/mod.ts @@ -80,11 +80,9 @@ export async function setup(config: LogConfig): Promise<void> { }; // tear down existing handlers - state.handlers.forEach( - (handler): void => { - handler.destroy(); - } - ); + state.handlers.forEach((handler): void => { + handler.destroy(); + }); state.handlers.clear(); // setup handlers @@ -106,13 +104,11 @@ export async function setup(config: LogConfig): Promise<void> { const handlerNames = loggerConfig.handlers || []; const handlers: BaseHandler[] = []; - handlerNames.forEach( - (handlerName): void => { - if (state.handlers.has(handlerName)) { - handlers.push(state.handlers.get(handlerName)!); - } + handlerNames.forEach((handlerName): void => { + if (state.handlers.has(handlerName)) { + handlers.push(state.handlers.get(handlerName)!); } - ); + }); const levelName = loggerConfig.level || DEFAULT_LEVEL; const logger = new Logger(levelName, handlers); diff --git a/std/mime/multipart.ts b/std/mime/multipart.ts index 8eb27b52a..9fdec99b1 100644 --- a/std/mime/multipart.ts +++ b/std/mime/multipart.ts @@ -188,20 +188,18 @@ class PartReader implements Reader, Closer { comps .slice(1) .map((v: string): string => v.trim()) - .map( - (kv: string): void => { - const [k, v] = kv.split("="); - if (v) { - const s = v.charAt(0); - const e = v.charAt(v.length - 1); - if ((s === e && s === '"') || s === "'") { - params[k] = v.substr(1, v.length - 2); - } else { - params[k] = v; - } + .map((kv: string): void => { + const [k, v] = kv.split("="); + if (v) { + const s = v.charAt(0); + const e = v.charAt(v.length - 1); + if ((s === e && s === '"') || s === "'") { + params[k] = v.substr(1, v.length - 2); + } else { + params[k] = v; } } - ); + }); return (this.contentDispositionParams = params); } diff --git a/std/testing/README.md b/std/testing/README.md index e2bd90b24..8d02f9d79 100644 --- a/std/testing/README.md +++ b/std/testing/README.md @@ -92,11 +92,9 @@ Using `assertThrows()`: ```ts test(function doesThrow(): void { - assertThrows( - (): void => { - throw new TypeError("hello world!"); - } - ); + assertThrows((): void => { + throw new TypeError("hello world!"); + }); assertThrows((): void => { throw new TypeError("hello world!"); }, TypeError); @@ -111,11 +109,9 @@ test(function doesThrow(): void { // This test will not pass test(function fails(): void { - assertThrows( - (): void => { - console.log("Hello world"); - } - ); + assertThrows((): void => { + console.log("Hello world"); + }); }); ``` diff --git a/std/testing/asserts.ts b/std/testing/asserts.ts index ceac52dbd..3ae45454c 100644 --- a/std/testing/asserts.ts +++ b/std/testing/asserts.ts @@ -56,12 +56,10 @@ function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] { ); messages.push(""); messages.push(""); - diffResult.forEach( - (result: DiffResult<string>): void => { - const c = createColor(result.type); - messages.push(c(`${createSign(result.type)}${result.value}`)); - } - ); + diffResult.forEach((result: DiffResult<string>): void => { + const c = createColor(result.type); + messages.push(c(`${createSign(result.type)}${result.value}`)); + }); messages.push(""); return messages; @@ -131,7 +129,7 @@ export function equal(c: unknown, d: unknown): boolean { } /** Make an assertion, if not `true`, then throw. */ -export function assert(expr: boolean, msg = ""): void { +export function assert(expr: unknown, msg = ""): asserts expr { if (!expr) { throw new AssertionError(msg); } diff --git a/std/testing/asserts_test.ts b/std/testing/asserts_test.ts index 956d66e3e..be0502ce6 100644 --- a/std/testing/asserts_test.ts +++ b/std/testing/asserts_test.ts @@ -51,8 +51,14 @@ test(function testingEqual(): void { assert(equal(new Map(), new Map())); assert( equal( - new Map([["foo", "bar"], ["baz", "baz"]]), - new Map([["foo", "bar"], ["baz", "baz"]]) + new Map([ + ["foo", "bar"], + ["baz", "baz"] + ]), + new Map([ + ["foo", "bar"], + ["baz", "baz"] + ]) ) ); assert( @@ -69,14 +75,26 @@ test(function testingEqual(): void { ); assert( equal( - new Map([["foo", "bar"], ["baz", "qux"]]), - new Map([["baz", "qux"], ["foo", "bar"]]) + new Map([ + ["foo", "bar"], + ["baz", "qux"] + ]), + new Map([ + ["baz", "qux"], + ["foo", "bar"] + ]) ) ); assert(equal(new Map([["foo", ["bar"]]]), new Map([["foo", ["bar"]]]))); assert(!equal(new Map([["foo", "bar"]]), new Map([["bar", "baz"]]))); assert( - !equal(new Map([["foo", "bar"]]), new Map([["foo", "bar"], ["bar", "baz"]])) + !equal( + new Map([["foo", "bar"]]), + new Map([ + ["foo", "bar"], + ["bar", "baz"] + ]) + ) ); assert( !equal( diff --git a/std/testing/diff.ts b/std/testing/diff.ts index dd544ac24..38d632e9a 100644 --- a/std/testing/diff.ts +++ b/std/testing/diff.ts @@ -133,7 +133,7 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { k: number, M: number ): FarthestPoint { - if (slide && slide.y === -1 && (down && down.y === -1)) + if (slide && slide.y === -1 && down && down.y === -1) return { y: 0, id: 0 }; if ( (down && down.y === -1) || diff --git a/std/testing/format.ts b/std/testing/format.ts index 28937d567..953347c27 100644 --- a/std/testing/format.ts +++ b/std/testing/format.ts @@ -360,13 +360,11 @@ const getKeysOfEnumerableProperties = (object: {}): Array<string | symbol> => { const keys: Array<string | symbol> = Object.keys(object).sort(); if (Object.getOwnPropertySymbols) { - Object.getOwnPropertySymbols(object).forEach( - (symbol): void => { - if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) { - keys.push(symbol); - } + Object.getOwnPropertySymbols(object).forEach((symbol): void => { + if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) { + keys.push(symbol); } - ); + }); } return keys; diff --git a/std/testing/mod.ts b/std/testing/mod.ts index bd7642b81..3b6386d5b 100644 --- a/std/testing/mod.ts +++ b/std/testing/mod.ts @@ -203,14 +203,12 @@ function report(result: TestResult): void { } function printFailedSummary(results: TestResults): void { - results.cases.forEach( - (v): void => { - if (!v.ok) { - console.error(`${RED_BG_FAIL} ${red(v.name)}`); - console.error(v.error); - } + results.cases.forEach((v): void => { + if (!v.ok) { + console.error(`${RED_BG_FAIL} ${red(v.name)}`); + console.error(v.error); } - ); + }); } function printResults( @@ -321,14 +319,12 @@ async function runTestsSerial( print( GREEN_OK + " " + name + " " + promptTestTime(end - start, true) ); - results.cases.forEach( - (v): void => { - if (v.name === name) { - v.ok = true; - v.printed = true; - } + results.cases.forEach((v): void => { + if (v.name === name) { + v.ok = true; + v.printed = true; } - ); + }); } catch (err) { if (disableLog) { print(CLEAR_LINE, false); @@ -336,15 +332,13 @@ async function runTestsSerial( print(`${RED_FAILED} ${name}`); print(err.stack); stats.failed++; - results.cases.forEach( - (v): void => { - if (v.name === name) { - v.error = err; - v.ok = false; - v.printed = true; - } + results.cases.forEach((v): void => { + if (v.name === name) { + v.error = err; + v.ok = false; + v.printed = true; } - ); + }); if (exitOnFail) { break; } diff --git a/std/testing/runner.ts b/std/testing/runner.ts index 48bc4c9c3..d0e9546f5 100755 --- a/std/testing/runner.ts +++ b/std/testing/runner.ts @@ -204,8 +204,8 @@ async function main(): Promise<void> { const include = parsedArgs._.length > 0 - ? (parsedArgs._ as string[]).flatMap( - (fileGlob: string): string[] => fileGlob.split(",") + ? (parsedArgs._ as string[]).flatMap((fileGlob: string): string[] => + fileGlob.split(",") ) : ["."]; const exclude = diff --git a/std/testing/test.ts b/std/testing/test.ts index 93233f7cc..dd6d772f6 100644 --- a/std/testing/test.ts +++ b/std/testing/test.ts @@ -51,12 +51,10 @@ test(function testingAssertNotStrictEqual(): void { test(function testingDoesThrow(): void { let count = 0; - assertThrows( - (): void => { - count++; - throw new Error(); - } - ); + assertThrows((): void => { + count++; + throw new Error(); + }); assert(count === 1); }); @@ -64,12 +62,10 @@ test(function testingDoesNotThrow(): void { let count = 0; let didThrow = false; try { - assertThrows( - (): void => { - count++; - console.log("Hello world"); - } - ); + assertThrows((): void => { + count++; + console.log("Hello world"); + }); } catch (e) { assert(e.message === "Expected function to throw."); didThrow = true; diff --git a/std/textproto/reader_test.ts b/std/textproto/reader_test.ts index adfb0c962..fe842e0e2 100644 --- a/std/textproto/reader_test.ts +++ b/std/textproto/reader_test.ts @@ -114,11 +114,9 @@ test({ assertEquals(m.get("SID"), "0"); assertEquals(m.get("Privilege"), "127"); // Not a legal http header - assertThrows( - (): void => { - assertEquals(m.get("Audio Mode"), "None"); - } - ); + assertThrows((): void => { + assertEquals(m.get("Audio Mode"), "None"); + }); } }); diff --git a/std/util/async.ts b/std/util/async.ts index 8c4823ad9..6e2db69dc 100644 --- a/std/util/async.ts +++ b/std/util/async.ts @@ -20,11 +20,9 @@ export interface Deferred<T> extends Promise<T> { */ export function deferred<T>(): Deferred<T> { let methods; - const promise = new Promise<T>( - (resolve, reject): void => { - methods = { resolve, reject }; - } - ); + const promise = new Promise<T>((resolve, reject): void => { + methods = { resolve, reject }; + }); return Object.assign(promise, methods)! as Deferred<T>; } @@ -111,10 +109,9 @@ export async function collectUint8Arrays( // Delays the given milliseconds and resolves. export function delay(ms: number): Promise<void> { - return new Promise( - (res): number => - setTimeout((): void => { - res(); - }, ms) + return new Promise((res): number => + setTimeout((): void => { + res(); + }, ms) ); } diff --git a/std/util/deep_assign.ts b/std/util/deep_assign.ts index 1dfc00a5b..b1c9f9ac9 100644 --- a/std/util/deep_assign.ts +++ b/std/util/deep_assign.ts @@ -8,26 +8,24 @@ export function deepAssign( if (!source || typeof source !== `object`) { return; } - Object.entries(source).forEach( - ([key, value]: [string, unknown]): void => { - if (value instanceof Date) { - target[key] = new Date(value); - return; - } - if (!value || typeof value !== `object`) { - target[key] = value; - return; - } - if (Array.isArray(value)) { - target[key] = []; - } - // value is an Object - if (typeof target[key] !== `object` || !target[key]) { - target[key] = {}; - } - deepAssign(target[key] as Record<string, unknown>, value!); + Object.entries(source).forEach(([key, value]: [string, unknown]): void => { + if (value instanceof Date) { + target[key] = new Date(value); + return; } - ); + if (!value || typeof value !== `object`) { + target[key] = value; + return; + } + if (Array.isArray(value)) { + target[key] = []; + } + // value is an Object + if (typeof target[key] !== `object` || !target[key]) { + target[key] = {}; + } + deepAssign(target[key] as Record<string, unknown>, value!); + }); } return target; } diff --git a/std/uuid/v4.ts b/std/uuid/v4.ts index 84ba28b0f..511933439 100644 --- a/std/uuid/v4.ts +++ b/std/uuid/v4.ts @@ -15,12 +15,10 @@ export default function generate(): string { rnds[6] = (rnds[6] & 0x0f) | 0x40; // Version 4 rnds[8] = (rnds[8] & 0x3f) | 0x80; // Variant 10 - const bits: string[] = [...rnds].map( - (bit): string => { - const s: string = bit.toString(16); - return bit < 0x10 ? "0" + s : s; - } - ); + const bits: string[] = [...rnds].map((bit): string => { + const s: string = bit.toString(16); + return bit < 0x10 ? "0" + s : s; + }); return [ ...bits.slice(0, 4), "-", diff --git a/std/ws/README.md b/std/ws/README.md index 271bf2afb..39bac4741 100644 --- a/std/ws/README.md +++ b/std/ws/README.md @@ -60,11 +60,9 @@ for await (const req of serve(`:${port}`)) { } } ) - .catch( - (err: Error): void => { - console.error(`failed to accept websocket: ${err}`); - } - ); + .catch((err: Error): void => { + console.error(`failed to accept websocket: ${err}`); + }); } ``` @@ -117,11 +115,9 @@ while (true) { } // FIXME: Without this, // sock.receive() won't resolved though it is readable... - await new Promise( - (resolve): void => { - setTimeout(resolve, 0); - } - ); + await new Promise((resolve): void => { + setTimeout(resolve, 0); + }); } await sock.close(1000); // FIXME: conn.close() won't shutdown process... diff --git a/std/ws/example_client.ts b/std/ws/example_client.ts index 3b132281f..d5c5f3058 100644 --- a/std/ws/example_client.ts +++ b/std/ws/example_client.ts @@ -44,11 +44,9 @@ while (true) { } // FIXME: Without this, // sock.receive() won't resolved though it is readable... - await new Promise( - (resolve): void => { - setTimeout(resolve, 0); - } - ); + await new Promise((resolve): void => { + setTimeout(resolve, 0); + }); } await sock.close(1000); // FIXME: conn.close() won't shutdown process... diff --git a/std/ws/example_server.ts b/std/ws/example_server.ts index ea981256e..cb8ec61cd 100644 --- a/std/ws/example_server.ts +++ b/std/ws/example_server.ts @@ -52,9 +52,7 @@ for await (const req of serve(`:${port}`)) { } } ) - .catch( - (err: Error): void => { - console.error(`failed to accept websocket: ${err}`); - } - ); + .catch((err: Error): void => { + console.error(`failed to accept websocket: ${err}`); + }); } |