diff options
Diffstat (limited to 'std/fs')
46 files changed, 0 insertions, 3797 deletions
diff --git a/std/fs/README.md b/std/fs/README.md deleted file mode 100644 index c82fb1219..000000000 --- a/std/fs/README.md +++ /dev/null @@ -1,177 +0,0 @@ -# fs - -fs module is made to provide helpers to manipulate the filesystem. - -## Usage - -Most of the following modules are exposed in `mod.ts`. This feature is currently -<b>unstable</b>. To enable it use `deno run --unstable`. - -### emptyDir - -Ensures that a directory is empty. Deletes directory contents if the directory -is not empty. If the directory does not exist, it is created. The directory -itself is not deleted. - -```ts -import { - emptyDir, - emptyDirSync, -} from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -emptyDir("./foo"); // returns a promise -emptyDirSync("./foo"); // void -``` - -### ensureDir - -Ensures that the directory exists. If the directory structure does not exist, it -is created. Like `mkdir -p`. - -```ts -import { - ensureDir, - ensureDirSync, -} from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -ensureDir("./bar"); // returns a promise -ensureDirSync("./ensureDirSync"); // void -``` - -### ensureFile - -Ensures that the file exists. If the file that is requested to be created is in -directories that do not exist, these directories are created. If the file -already exists, it is **NOT MODIFIED**. - -```ts -import { - ensureFile, - ensureFileSync, -} from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -ensureFile("./folder/targetFile.dat"); // returns promise -ensureFileSync("./folder/targetFile.dat"); // void -``` - -### ensureSymlink - -Ensures that the link exists. If the directory structure does not exist, it is -created. - -```ts -import { - ensureSymlink, - ensureSymlinkSync, -} from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -ensureSymlink("./folder/targetFile.dat", "./folder/targetFile.link.dat"); // returns promise -ensureSymlinkSync("./folder/targetFile.dat", "./folder/targetFile.link.dat"); // void -``` - -### EOL - -Detects and format the passed string for the targeted End Of Line character. - -```ts -import { format, detect, EOL } from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -const CRLFinput = "deno\r\nis not\r\nnode"; -const Mixedinput = "deno\nis not\r\nnode"; -const LFinput = "deno\nis not\nnode"; -const NoNLinput = "deno is not node"; - -detect(LFinput); // output EOL.LF -detect(CRLFinput); // output EOL.CRLF -detect(Mixedinput); // output EOL.CRLF -detect(NoNLinput); // output null - -format(CRLFinput, EOL.LF); // output "deno\nis not\nnode" -... -``` - -### exists - -Test whether or not the given path exists by checking with the file system. - -```ts -import { - exists, - existsSync, -} from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -exists("./foo"); // returns a Promise<boolean> -existsSync("./foo"); // returns boolean -``` - -### move - -Moves a file or directory. Overwrites it if option provided. - -```ts -import { move, moveSync } from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -move("./foo", "./bar"); // returns a promise -moveSync("./foo", "./bar"); // void -moveSync("./foo", "./existingFolder", { overwrite: true }); -// Will overwrite existingFolder -``` - -### copy - -copy a file or directory. Overwrites it if option provided. - -```ts -import { copy, copySync } from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -copy("./foo", "./bar"); // returns a promise -copySync("./foo", "./bar"); // void -copySync("./foo", "./existingFolder", { overwrite: true }); -// Will overwrite existingFolder -``` - -### walk - -Iterate all files in a directory recursively. - -```ts -import { walk, walkSync } from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -for (const entry of walkSync(".")) { - console.log(entry.path); -} - -// Async -async function printFilesNames() { - for await (const entry of walk(".")) { - console.log(entry.path); - } -} - -printFilesNames().then(() => console.log("Done!")); -``` - -### expandGlob - -Expand the glob string from the specified `root` directory and yield each result -as a `WalkEntry` object. - -```ts -import { expandGlob } from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -for await (const file of expandGlob("**/*.ts")) { - console.log(file); -} -``` - -### expandGlobSync - -Synchronous version of `expandGlob()`. - -```ts -import { expandGlobSync } from "https://deno.land/std@$STD_VERSION/fs/mod.ts"; - -for (const file of expandGlobSync("**/*.ts")) { - console.log(file); -} -``` diff --git a/std/fs/_util.ts b/std/fs/_util.ts deleted file mode 100644 index a9445a394..000000000 --- a/std/fs/_util.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; - -/** - * Test whether or not `dest` is a sub-directory of `src` - * @param src src file path - * @param dest dest file path - * @param sep path separator - */ -export function isSubdir( - src: string, - dest: string, - sep: string = path.sep, -): boolean { - if (src === dest) { - return false; - } - const srcArray = src.split(sep); - const destArray = dest.split(sep); - return srcArray.every((current, i) => destArray[i] === current); -} - -export type PathType = "file" | "dir" | "symlink"; - -/** - * Get a human readable file type string. - * - * @param fileInfo A FileInfo describes a file and is returned by `stat`, - * `lstat` - */ -export function getFileInfoType(fileInfo: Deno.FileInfo): PathType | undefined { - return fileInfo.isFile - ? "file" - : fileInfo.isDirectory - ? "dir" - : fileInfo.isSymlink - ? "symlink" - : undefined; -} diff --git a/std/fs/_util_test.ts b/std/fs/_util_test.ts deleted file mode 100644 index 9a24caaf0..000000000 --- a/std/fs/_util_test.ts +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright the Browserify authors. MIT License. - -import { assertEquals } from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { getFileInfoType, isSubdir, PathType } from "./_util.ts"; -import { ensureFileSync } from "./ensure_file.ts"; -import { ensureDirSync } from "./ensure_dir.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -Deno.test("_isSubdir", function (): void { - const pairs = [ - ["", "", false, path.posix.sep], - ["/first/second", "/first", false, path.posix.sep], - ["/first", "/first", false, path.posix.sep], - ["/first", "/first/second", true, path.posix.sep], - ["first", "first/second", true, path.posix.sep], - ["../first", "../first/second", true, path.posix.sep], - ["c:\\first", "c:\\first", false, path.win32.sep], - ["c:\\first", "c:\\first\\second", true, path.win32.sep], - ]; - - pairs.forEach(function (p): void { - const src = p[0] as string; - const dest = p[1] as string; - const expected = p[2] as boolean; - const sep = p[3] as string; - assertEquals( - isSubdir(src, dest, sep), - expected, - `'${src}' should ${expected ? "" : "not"} be parent dir of '${dest}'`, - ); - }); -}); - -Deno.test("_getFileInfoType", function (): void { - const pairs = [ - [path.join(testdataDir, "file_type_1"), "file"], - [path.join(testdataDir, "file_type_dir_1"), "dir"], - ]; - - pairs.forEach(function (p): void { - const filePath = p[0] as string; - const type = p[1] as PathType; - switch (type) { - case "file": - ensureFileSync(filePath); - break; - case "dir": - ensureDirSync(filePath); - break; - case "symlink": - // TODO(axetroy): test symlink - break; - } - - const stat = Deno.statSync(filePath); - - Deno.removeSync(filePath, { recursive: true }); - - assertEquals(getFileInfoType(stat), type); - }); -}); diff --git a/std/fs/copy.ts b/std/fs/copy.ts deleted file mode 100644 index 05ea6056b..000000000 --- a/std/fs/copy.ts +++ /dev/null @@ -1,307 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { getFileInfoType, isSubdir } from "./_util.ts"; -import { assert } from "../_util/assert.ts"; -import { isWindows } from "../_util/os.ts"; - -export interface CopyOptions { - /** - * overwrite existing file or directory. Default is `false` - */ - overwrite?: boolean; - /** - * When `true`, will set last modification and access times to the ones of the - * original source files. - * When `false`, timestamp behavior is OS-dependent. - * Default is `false`. - */ - preserveTimestamps?: boolean; -} - -interface InternalCopyOptions extends CopyOptions { - /** - * default is `false` - */ - isFolder?: boolean; -} - -async function ensureValidCopy( - src: string, - dest: string, - options: InternalCopyOptions, -): Promise<Deno.FileInfo | undefined> { - let destStat: Deno.FileInfo; - - try { - destStat = await Deno.lstat(dest); - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return; - } - throw err; - } - - if (options.isFolder && !destStat.isDirectory) { - throw new Error( - `Cannot overwrite non-directory '${dest}' with directory '${src}'.`, - ); - } - if (!options.overwrite) { - throw new Error(`'${dest}' already exists.`); - } - - return destStat; -} - -function ensureValidCopySync( - src: string, - dest: string, - options: InternalCopyOptions, -): Deno.FileInfo | undefined { - let destStat: Deno.FileInfo; - try { - destStat = Deno.lstatSync(dest); - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return; - } - throw err; - } - - if (options.isFolder && !destStat.isDirectory) { - throw new Error( - `Cannot overwrite non-directory '${dest}' with directory '${src}'.`, - ); - } - if (!options.overwrite) { - throw new Error(`'${dest}' already exists.`); - } - - return destStat; -} - -/* copy file to dest */ -async function copyFile( - src: string, - dest: string, - options: InternalCopyOptions, -): Promise<void> { - await ensureValidCopy(src, dest, options); - await Deno.copyFile(src, dest); - if (options.preserveTimestamps) { - const statInfo = await Deno.stat(src); - assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - await Deno.utime(dest, statInfo.atime, statInfo.mtime); - } -} -/* copy file to dest synchronously */ -function copyFileSync( - src: string, - dest: string, - options: InternalCopyOptions, -): void { - ensureValidCopySync(src, dest, options); - Deno.copyFileSync(src, dest); - if (options.preserveTimestamps) { - const statInfo = Deno.statSync(src); - assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - Deno.utimeSync(dest, statInfo.atime, statInfo.mtime); - } -} - -/* copy symlink to dest */ -async function copySymLink( - src: string, - dest: string, - options: InternalCopyOptions, -): Promise<void> { - await ensureValidCopy(src, dest, options); - const originSrcFilePath = await Deno.readLink(src); - const type = getFileInfoType(await Deno.lstat(src)); - if (isWindows) { - await Deno.symlink(originSrcFilePath, dest, { - type: type === "dir" ? "dir" : "file", - }); - } else { - await Deno.symlink(originSrcFilePath, dest); - } - if (options.preserveTimestamps) { - const statInfo = await Deno.lstat(src); - assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - await Deno.utime(dest, statInfo.atime, statInfo.mtime); - } -} - -/* copy symlink to dest synchronously */ -function copySymlinkSync( - src: string, - dest: string, - options: InternalCopyOptions, -): void { - ensureValidCopySync(src, dest, options); - const originSrcFilePath = Deno.readLinkSync(src); - const type = getFileInfoType(Deno.lstatSync(src)); - if (isWindows) { - Deno.symlinkSync(originSrcFilePath, dest, { - type: type === "dir" ? "dir" : "file", - }); - } else { - Deno.symlinkSync(originSrcFilePath, dest); - } - - if (options.preserveTimestamps) { - const statInfo = Deno.lstatSync(src); - assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - Deno.utimeSync(dest, statInfo.atime, statInfo.mtime); - } -} - -/* copy folder from src to dest. */ -async function copyDir( - src: string, - dest: string, - options: CopyOptions, -): Promise<void> { - const destStat = await ensureValidCopy(src, dest, { - ...options, - isFolder: true, - }); - - if (!destStat) { - await ensureDir(dest); - } - - if (options.preserveTimestamps) { - const srcStatInfo = await Deno.stat(src); - assert(srcStatInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(srcStatInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - await Deno.utime(dest, srcStatInfo.atime, srcStatInfo.mtime); - } - - for await (const entry of Deno.readDir(src)) { - const srcPath = path.join(src, entry.name); - const destPath = path.join(dest, path.basename(srcPath as string)); - if (entry.isSymlink) { - await copySymLink(srcPath, destPath, options); - } else if (entry.isDirectory) { - await copyDir(srcPath, destPath, options); - } else if (entry.isFile) { - await copyFile(srcPath, destPath, options); - } - } -} - -/* copy folder from src to dest synchronously */ -function copyDirSync(src: string, dest: string, options: CopyOptions): void { - const destStat = ensureValidCopySync(src, dest, { - ...options, - isFolder: true, - }); - - if (!destStat) { - ensureDirSync(dest); - } - - if (options.preserveTimestamps) { - const srcStatInfo = Deno.statSync(src); - assert(srcStatInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(srcStatInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - Deno.utimeSync(dest, srcStatInfo.atime, srcStatInfo.mtime); - } - - for (const entry of Deno.readDirSync(src)) { - assert(entry.name != null, "file.name must be set"); - const srcPath = path.join(src, entry.name); - const destPath = path.join(dest, path.basename(srcPath as string)); - if (entry.isSymlink) { - copySymlinkSync(srcPath, destPath, options); - } else if (entry.isDirectory) { - copyDirSync(srcPath, destPath, options); - } else if (entry.isFile) { - copyFileSync(srcPath, destPath, options); - } - } -} - -/** - * Copy a file or directory. The directory can have contents. Like `cp -r`. - * Requires the `--allow-read` and `--allow-write` flag. - * @param src the file/directory path. - * Note that if `src` is a directory it will copy everything inside - * of this directory, not the entire directory itself - * @param dest the destination path. Note that if `src` is a file, `dest` cannot - * be a directory - * @param options - */ -export async function copy( - src: string, - dest: string, - options: CopyOptions = {}, -): Promise<void> { - src = path.resolve(src); - dest = path.resolve(dest); - - if (src === dest) { - throw new Error("Source and destination cannot be the same."); - } - - const srcStat = await Deno.lstat(src); - - if (srcStat.isDirectory && isSubdir(src, dest)) { - throw new Error( - `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`, - ); - } - - if (srcStat.isSymlink) { - await copySymLink(src, dest, options); - } else if (srcStat.isDirectory) { - await copyDir(src, dest, options); - } else if (srcStat.isFile) { - await copyFile(src, dest, options); - } -} - -/** - * Copy a file or directory. The directory can have contents. Like `cp -r`. - * Requires the `--allow-read` and `--allow-write` flag. - * @param src the file/directory path. - * Note that if `src` is a directory it will copy everything inside - * of this directory, not the entire directory itself - * @param dest the destination path. Note that if `src` is a file, `dest` cannot - * be a directory - * @param options - */ -export function copySync( - src: string, - dest: string, - options: CopyOptions = {}, -): void { - src = path.resolve(src); - dest = path.resolve(dest); - - if (src === dest) { - throw new Error("Source and destination cannot be the same."); - } - - const srcStat = Deno.lstatSync(src); - - if (srcStat.isDirectory && isSubdir(src, dest)) { - throw new Error( - `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`, - ); - } - - if (srcStat.isSymlink) { - copySymlinkSync(src, dest, options); - } else if (srcStat.isDirectory) { - copyDirSync(src, dest, options); - } else if (srcStat.isFile) { - copyFileSync(src, dest, options); - } -} diff --git a/std/fs/copy_test.ts b/std/fs/copy_test.ts deleted file mode 100644 index 40d7cb19a..000000000 --- a/std/fs/copy_test.ts +++ /dev/null @@ -1,520 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assert, - assertEquals, - assertThrows, - assertThrowsAsync, -} from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { copy, copySync } from "./copy.ts"; -import { exists, existsSync } from "./exists.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { ensureFile, ensureFileSync } from "./ensure_file.ts"; -import { ensureSymlink, ensureSymlinkSync } from "./ensure_symlink.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -function testCopy( - name: string, - cb: (tempDir: string) => Promise<void>, - ignore = false, -): void { - Deno.test({ - name, - async fn(): Promise<void> { - const tempDir = await Deno.makeTempDir({ - prefix: "deno_std_copy_async_test_", - }); - await cb(tempDir); - await Deno.remove(tempDir, { recursive: true }); - }, - ignore, - }); -} - -function testCopySync(name: string, cb: (tempDir: string) => void): void { - Deno.test({ - name, - fn: (): void => { - const tempDir = Deno.makeTempDirSync({ - prefix: "deno_std_copy_sync_test_", - }); - cb(tempDir); - Deno.removeSync(tempDir, { recursive: true }); - }, - }); -} - -testCopy( - "[fs] copy file if it does no exist", - async (tempDir: string): Promise<void> => { - const srcFile = path.join(testdataDir, "copy_file_not_exists.txt"); - const destFile = path.join(tempDir, "copy_file_not_exists_1.txt"); - await assertThrowsAsync( - async (): Promise<void> => { - await copy(srcFile, destFile); - }, - ); - }, -); - -testCopy( - "[fs] copy if src and dest are the same paths", - async (tempDir: string): Promise<void> => { - const srcFile = path.join(tempDir, "copy_file_same.txt"); - const destFile = path.join(tempDir, "copy_file_same.txt"); - await assertThrowsAsync( - async (): Promise<void> => { - await copy(srcFile, destFile); - }, - Error, - "Source and destination cannot be the same.", - ); - }, -); - -testCopy( - "[fs] copy file", - async (tempDir: string): Promise<void> => { - const srcFile = path.join(testdataDir, "copy_file.txt"); - const destFile = path.join(tempDir, "copy_file_copy.txt"); - - const srcContent = new TextDecoder().decode(await Deno.readFile(srcFile)); - - assertEquals( - await exists(srcFile), - true, - `source should exist before copy`, - ); - assertEquals( - await exists(destFile), - false, - "destination should not exist before copy", - ); - - await copy(srcFile, destFile); - - assertEquals(await exists(srcFile), true, "source should exist after copy"); - assertEquals( - await exists(destFile), - true, - "destination should exist before copy", - ); - - const destContent = new TextDecoder().decode(await Deno.readFile(destFile)); - - assertEquals( - srcContent, - destContent, - "source and destination should have the same content", - ); - - // Copy again and it should throw an error. - await assertThrowsAsync( - async (): Promise<void> => { - await copy(srcFile, destFile); - }, - Error, - `'${destFile}' already exists.`, - ); - - // Modify destination file. - await Deno.writeFile(destFile, new TextEncoder().encode("txt copy")); - - assertEquals( - new TextDecoder().decode(await Deno.readFile(destFile)), - "txt copy", - ); - - // Copy again with overwrite option. - await copy(srcFile, destFile, { overwrite: true }); - - // Make sure the file has been overwritten. - assertEquals( - new TextDecoder().decode(await Deno.readFile(destFile)), - "txt", - ); - }, -); - -testCopy( - "[fs] copy with preserve timestamps", - async (tempDir: string): Promise<void> => { - const srcFile = path.join(testdataDir, "copy_file.txt"); - const destFile = path.join(tempDir, "copy_file_copy.txt"); - - const srcStatInfo = await Deno.stat(srcFile); - - assert(srcStatInfo.atime instanceof Date); - assert(srcStatInfo.mtime instanceof Date); - - // Copy with overwrite and preserve timestamps options. - await copy(srcFile, destFile, { - overwrite: true, - preserveTimestamps: true, - }); - - const destStatInfo = await Deno.stat(destFile); - - assert(destStatInfo.atime instanceof Date); - assert(destStatInfo.mtime instanceof Date); - assertEquals(destStatInfo.atime, srcStatInfo.atime); - assertEquals(destStatInfo.mtime, srcStatInfo.mtime); - }, -); - -testCopy( - "[fs] copy directory to its subdirectory", - async (tempDir: string): Promise<void> => { - const srcDir = path.join(tempDir, "parent"); - const destDir = path.join(srcDir, "child"); - - await ensureDir(srcDir); - - await assertThrowsAsync( - async (): Promise<void> => { - await copy(srcDir, destDir); - }, - Error, - `Cannot copy '${srcDir}' to a subdirectory of itself, '${destDir}'.`, - ); - }, -); - -testCopy( - "[fs] copy directory and destination exist and not a directory", - async (tempDir: string): Promise<void> => { - const srcDir = path.join(tempDir, "parent"); - const destDir = path.join(tempDir, "child.txt"); - - await ensureDir(srcDir); - await ensureFile(destDir); - - await assertThrowsAsync( - async (): Promise<void> => { - await copy(srcDir, destDir); - }, - Error, - `Cannot overwrite non-directory '${destDir}' with directory '${srcDir}'.`, - ); - }, -); - -testCopy( - "[fs] copy directory", - async (tempDir: string): Promise<void> => { - const srcDir = path.join(testdataDir, "copy_dir"); - const destDir = path.join(tempDir, "copy_dir"); - 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"); - - await copy(srcDir, destDir); - - assertEquals(await exists(destFile), true); - assertEquals(await exists(destNestFile), true); - - // After copy. The source and destination should have the same content. - assertEquals( - new TextDecoder().decode(await Deno.readFile(srcFile)), - new TextDecoder().decode(await Deno.readFile(destFile)), - ); - assertEquals( - new TextDecoder().decode(await Deno.readFile(srcNestFile)), - new TextDecoder().decode(await Deno.readFile(destNestFile)), - ); - - // Copy again without overwrite option and it should throw an error. - await assertThrowsAsync( - async (): Promise<void> => { - await copy(srcDir, destDir); - }, - Error, - `'${destDir}' already exists.`, - ); - - // Modify the file in the destination directory. - await Deno.writeFile(destNestFile, new TextEncoder().encode("nest copy")); - assertEquals( - new TextDecoder().decode(await Deno.readFile(destNestFile)), - "nest copy", - ); - - // Copy again with overwrite option. - await copy(srcDir, destDir, { overwrite: true }); - - // Make sure the file has been overwritten. - assertEquals( - new TextDecoder().decode(await Deno.readFile(destNestFile)), - "nest", - ); - }, -); - -testCopy( - "[fs] copy symlink file", - async (tempDir: string): Promise<void> => { - const dir = path.join(testdataDir, "copy_dir_link_file"); - const srcLink = path.join(dir, "0.txt"); - const destLink = path.join(tempDir, "0_copy.txt"); - - assert( - (await Deno.lstat(srcLink)).isSymlink, - `'${srcLink}' should be symlink type`, - ); - - await copy(srcLink, destLink); - - const statInfo = await Deno.lstat(destLink); - - assert(statInfo.isSymlink, `'${destLink}' should be symlink type`); - }, -); - -testCopy( - "[fs] copy symlink directory", - async (tempDir: string): Promise<void> => { - const srcDir = path.join(testdataDir, "copy_dir"); - const srcLink = path.join(tempDir, "copy_dir_link"); - const destLink = path.join(tempDir, "copy_dir_link_copy"); - - await ensureSymlink(srcDir, srcLink); - - assert( - (await Deno.lstat(srcLink)).isSymlink, - `'${srcLink}' should be symlink type`, - ); - - await copy(srcLink, destLink); - - const statInfo = await Deno.lstat(destLink); - - assert(statInfo.isSymlink); - }, -); - -testCopySync( - "[fs] copy file synchronously if it does not exist", - (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); - }); - }, -); - -testCopySync( - "[fs] copy synchronously with preserve timestamps", - (tempDir: string): void => { - const srcFile = path.join(testdataDir, "copy_file.txt"); - const destFile = path.join(tempDir, "copy_file_copy.txt"); - - const srcStatInfo = Deno.statSync(srcFile); - - assert(srcStatInfo.atime instanceof Date); - assert(srcStatInfo.mtime instanceof Date); - - // Copy with overwrite and preserve timestamps options. - copySync(srcFile, destFile, { - overwrite: true, - preserveTimestamps: true, - }); - - const destStatInfo = Deno.statSync(destFile); - - assert(destStatInfo.atime instanceof Date); - assert(destStatInfo.mtime instanceof Date); - // TODO(bartlomieju): Activate test when https://github.com/denoland/deno/issues/2411 - // is fixed - // assertEquals(destStatInfo.atime, srcStatInfo.atime); - // assertEquals(destStatInfo.mtime, srcStatInfo.mtime); - }, -); - -testCopySync( - "[fs] copy synchronously if src and dest are the same paths", - (): void => { - const srcFile = path.join(testdataDir, "copy_file_same_sync.txt"); - assertThrows( - (): void => { - copySync(srcFile, srcFile); - }, - Error, - "Source and destination cannot be the same.", - ); - }, -); - -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)); - - assertEquals(existsSync(srcFile), true); - assertEquals(existsSync(destFile), false); - - copySync(srcFile, destFile); - - assertEquals(existsSync(srcFile), true); - assertEquals(existsSync(destFile), true); - - const destContent = new TextDecoder().decode(Deno.readFileSync(destFile)); - - assertEquals(srcContent, destContent); - - // 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")); - - assertEquals( - new TextDecoder().decode(Deno.readFileSync(destFile)), - "txt copy", - ); - - // 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"); -}); - -testCopySync( - "[fs] copy directory synchronously to its subdirectory", - (tempDir: string): void => { - const srcDir = path.join(tempDir, "parent"); - const destDir = path.join(srcDir, "child"); - - ensureDirSync(srcDir); - - assertThrows( - (): void => { - copySync(srcDir, destDir); - }, - Error, - `Cannot copy '${srcDir}' to a subdirectory of itself, '${destDir}'.`, - ); - }, -); - -testCopySync( - "[fs] copy directory synchronously, and destination exist and not a " + - "directory", - (tempDir: string): void => { - const srcDir = path.join(tempDir, "parent_sync"); - const destDir = path.join(tempDir, "child.txt"); - - ensureDirSync(srcDir); - ensureFileSync(destDir); - - assertThrows( - (): void => { - copySync(srcDir, destDir); - }, - Error, - `Cannot overwrite non-directory '${destDir}' with directory '${srcDir}'.`, - ); - }, -); - -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", - (tempDir: string): void => { - const dir = path.join(testdataDir, "copy_dir_link_file"); - const srcLink = path.join(dir, "0.txt"); - const destLink = path.join(tempDir, "0_copy.txt"); - - assert( - Deno.lstatSync(srcLink).isSymlink, - `'${srcLink}' should be symlink type`, - ); - - copySync(srcLink, destLink); - - const statInfo = Deno.lstatSync(destLink); - - assert(statInfo.isSymlink, `'${destLink}' should be symlink type`); - }, -); - -testCopySync( - "[fs] copy symlink directory synchronously", - (tempDir: string): void => { - const originDir = path.join(testdataDir, "copy_dir"); - const srcLink = path.join(tempDir, "copy_dir_link"); - const destLink = path.join(tempDir, "copy_dir_link_copy"); - - ensureSymlinkSync(originDir, srcLink); - - assert( - Deno.lstatSync(srcLink).isSymlink, - `'${srcLink}' should be symlink type`, - ); - - copySync(srcLink, destLink); - - const statInfo = Deno.lstatSync(destLink); - - assert(statInfo.isSymlink); - }, -); diff --git a/std/fs/empty_dir.ts b/std/fs/empty_dir.ts deleted file mode 100644 index df73ad6b7..000000000 --- a/std/fs/empty_dir.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { join } from "../path/mod.ts"; - -/** - * Ensures that a directory is empty. - * Deletes directory contents if the directory is not empty. - * If the directory does not exist, it is created. - * The directory itself is not deleted. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export async function emptyDir(dir: string): Promise<void> { - try { - const items = []; - for await (const dirEntry of Deno.readDir(dir)) { - items.push(dirEntry); - } - - while (items.length) { - const item = items.shift(); - if (item && item.name) { - const filepath = join(dir, item.name); - await Deno.remove(filepath, { recursive: true }); - } - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - - // if not exist. then create it - await Deno.mkdir(dir, { recursive: true }); - } -} - -/** - * Ensures that a directory is empty. - * Deletes directory contents if the directory is not empty. - * If the directory does not exist, it is created. - * The directory itself is not deleted. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export function emptyDirSync(dir: string): void { - try { - const items = [...Deno.readDirSync(dir)]; - - // If the directory exists, remove all entries inside it. - while (items.length) { - const item = items.shift(); - if (item && item.name) { - const filepath = join(dir, item.name); - Deno.removeSync(filepath, { recursive: true }); - } - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - // if not exist. then create it - Deno.mkdirSync(dir, { recursive: true }); - return; - } -} diff --git a/std/fs/empty_dir_test.ts b/std/fs/empty_dir_test.ts deleted file mode 100644 index a78f221eb..000000000 --- a/std/fs/empty_dir_test.ts +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assert, - assertEquals, - assertStringIncludes, - assertThrows, - assertThrowsAsync, -} from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { emptyDir, emptyDirSync } from "./empty_dir.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -Deno.test("emptyDirIfItNotExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "empty_dir_test_1"); - const testNestDir = path.join(testDir, "nest"); - // empty a dir which not exist. then it will create new one - await emptyDir(testNestDir); - - try { - // check the dir - const stat = await Deno.stat(testNestDir); - assertEquals(stat.isDirectory, true); - } finally { - // remove the test dir - await Deno.remove(testDir, { recursive: true }); - } -}); - -Deno.test("emptyDirSyncIfItNotExist", function (): void { - const testDir = path.join(testdataDir, "empty_dir_test_2"); - const testNestDir = path.join(testDir, "nest"); - // empty a dir which does not exist, then it will a create new one. - emptyDirSync(testNestDir); - - try { - // check the dir - const stat = Deno.statSync(testNestDir); - assertEquals(stat.isDirectory, true); - } finally { - // remove the test dir - Deno.removeSync(testDir, { recursive: true }); - } -}); - -Deno.test("emptyDirIfItExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "empty_dir_test_3"); - const testNestDir = path.join(testDir, "nest"); - // create test dir - await emptyDir(testNestDir); - const testDirFile = path.join(testNestDir, "test.ts"); - // create test file in test dir - await Deno.writeFile(testDirFile, new Uint8Array()); - - // before empty: make sure file/directory exist - const beforeFileStat = await Deno.stat(testDirFile); - assertEquals(beforeFileStat.isFile, true); - - const beforeDirStat = await Deno.stat(testNestDir); - assertEquals(beforeDirStat.isDirectory, true); - - await emptyDir(testDir); - - // after empty: file/directory have already been removed - try { - // test dir still there - const stat = await Deno.stat(testDir); - assertEquals(stat.isDirectory, true); - - // nest directory have been removed - await assertThrowsAsync( - async (): Promise<void> => { - await Deno.stat(testNestDir); - }, - ); - - // test file have been removed - await assertThrowsAsync( - async (): Promise<void> => { - await Deno.stat(testDirFile); - }, - ); - } finally { - // remote test dir - await Deno.remove(testDir, { recursive: true }); - } -}); - -Deno.test("emptyDirSyncIfItExist", function (): void { - const testDir = path.join(testdataDir, "empty_dir_test_4"); - const testNestDir = path.join(testDir, "nest"); - // create test dir - emptyDirSync(testNestDir); - const testDirFile = path.join(testNestDir, "test.ts"); - // create test file in test dir - Deno.writeFileSync(testDirFile, new Uint8Array()); - - // before empty: make sure file/directory exist - const beforeFileStat = Deno.statSync(testDirFile); - assertEquals(beforeFileStat.isFile, true); - - const beforeDirStat = Deno.statSync(testNestDir); - assertEquals(beforeDirStat.isDirectory, true); - - emptyDirSync(testDir); - - // after empty: file/directory have already remove - try { - // test dir still present - const stat = Deno.statSync(testDir); - assertEquals(stat.isDirectory, true); - - // nest directory have been removed - assertThrows((): void => { - Deno.statSync(testNestDir); - }); - - // test file have been removed - assertThrows((): void => { - Deno.statSync(testDirFile); - }); - } finally { - // remote test dir - Deno.removeSync(testDir, { recursive: true }); - } -}); - -interface Scenes { - read: boolean; // --allow-read - write: boolean; // --allow-write - async: boolean; - output: string; -} -const scenes: Scenes[] = [ - // 1 - { - read: false, - write: false, - async: true, - output: "run again with the --allow-read flag", - }, - { - read: false, - write: false, - async: false, - output: "run again with the --allow-read flag", - }, - // 2 - { - read: true, - write: false, - async: true, - output: "run again with the --allow-write flag", - }, - { - read: true, - write: false, - async: false, - output: "run again with the --allow-write flag", - }, - // 3 - { - read: false, - write: true, - async: true, - output: "run again with the --allow-read flag", - }, - { - read: false, - write: true, - async: false, - output: "run again with the --allow-read flag", - }, - // 4 - { - read: true, - write: true, - async: true, - output: "success", - }, - { - read: true, - write: true, - async: false, - output: "success", - }, -]; -for (const s of scenes) { - let title = `test ${s.async ? "emptyDir" : "emptyDirSync"}`; - title += `("testdata/testfolder") ${s.read ? "with" : "without"}`; - title += ` --allow-read & ${s.write ? "with" : "without"} --allow-write`; - Deno.test(`[fs] emptyDirPermission ${title}`, async function (): Promise< - void - > { - const testfolder = path.join(testdataDir, "testfolder"); - - try { - await Deno.mkdir(testfolder); - - await Deno.writeFile( - path.join(testfolder, "child.txt"), - new TextEncoder().encode("hello world"), - ); - - try { - const args = [Deno.execPath(), "run", "--quiet"]; - - if (s.read) { - args.push("--allow-read"); - } - - if (s.write) { - args.push("--allow-write"); - } - - args.push( - path.join( - testdataDir, - s.async ? "empty_dir.ts" : "empty_dir_sync.ts", - ), - ); - args.push("testfolder"); - - const p = Deno.run({ - stdout: "piped", - cwd: testdataDir, - cmd: args, - }); - - assert(p.stdout); - const output = await p.output(); - p.close(); - assertStringIncludes(new TextDecoder().decode(output), s.output); - } catch (err) { - await Deno.remove(testfolder, { recursive: true }); - throw err; - } - } finally { - // Make the test rerunnable - // Otherwise it would throw an error due to mkdir fail. - await Deno.remove(testfolder, { recursive: true }); - // done - } - }); -} diff --git a/std/fs/ensure_dir.ts b/std/fs/ensure_dir.ts deleted file mode 100644 index 20259a6f7..000000000 --- a/std/fs/ensure_dir.ts +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { getFileInfoType } from "./_util.ts"; - -/** - * Ensures that the directory exists. - * If the directory structure does not exist, it is created. Like mkdir -p. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export async function ensureDir(dir: string): Promise<void> { - try { - const fileInfo = await Deno.lstat(dir); - if (!fileInfo.isDirectory) { - throw new Error( - `Ensure path exists, expected 'dir', got '${ - getFileInfoType(fileInfo) - }'`, - ); - } - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - // if dir not exists. then create it. - await Deno.mkdir(dir, { recursive: true }); - return; - } - throw err; - } -} - -/** - * Ensures that the directory exists. - * If the directory structure does not exist, it is created. Like mkdir -p. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export function ensureDirSync(dir: string): void { - try { - const fileInfo = Deno.lstatSync(dir); - if (!fileInfo.isDirectory) { - throw new Error( - `Ensure path exists, expected 'dir', got '${ - getFileInfoType(fileInfo) - }'`, - ); - } - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - // if dir not exists. then create it. - Deno.mkdirSync(dir, { recursive: true }); - return; - } - throw err; - } -} diff --git a/std/fs/ensure_dir_test.ts b/std/fs/ensure_dir_test.ts deleted file mode 100644 index ad8b75a9f..000000000 --- a/std/fs/ensure_dir_test.ts +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertThrows, assertThrowsAsync } from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { ensureFile, ensureFileSync } from "./ensure_file.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -Deno.test("ensureDirIfItNotExist", async function (): Promise<void> { - const baseDir = path.join(testdataDir, "ensure_dir_not_exist"); - const testDir = path.join(baseDir, "test"); - - await ensureDir(testDir); - - await assertThrowsAsync( - async (): Promise<void> => { - await Deno.stat(testDir).then((): void => { - throw new Error("test dir should exists."); - }); - }, - ); - - await Deno.remove(baseDir, { recursive: true }); -}); - -Deno.test("ensureDirSyncIfItNotExist", function (): void { - const baseDir = path.join(testdataDir, "ensure_dir_sync_not_exist"); - const testDir = path.join(baseDir, "test"); - - ensureDirSync(testDir); - - Deno.statSync(testDir); - - Deno.removeSync(baseDir, { recursive: true }); -}); - -Deno.test("ensureDirIfItExist", async function (): Promise<void> { - const baseDir = path.join(testdataDir, "ensure_dir_exist"); - const testDir = path.join(baseDir, "test"); - - // create test directory - await Deno.mkdir(testDir, { recursive: true }); - - await ensureDir(testDir); - - await assertThrowsAsync( - async (): Promise<void> => { - await Deno.stat(testDir).then((): void => { - throw new Error("test dir should still exists."); - }); - }, - ); - - await Deno.remove(baseDir, { recursive: true }); -}); - -Deno.test("ensureDirSyncIfItExist", function (): void { - const baseDir = path.join(testdataDir, "ensure_dir_sync_exist"); - const testDir = path.join(baseDir, "test"); - - // create test directory - Deno.mkdirSync(testDir, { recursive: true }); - - ensureDirSync(testDir); - - assertThrows((): void => { - Deno.statSync(testDir); - throw new Error("test dir should still exists."); - }); - - Deno.removeSync(baseDir, { recursive: true }); -}); - -Deno.test("ensureDirIfItAsFile", async function (): Promise<void> { - const baseDir = path.join(testdataDir, "ensure_dir_exist_file"); - const testFile = path.join(baseDir, "test"); - - await ensureFile(testFile); - - await assertThrowsAsync( - async (): Promise<void> => { - await ensureDir(testFile); - }, - Error, - `Ensure path exists, expected 'dir', got 'file'`, - ); - - await Deno.remove(baseDir, { recursive: true }); -}); - -Deno.test("ensureDirSyncIfItAsFile", function (): void { - const baseDir = path.join(testdataDir, "ensure_dir_exist_file_async"); - const testFile = path.join(baseDir, "test"); - - ensureFileSync(testFile); - - assertThrows( - (): void => { - ensureDirSync(testFile); - }, - Error, - `Ensure path exists, expected 'dir', got 'file'`, - ); - - Deno.removeSync(baseDir, { recursive: true }); -}); diff --git a/std/fs/ensure_file.ts b/std/fs/ensure_file.ts deleted file mode 100644 index f70732c37..000000000 --- a/std/fs/ensure_file.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { getFileInfoType } from "./_util.ts"; - -/** - * Ensures that the file exists. - * If the file that is requested to be created is in directories that do not - * exist. - * these directories are created. If the file already exists, - * it is NOTMODIFIED. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export async function ensureFile(filePath: string): Promise<void> { - try { - // if file exists - const stat = await Deno.lstat(filePath); - if (!stat.isFile) { - throw new Error( - `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`, - ); - } - } catch (err) { - // if file not exists - if (err instanceof Deno.errors.NotFound) { - // ensure dir exists - await ensureDir(path.dirname(filePath)); - // create file - await Deno.writeFile(filePath, new Uint8Array()); - return; - } - - throw err; - } -} - -/** - * Ensures that the file exists. - * If the file that is requested to be created is in directories that do not - * exist, - * these directories are created. If the file already exists, - * it is NOT MODIFIED. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export function ensureFileSync(filePath: string): void { - try { - // if file exists - const stat = Deno.lstatSync(filePath); - if (!stat.isFile) { - throw new Error( - `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`, - ); - } - } catch (err) { - // if file not exists - if (err instanceof Deno.errors.NotFound) { - // ensure dir exists - ensureDirSync(path.dirname(filePath)); - // create file - Deno.writeFileSync(filePath, new Uint8Array()); - return; - } - throw err; - } -} diff --git a/std/fs/ensure_file_test.ts b/std/fs/ensure_file_test.ts deleted file mode 100644 index e10603426..000000000 --- a/std/fs/ensure_file_test.ts +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertThrows, assertThrowsAsync } from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { ensureFile, ensureFileSync } from "./ensure_file.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -Deno.test("ensureFileIfItNotExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "ensure_file_1"); - const testFile = path.join(testDir, "test.txt"); - - await ensureFile(testFile); - - await assertThrowsAsync( - async (): Promise<void> => { - await Deno.stat(testFile).then((): void => { - throw new Error("test file should exists."); - }); - }, - ); - - await Deno.remove(testDir, { recursive: true }); -}); - -Deno.test("ensureFileSyncIfItNotExist", function (): void { - const testDir = path.join(testdataDir, "ensure_file_2"); - const testFile = path.join(testDir, "test.txt"); - - ensureFileSync(testFile); - - assertThrows((): void => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - }); - - Deno.removeSync(testDir, { recursive: true }); -}); - -Deno.test("ensureFileIfItExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "ensure_file_3"); - const testFile = path.join(testDir, "test.txt"); - - await Deno.mkdir(testDir, { recursive: true }); - await Deno.writeFile(testFile, new Uint8Array()); - - await ensureFile(testFile); - - await assertThrowsAsync( - async (): Promise<void> => { - await Deno.stat(testFile).then((): void => { - throw new Error("test file should exists."); - }); - }, - ); - - await Deno.remove(testDir, { recursive: true }); -}); - -Deno.test("ensureFileSyncIfItExist", function (): void { - const testDir = path.join(testdataDir, "ensure_file_4"); - const testFile = path.join(testDir, "test.txt"); - - Deno.mkdirSync(testDir, { recursive: true }); - Deno.writeFileSync(testFile, new Uint8Array()); - - ensureFileSync(testFile); - - assertThrows((): void => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - }); - - Deno.removeSync(testDir, { recursive: true }); -}); - -Deno.test("ensureFileIfItExistAsDir", async function (): Promise<void> { - const testDir = path.join(testdataDir, "ensure_file_5"); - - await Deno.mkdir(testDir, { recursive: true }); - - await assertThrowsAsync( - async (): Promise<void> => { - await ensureFile(testDir); - }, - Error, - `Ensure path exists, expected 'file', got 'dir'`, - ); - - await Deno.remove(testDir, { recursive: true }); -}); - -Deno.test("ensureFileSyncIfItExistAsDir", function (): void { - const testDir = path.join(testdataDir, "ensure_file_6"); - - Deno.mkdirSync(testDir, { recursive: true }); - - assertThrows( - (): void => { - ensureFileSync(testDir); - }, - Error, - `Ensure path exists, expected 'file', got 'dir'`, - ); - - Deno.removeSync(testDir, { recursive: true }); -}); diff --git a/std/fs/ensure_link.ts b/std/fs/ensure_link.ts deleted file mode 100644 index 56d740ef0..000000000 --- a/std/fs/ensure_link.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { exists, existsSync } from "./exists.ts"; -import { getFileInfoType } from "./_util.ts"; - -/** - * Ensures that the hard link exists. - * If the directory structure does not exist, it is created. - * - * @param src the source file path. Directory hard links are not allowed. - * @param dest the destination link path - */ -export async function ensureLink(src: string, dest: string): Promise<void> { - if (await exists(dest)) { - const destStatInfo = await Deno.lstat(dest); - const destFilePathType = getFileInfoType(destStatInfo); - if (destFilePathType !== "file") { - throw new Error( - `Ensure path exists, expected 'file', got '${destFilePathType}'`, - ); - } - return; - } - - await ensureDir(path.dirname(dest)); - - await Deno.link(src, dest); -} - -/** - * Ensures that the hard link exists. - * If the directory structure does not exist, it is created. - * - * @param src the source file path. Directory hard links are not allowed. - * @param dest the destination link path - */ -export function ensureLinkSync(src: string, dest: string): void { - if (existsSync(dest)) { - const destStatInfo = Deno.lstatSync(dest); - const destFilePathType = getFileInfoType(destStatInfo); - if (destFilePathType !== "file") { - throw new Error( - `Ensure path exists, expected 'file', got '${destFilePathType}'`, - ); - } - return; - } - - ensureDirSync(path.dirname(dest)); - - Deno.linkSync(src, dest); -} diff --git a/std/fs/ensure_link_test.ts b/std/fs/ensure_link_test.ts deleted file mode 100644 index d45b058ca..000000000 --- a/std/fs/ensure_link_test.ts +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -// TODO(axetroy): Add test for Windows once symlink is implemented for Windows. -import { - assertEquals, - assertThrows, - assertThrowsAsync, -} from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { ensureLink, ensureLinkSync } from "./ensure_link.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -Deno.test("ensureLinkIfItNotExist", async function (): Promise<void> { - const srcDir = path.join(testdataDir, "ensure_link_1"); - const destDir = path.join(testdataDir, "ensure_link_1_2"); - const testFile = path.join(srcDir, "test.txt"); - const linkFile = path.join(destDir, "link.txt"); - - await assertThrowsAsync( - async (): Promise<void> => { - await ensureLink(testFile, linkFile); - }, - ); - - await Deno.remove(destDir, { recursive: true }); -}); - -Deno.test("ensureLinkSyncIfItNotExist", function (): void { - const testDir = path.join(testdataDir, "ensure_link_2"); - const testFile = path.join(testDir, "test.txt"); - const linkFile = path.join(testDir, "link.txt"); - - assertThrows((): void => { - ensureLinkSync(testFile, linkFile); - }); - - Deno.removeSync(testDir, { recursive: true }); -}); - -Deno.test("ensureLinkIfItExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "ensure_link_3"); - const testFile = path.join(testDir, "test.txt"); - const linkFile = path.join(testDir, "link.txt"); - - await Deno.mkdir(testDir, { recursive: true }); - await Deno.writeFile(testFile, new Uint8Array()); - - await ensureLink(testFile, linkFile); - - const srcStat = await Deno.lstat(testFile); - const linkStat = await Deno.lstat(linkFile); - - assertEquals(srcStat.isFile, true); - assertEquals(linkStat.isFile, true); - - // har link success. try to change one of them. they should be change both. - - // let's change origin file. - await Deno.writeFile(testFile, new TextEncoder().encode("123")); - - const testFileContent1 = new TextDecoder().decode( - await Deno.readFile(testFile), - ); - const linkFileContent1 = new TextDecoder().decode( - await Deno.readFile(testFile), - ); - - assertEquals(testFileContent1, "123"); - assertEquals(testFileContent1, linkFileContent1); - - // let's change link file. - await Deno.writeFile(testFile, new TextEncoder().encode("abc")); - - const testFileContent2 = new TextDecoder().decode( - await Deno.readFile(testFile), - ); - const linkFileContent2 = new TextDecoder().decode( - await Deno.readFile(testFile), - ); - - assertEquals(testFileContent2, "abc"); - assertEquals(testFileContent2, linkFileContent2); - - await Deno.remove(testDir, { recursive: true }); -}); - -Deno.test("ensureLinkSyncIfItExist", function (): void { - const testDir = path.join(testdataDir, "ensure_link_4"); - const testFile = path.join(testDir, "test.txt"); - const linkFile = path.join(testDir, "link.txt"); - - Deno.mkdirSync(testDir, { recursive: true }); - Deno.writeFileSync(testFile, new Uint8Array()); - - ensureLinkSync(testFile, linkFile); - - const srcStat = Deno.lstatSync(testFile); - - const linkStat = Deno.lstatSync(linkFile); - - assertEquals(srcStat.isFile, true); - assertEquals(linkStat.isFile, true); - - // har link success. try to change one of them. they should be change both. - - // let's change origin file. - Deno.writeFileSync(testFile, new TextEncoder().encode("123")); - - const testFileContent1 = new TextDecoder().decode( - Deno.readFileSync(testFile), - ); - const linkFileContent1 = new TextDecoder().decode( - Deno.readFileSync(testFile), - ); - - assertEquals(testFileContent1, "123"); - assertEquals(testFileContent1, linkFileContent1); - - // let's change link file. - Deno.writeFileSync(testFile, new TextEncoder().encode("abc")); - - const testFileContent2 = new TextDecoder().decode( - Deno.readFileSync(testFile), - ); - const linkFileContent2 = new TextDecoder().decode( - Deno.readFileSync(testFile), - ); - - assertEquals(testFileContent2, "abc"); - assertEquals(testFileContent2, linkFileContent2); - - Deno.removeSync(testDir, { recursive: true }); -}); - -Deno.test("ensureLinkDirectoryIfItExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "ensure_link_origin_3"); - const linkDir = path.join(testdataDir, "ensure_link_link_3"); - const testFile = path.join(testDir, "test.txt"); - - await Deno.mkdir(testDir, { recursive: true }); - await Deno.writeFile(testFile, new Uint8Array()); - - await assertThrowsAsync( - async (): Promise<void> => { - await ensureLink(testDir, linkDir); - }, - // "Operation not permitted (os error 1)" // throw an local matching test - // "Access is denied. (os error 5)" // throw in CI - ); - - Deno.removeSync(testDir, { recursive: true }); -}); - -Deno.test("ensureLinkSyncDirectoryIfItExist", function (): void { - const testDir = path.join(testdataDir, "ensure_link_origin_3"); - const linkDir = path.join(testdataDir, "ensure_link_link_3"); - const testFile = path.join(testDir, "test.txt"); - - Deno.mkdirSync(testDir, { recursive: true }); - Deno.writeFileSync(testFile, new Uint8Array()); - - assertThrows( - (): void => { - ensureLinkSync(testDir, linkDir); - }, - // "Operation not permitted (os error 1)" // throw an local matching test - // "Access is denied. (os error 5)" // throw in CI - ); - - Deno.removeSync(testDir, { recursive: true }); -}); diff --git a/std/fs/ensure_symlink.ts b/std/fs/ensure_symlink.ts deleted file mode 100644 index 63ef6f162..000000000 --- a/std/fs/ensure_symlink.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { exists, existsSync } from "./exists.ts"; -import { getFileInfoType } from "./_util.ts"; -import { isWindows } from "../_util/os.ts"; - -/** - * Ensures that the link exists. - * If the directory structure does not exist, it is created. - * - * @param src the source file path - * @param dest the destination link path - */ -export async function ensureSymlink(src: string, dest: string): Promise<void> { - const srcStatInfo = await Deno.lstat(src); - const srcFilePathType = getFileInfoType(srcStatInfo); - - if (await exists(dest)) { - const destStatInfo = await Deno.lstat(dest); - const destFilePathType = getFileInfoType(destStatInfo); - if (destFilePathType !== "symlink") { - throw new Error( - `Ensure path exists, expected 'symlink', got '${destFilePathType}'`, - ); - } - return; - } - - await ensureDir(path.dirname(dest)); - - const options: Deno.SymlinkOptions | undefined = isWindows - ? { - type: srcFilePathType === "dir" ? "dir" : "file", - } - : undefined; - - await Deno.symlink(src, dest, options); -} - -/** - * Ensures that the link exists. - * If the directory structure does not exist, it is created. - * - * @param src the source file path - * @param dest the destination link path - */ -export function ensureSymlinkSync(src: string, dest: string): void { - const srcStatInfo = Deno.lstatSync(src); - const srcFilePathType = getFileInfoType(srcStatInfo); - - if (existsSync(dest)) { - const destStatInfo = Deno.lstatSync(dest); - const destFilePathType = getFileInfoType(destStatInfo); - if (destFilePathType !== "symlink") { - throw new Error( - `Ensure path exists, expected 'symlink', got '${destFilePathType}'`, - ); - } - return; - } - - ensureDirSync(path.dirname(dest)); - - const options: Deno.SymlinkOptions | undefined = isWindows - ? { - type: srcFilePathType === "dir" ? "dir" : "file", - } - : undefined; - - Deno.symlinkSync(src, dest, options); -} diff --git a/std/fs/ensure_symlink_test.ts b/std/fs/ensure_symlink_test.ts deleted file mode 100644 index 64adfa812..000000000 --- a/std/fs/ensure_symlink_test.ts +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -// TODO(axetroy): Add test for Windows once symlink is implemented for Windows. -import { - assertEquals, - assertThrows, - assertThrowsAsync, -} from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { ensureSymlink, ensureSymlinkSync } from "./ensure_symlink.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -Deno.test("ensureSymlinkIfItNotExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "link_file_1"); - const testFile = path.join(testDir, "test.txt"); - - await assertThrowsAsync( - async (): Promise<void> => { - await ensureSymlink(testFile, path.join(testDir, "test1.txt")); - }, - ); - - await assertThrowsAsync( - async (): Promise<void> => { - await Deno.stat(testFile).then((): void => { - throw new Error("test file should exists."); - }); - }, - ); -}); - -Deno.test("ensureSymlinkSyncIfItNotExist", function (): 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 => { - Deno.statSync(testFile); - throw new Error("test file should exists."); - }); -}); - -Deno.test("ensureSymlinkIfItExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "link_file_3"); - const testFile = path.join(testDir, "test.txt"); - const linkFile = path.join(testDir, "link.txt"); - - await Deno.mkdir(testDir, { recursive: true }); - await Deno.writeFile(testFile, new Uint8Array()); - - await ensureSymlink(testFile, linkFile); - - const srcStat = await Deno.lstat(testFile); - const linkStat = await Deno.lstat(linkFile); - - assertEquals(srcStat.isFile, true); - assertEquals(linkStat.isSymlink, true); - - await Deno.remove(testDir, { recursive: true }); -}); - -Deno.test("ensureSymlinkSyncIfItExist", function (): void { - const testDir = path.join(testdataDir, "link_file_4"); - const testFile = path.join(testDir, "test.txt"); - const linkFile = path.join(testDir, "link.txt"); - - Deno.mkdirSync(testDir, { recursive: true }); - Deno.writeFileSync(testFile, new Uint8Array()); - - ensureSymlinkSync(testFile, linkFile); - - const srcStat = Deno.lstatSync(testFile); - - const linkStat = Deno.lstatSync(linkFile); - - assertEquals(srcStat.isFile, true); - assertEquals(linkStat.isSymlink, true); - - Deno.removeSync(testDir, { recursive: true }); -}); - -Deno.test("ensureSymlinkDirectoryIfItExist", async function (): Promise<void> { - const testDir = path.join(testdataDir, "link_file_origin_3"); - const linkDir = path.join(testdataDir, "link_file_link_3"); - const testFile = path.join(testDir, "test.txt"); - - await Deno.mkdir(testDir, { recursive: true }); - await Deno.writeFile(testFile, new Uint8Array()); - - await ensureSymlink(testDir, linkDir); - - const testDirStat = await Deno.lstat(testDir); - const linkDirStat = await Deno.lstat(linkDir); - const testFileStat = await Deno.lstat(testFile); - - assertEquals(testFileStat.isFile, true); - assertEquals(testDirStat.isDirectory, true); - assertEquals(linkDirStat.isSymlink, true); - - await Deno.remove(linkDir, { recursive: true }); - await Deno.remove(testDir, { recursive: true }); -}); - -Deno.test("ensureSymlinkSyncDirectoryIfItExist", function (): void { - const testDir = path.join(testdataDir, "link_file_origin_3"); - const linkDir = path.join(testdataDir, "link_file_link_3"); - const testFile = path.join(testDir, "test.txt"); - - Deno.mkdirSync(testDir, { recursive: true }); - Deno.writeFileSync(testFile, new Uint8Array()); - - ensureSymlinkSync(testDir, linkDir); - - const testDirStat = Deno.lstatSync(testDir); - const linkDirStat = Deno.lstatSync(linkDir); - const testFileStat = Deno.lstatSync(testFile); - - assertEquals(testFileStat.isFile, true); - assertEquals(testDirStat.isDirectory, true); - assertEquals(linkDirStat.isSymlink, true); - - Deno.removeSync(linkDir, { recursive: true }); - Deno.removeSync(testDir, { recursive: true }); -}); diff --git a/std/fs/eol.ts b/std/fs/eol.ts deleted file mode 100644 index 25797bd71..000000000 --- a/std/fs/eol.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. - -/** EndOfLine character enum */ -export enum EOL { - LF = "\n", - CRLF = "\r\n", -} - -const regDetect = /(?:\r?\n)/g; - -/** - * Detect the EOL character for string input. - * returns null if no newline - */ -export function detect(content: string): EOL | null { - const d = content.match(regDetect); - if (!d || d.length === 0) { - return null; - } - const hasCRLF = d.some((x: string): boolean => x === EOL.CRLF); - - return hasCRLF ? EOL.CRLF : EOL.LF; -} - -/** Format the file to the targeted EOL */ -export function format(content: string, eol: EOL): string { - return content.replace(regDetect, eol); -} diff --git a/std/fs/eol_test.ts b/std/fs/eol_test.ts deleted file mode 100644 index 23e02f4a3..000000000 --- a/std/fs/eol_test.ts +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals } from "../testing/asserts.ts"; -import { detect, EOL, format } from "./eol.ts"; - -const CRLFinput = "deno\r\nis not\r\nnode"; -const Mixedinput = "deno\nis not\r\nnode"; -const Mixedinput2 = "deno\r\nis not\nnode"; -const LFinput = "deno\nis not\nnode"; -const NoNLinput = "deno is not node"; - -Deno.test({ - name: "[EOL] Detect CR LF", - fn(): void { - assertEquals(detect(CRLFinput), EOL.CRLF); - }, -}); - -Deno.test({ - name: "[EOL] Detect LF", - fn(): void { - assertEquals(detect(LFinput), EOL.LF); - }, -}); - -Deno.test({ - name: "[EOL] Detect No New Line", - fn(): void { - assertEquals(detect(NoNLinput), null); - }, -}); - -Deno.test({ - name: "[EOL] Detect Mixed", - fn(): void { - assertEquals(detect(Mixedinput), EOL.CRLF); - assertEquals(detect(Mixedinput2), EOL.CRLF); - }, -}); - -Deno.test({ - name: "[EOL] Format", - fn(): void { - assertEquals(format(CRLFinput, EOL.LF), LFinput); - assertEquals(format(LFinput, EOL.LF), LFinput); - assertEquals(format(LFinput, EOL.CRLF), CRLFinput); - assertEquals(format(CRLFinput, EOL.CRLF), CRLFinput); - assertEquals(format(CRLFinput, EOL.CRLF), CRLFinput); - assertEquals(format(NoNLinput, EOL.CRLF), NoNLinput); - assertEquals(format(Mixedinput, EOL.CRLF), CRLFinput); - assertEquals(format(Mixedinput, EOL.LF), LFinput); - assertEquals(format(Mixedinput2, EOL.CRLF), CRLFinput); - assertEquals(format(Mixedinput2, EOL.LF), LFinput); - }, -}); diff --git a/std/fs/exists.ts b/std/fs/exists.ts deleted file mode 100644 index e98bbcc70..000000000 --- a/std/fs/exists.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -/** - * Test whether or not the given path exists by checking with the file system - */ -export async function exists(filePath: string): Promise<boolean> { - try { - await Deno.lstat(filePath); - return true; - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return false; - } - - throw err; - } -} - -/** - * Test whether or not the given path exists by checking with the file system - */ -export function existsSync(filePath: string): boolean { - try { - Deno.lstatSync(filePath); - return true; - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return false; - } - throw err; - } -} diff --git a/std/fs/exists_test.ts b/std/fs/exists_test.ts deleted file mode 100644 index b3004ec0e..000000000 --- a/std/fs/exists_test.ts +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { assertEquals, assertStringIncludes } from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { exists, existsSync } from "./exists.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -Deno.test("[fs] existsFile", async function (): Promise<void> { - assertEquals( - await exists(path.join(testdataDir, "not_exist_file.ts")), - false, - ); - assertEquals(await existsSync(path.join(testdataDir, "0.ts")), true); -}); - -Deno.test("[fs] existsFileSync", function (): void { - assertEquals(existsSync(path.join(testdataDir, "not_exist_file.ts")), false); - assertEquals(existsSync(path.join(testdataDir, "0.ts")), true); -}); - -Deno.test("[fs] existsDirectory", async function (): Promise<void> { - assertEquals( - await exists(path.join(testdataDir, "not_exist_directory")), - false, - ); - assertEquals(existsSync(testdataDir), true); -}); - -Deno.test("[fs] existsDirectorySync", function (): void { - assertEquals( - existsSync(path.join(testdataDir, "not_exist_directory")), - false, - ); - assertEquals(existsSync(testdataDir), true); -}); - -Deno.test("[fs] existsLinkSync", function (): void { - // TODO(axetroy): generate link file use Deno api instead of set a link file - // in repository - assertEquals(existsSync(path.join(testdataDir, "0-link")), true); -}); - -Deno.test("[fs] existsLink", async function (): Promise<void> { - // TODO(axetroy): generate link file use Deno api instead of set a link file - // in repository - assertEquals(await exists(path.join(testdataDir, "0-link")), true); -}); - -interface Scenes { - read: boolean; // --allow-read - async: boolean; - output: string; - file: string; // target file to run -} - -const scenes: Scenes[] = [ - // 1 - { - read: false, - async: true, - output: "run again with the --allow-read flag", - file: "0.ts", - }, - { - read: false, - async: false, - output: "run again with the --allow-read flag", - file: "0.ts", - }, - // 2 - { - read: true, - async: true, - output: "exist", - file: "0.ts", - }, - { - read: true, - async: false, - output: "exist", - file: "0.ts", - }, - // 3 - { - read: false, - async: true, - output: "run again with the --allow-read flag", - file: "no_exist_file_for_test.ts", - }, - { - read: false, - async: false, - output: "run again with the --allow-read flag", - file: "no_exist_file_for_test.ts", - }, - // 4 - { - read: true, - async: true, - output: "not exist", - file: "no_exist_file_for_test.ts", - }, - { - read: true, - async: false, - output: "not exist", - file: "no_exist_file_for_test.ts", - }, -]; - -for (const s of scenes) { - let title = `test ${s.async ? "exists" : "existsSync"}("testdata/${s.file}")`; - title += ` ${s.read ? "with" : "without"} --allow-read`; - Deno.test(`[fs] existsPermission ${title}`, async function (): Promise<void> { - const args = [Deno.execPath(), "run", "--quiet"]; - - if (s.read) { - args.push("--allow-read"); - } - - args.push(path.join(testdataDir, s.async ? "exists.ts" : "exists_sync.ts")); - args.push(s.file); - - const p = Deno.run({ - stdout: "piped", - cwd: testdataDir, - cmd: args, - }); - - const output = await p.output(); - p.close(); - assertStringIncludes(new TextDecoder().decode(output), s.output); - }); - // done -} diff --git a/std/fs/expand_glob.ts b/std/fs/expand_glob.ts deleted file mode 100644 index ec0f560d8..000000000 --- a/std/fs/expand_glob.ts +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - GlobOptions, - globToRegExp, - isAbsolute, - isGlob, - joinGlobs, - normalize, - SEP_PATTERN, -} from "../path/mod.ts"; -import { - _createWalkEntry, - _createWalkEntrySync, - walk, - WalkEntry, - walkSync, -} from "./walk.ts"; -import { assert } from "../_util/assert.ts"; -import { isWindows } from "../_util/os.ts"; - -export interface ExpandGlobOptions extends Omit<GlobOptions, "os"> { - root?: string; - exclude?: string[]; - includeDirs?: boolean; -} - -interface SplitPath { - segments: string[]; - isAbsolute: boolean; - hasTrailingSep: boolean; - // Defined for any absolute Windows path. - winRoot?: string; -} - -function split(path: string): SplitPath { - const s = SEP_PATTERN.source; - const segments = path - .replace(new RegExp(`^${s}|${s}$`, "g"), "") - .split(SEP_PATTERN); - const isAbsolute_ = isAbsolute(path); - return { - segments, - isAbsolute: isAbsolute_, - hasTrailingSep: !!path.match(new RegExp(`${s}$`)), - winRoot: isWindows && isAbsolute_ ? segments.shift() : undefined, - }; -} - -function throwUnlessNotFound(error: Error): void { - if (!(error instanceof Deno.errors.NotFound)) { - throw error; - } -} - -function comparePath(a: WalkEntry, b: WalkEntry): number { - if (a.path < b.path) return -1; - if (a.path > b.path) return 1; - return 0; -} - -/** Expand the glob string from the specified `root` directory and yield each - * result as a `WalkEntry` object. - * - * See [`globToRegExp()`](../path/glob.ts#globToRegExp) for details on supported - * syntax. - * - * Example: - * - * for await (const file of expandGlob("**\/*.ts")) { - * console.log(file); - * } - */ -export async function* expandGlob( - glob: string, - { - root = Deno.cwd(), - exclude = [], - includeDirs = true, - extended = false, - globstar = false, - }: ExpandGlobOptions = {}, -): AsyncIterableIterator<WalkEntry> { - const globOptions: GlobOptions = { extended, globstar }; - const absRoot = isAbsolute(root) - ? normalize(root) - : joinGlobs([Deno.cwd(), root], globOptions); - const resolveFromRoot = (path: string): string => - isAbsolute(path) - ? normalize(path) - : joinGlobs([absRoot, path], globOptions); - const excludePatterns = exclude - .map(resolveFromRoot) - .map((s: string): RegExp => globToRegExp(s, globOptions)); - const shouldInclude = (path: string): boolean => - !excludePatterns.some((p: RegExp): boolean => !!path.match(p)); - const { segments, hasTrailingSep, winRoot } = split(resolveFromRoot(glob)); - - let fixedRoot = winRoot != undefined ? winRoot : "/"; - while (segments.length > 0 && !isGlob(segments[0])) { - const seg = segments.shift(); - assert(seg != null); - fixedRoot = joinGlobs([fixedRoot, seg], globOptions); - } - - let fixedRootInfo: WalkEntry; - try { - fixedRootInfo = await _createWalkEntry(fixedRoot); - } catch (error) { - return throwUnlessNotFound(error); - } - - async function* advanceMatch( - walkInfo: WalkEntry, - globSegment: string, - ): AsyncIterableIterator<WalkEntry> { - if (!walkInfo.isDirectory) { - return; - } else if (globSegment == "..") { - const parentPath = joinGlobs([walkInfo.path, ".."], globOptions); - try { - if (shouldInclude(parentPath)) { - return yield await _createWalkEntry(parentPath); - } - } catch (error) { - throwUnlessNotFound(error); - } - return; - } else if (globSegment == "**") { - return yield* walk(walkInfo.path, { - includeFiles: false, - skip: excludePatterns, - }); - } - yield* walk(walkInfo.path, { - maxDepth: 1, - match: [ - globToRegExp( - joinGlobs([walkInfo.path, globSegment], globOptions), - globOptions, - ), - ], - skip: excludePatterns, - }); - } - - let currentMatches: WalkEntry[] = [fixedRootInfo]; - for (const segment of segments) { - // Advancing the list of current matches may introduce duplicates, so we - // pass everything through this Map. - const nextMatchMap: Map<string, WalkEntry> = new Map(); - for (const currentMatch of currentMatches) { - for await (const nextMatch of advanceMatch(currentMatch, segment)) { - nextMatchMap.set(nextMatch.path, nextMatch); - } - } - currentMatches = [...nextMatchMap.values()].sort(comparePath); - } - if (hasTrailingSep) { - currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => entry.isDirectory, - ); - } - if (!includeDirs) { - currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => !entry.isDirectory, - ); - } - yield* currentMatches; -} - -/** Synchronous version of `expandGlob()`. - * - * Example: - * - * for (const file of expandGlobSync("**\/*.ts")) { - * console.log(file); - * } - */ -export function* expandGlobSync( - glob: string, - { - root = Deno.cwd(), - exclude = [], - includeDirs = true, - extended = false, - globstar = false, - }: ExpandGlobOptions = {}, -): IterableIterator<WalkEntry> { - const globOptions: GlobOptions = { extended, globstar }; - const absRoot = isAbsolute(root) - ? normalize(root) - : joinGlobs([Deno.cwd(), root], globOptions); - const resolveFromRoot = (path: string): string => - isAbsolute(path) - ? normalize(path) - : joinGlobs([absRoot, path], globOptions); - const excludePatterns = exclude - .map(resolveFromRoot) - .map((s: string): RegExp => globToRegExp(s, globOptions)); - const shouldInclude = (path: string): boolean => - !excludePatterns.some((p: RegExp): boolean => !!path.match(p)); - const { segments, hasTrailingSep, winRoot } = split(resolveFromRoot(glob)); - - let fixedRoot = winRoot != undefined ? winRoot : "/"; - while (segments.length > 0 && !isGlob(segments[0])) { - const seg = segments.shift(); - assert(seg != null); - fixedRoot = joinGlobs([fixedRoot, seg], globOptions); - } - - let fixedRootInfo: WalkEntry; - try { - fixedRootInfo = _createWalkEntrySync(fixedRoot); - } catch (error) { - return throwUnlessNotFound(error); - } - - function* advanceMatch( - walkInfo: WalkEntry, - globSegment: string, - ): IterableIterator<WalkEntry> { - if (!walkInfo.isDirectory) { - return; - } else if (globSegment == "..") { - const parentPath = joinGlobs([walkInfo.path, ".."], globOptions); - try { - if (shouldInclude(parentPath)) { - return yield _createWalkEntrySync(parentPath); - } - } catch (error) { - throwUnlessNotFound(error); - } - return; - } else if (globSegment == "**") { - return yield* walkSync(walkInfo.path, { - includeFiles: false, - skip: excludePatterns, - }); - } - yield* walkSync(walkInfo.path, { - maxDepth: 1, - match: [ - globToRegExp( - joinGlobs([walkInfo.path, globSegment], globOptions), - globOptions, - ), - ], - skip: excludePatterns, - }); - } - - let currentMatches: WalkEntry[] = [fixedRootInfo]; - for (const segment of segments) { - // Advancing the list of current matches may introduce duplicates, so we - // pass everything through this Map. - const nextMatchMap: Map<string, WalkEntry> = new Map(); - for (const currentMatch of currentMatches) { - for (const nextMatch of advanceMatch(currentMatch, segment)) { - nextMatchMap.set(nextMatch.path, nextMatch); - } - } - currentMatches = [...nextMatchMap.values()].sort(comparePath); - } - if (hasTrailingSep) { - currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => entry.isDirectory, - ); - } - if (!includeDirs) { - currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => !entry.isDirectory, - ); - } - yield* currentMatches; -} diff --git a/std/fs/expand_glob_test.ts b/std/fs/expand_glob_test.ts deleted file mode 100644 index da9e89e6b..000000000 --- a/std/fs/expand_glob_test.ts +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { decode } from "../encoding/utf8.ts"; -import { - assert, - assertEquals, - assertStringIncludes, -} from "../testing/asserts.ts"; -import { - fromFileUrl, - join, - joinGlobs, - normalize, - relative, -} from "../path/mod.ts"; -import { - expandGlob, - ExpandGlobOptions, - expandGlobSync, -} from "./expand_glob.ts"; - -async function expandGlobArray( - globString: string, - options: ExpandGlobOptions, -): Promise<string[]> { - const paths: string[] = []; - for await (const { path } of expandGlob(globString, options)) { - paths.push(path); - } - paths.sort(); - const pathsSync = [...expandGlobSync(globString, options)].map( - ({ path }): string => path, - ); - pathsSync.sort(); - assertEquals(paths, pathsSync); - const root = normalize(options.root || Deno.cwd()); - for (const path of paths) { - assert(path.startsWith(root)); - } - const relativePaths = paths.map( - (path: string): string => relative(root, path) || ".", - ); - relativePaths.sort(); - return relativePaths; -} - -const EG_OPTIONS: ExpandGlobOptions = { - root: fromFileUrl(new URL(join("testdata", "glob"), import.meta.url)), - includeDirs: true, - extended: false, - globstar: false, -}; - -Deno.test("expandGlobWildcard", async function (): Promise<void> { - const options = EG_OPTIONS; - assertEquals(await expandGlobArray("*", options), [ - "abc", - "abcdef", - "abcdefghi", - "subdir", - ]); -}); - -Deno.test("expandGlobTrailingSeparator", async function (): Promise<void> { - const options = EG_OPTIONS; - assertEquals(await expandGlobArray("*/", options), ["subdir"]); -}); - -Deno.test("expandGlobParent", async function (): Promise<void> { - const options = EG_OPTIONS; - assertEquals(await expandGlobArray("subdir/../*", options), [ - "abc", - "abcdef", - "abcdefghi", - "subdir", - ]); -}); - -Deno.test("expandGlobExt", async function (): Promise<void> { - const options = { ...EG_OPTIONS, extended: true }; - assertEquals(await expandGlobArray("abc?(def|ghi)", options), [ - "abc", - "abcdef", - ]); - assertEquals(await expandGlobArray("abc*(def|ghi)", options), [ - "abc", - "abcdef", - "abcdefghi", - ]); - assertEquals(await expandGlobArray("abc+(def|ghi)", options), [ - "abcdef", - "abcdefghi", - ]); - assertEquals(await expandGlobArray("abc@(def|ghi)", options), ["abcdef"]); - assertEquals(await expandGlobArray("abc{def,ghi}", options), ["abcdef"]); - assertEquals(await expandGlobArray("abc!(def|ghi)", options), ["abc"]); -}); - -Deno.test("expandGlobGlobstar", async function (): Promise<void> { - const options = { ...EG_OPTIONS, globstar: true }; - assertEquals( - await expandGlobArray(joinGlobs(["**", "abc"], options), options), - ["abc", join("subdir", "abc")], - ); -}); - -Deno.test("expandGlobGlobstarParent", async function (): Promise<void> { - const options = { ...EG_OPTIONS, globstar: true }; - assertEquals( - await expandGlobArray(joinGlobs(["subdir", "**", ".."], options), options), - ["."], - ); -}); - -Deno.test("expandGlobIncludeDirs", async function (): Promise<void> { - const options = { ...EG_OPTIONS, includeDirs: false }; - assertEquals(await expandGlobArray("subdir", options), []); -}); - -Deno.test("expandGlobPermError", async function (): Promise<void> { - const exampleUrl = new URL("testdata/expand_wildcard.js", import.meta.url); - const p = Deno.run({ - cmd: [ - Deno.execPath(), - "run", - "--quiet", - "--unstable", - exampleUrl.toString(), - ], - stdin: "null", - stdout: "piped", - stderr: "piped", - }); - assertEquals(await p.status(), { code: 1, success: false }); - assertEquals(decode(await p.output()), ""); - assertStringIncludes( - decode(await p.stderrOutput()), - "Uncaught PermissionDenied", - ); - p.close(); -}); diff --git a/std/fs/mod.ts b/std/fs/mod.ts deleted file mode 100644 index 98dd3daa5..000000000 --- a/std/fs/mod.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -export * from "./empty_dir.ts"; -export * from "./ensure_dir.ts"; -export * from "./ensure_file.ts"; -export * from "./ensure_link.ts"; -export * from "./ensure_symlink.ts"; -export * from "./exists.ts"; -export * from "./expand_glob.ts"; -export * from "./move.ts"; -export * from "./copy.ts"; -export * from "./walk.ts"; -export * from "./eol.ts"; diff --git a/std/fs/move.ts b/std/fs/move.ts deleted file mode 100644 index 2e34e7387..000000000 --- a/std/fs/move.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { exists, existsSync } from "./exists.ts"; -import { isSubdir } from "./_util.ts"; - -interface MoveOptions { - overwrite?: boolean; -} - -/** Moves a file or directory */ -export async function move( - src: string, - dest: string, - { overwrite = false }: MoveOptions = {}, -): Promise<void> { - const srcStat = await Deno.stat(src); - - if (srcStat.isDirectory && isSubdir(src, dest)) { - throw new Error( - `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`, - ); - } - - if (overwrite) { - if (await exists(dest)) { - await Deno.remove(dest, { recursive: true }); - } - } else { - if (await exists(dest)) { - throw new Error("dest already exists."); - } - } - - await Deno.rename(src, dest); - - return; -} - -/** Moves a file or directory synchronously */ -export function moveSync( - src: string, - dest: string, - { overwrite = false }: MoveOptions = {}, -): void { - const srcStat = Deno.statSync(src); - - if (srcStat.isDirectory && isSubdir(src, dest)) { - throw new Error( - `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`, - ); - } - - if (overwrite) { - if (existsSync(dest)) { - Deno.removeSync(dest, { recursive: true }); - } - } else { - if (existsSync(dest)) { - throw new Error("dest already exists."); - } - } - - Deno.renameSync(src, dest); -} diff --git a/std/fs/move_test.ts b/std/fs/move_test.ts deleted file mode 100644 index 048193755..000000000 --- a/std/fs/move_test.ts +++ /dev/null @@ -1,375 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { - assertEquals, - assertThrows, - assertThrowsAsync, -} from "../testing/asserts.ts"; -import * as path from "../path/mod.ts"; -import { move, moveSync } from "./move.ts"; -import { ensureFile, ensureFileSync } from "./ensure_file.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { exists, existsSync } from "./exists.ts"; - -const moduleDir = path.dirname(path.fromFileUrl(import.meta.url)); -const testdataDir = path.resolve(moduleDir, "testdata"); - -Deno.test("moveDirectoryIfSrcNotExists", async function (): Promise<void> { - const srcDir = path.join(testdataDir, "move_test_src_1"); - const destDir = path.join(testdataDir, "move_test_dest_1"); - // if src directory not exist - await assertThrowsAsync( - async (): Promise<void> => { - await move(srcDir, destDir); - }, - ); -}); - -Deno.test("moveDirectoryIfDestNotExists", async function (): Promise<void> { - const srcDir = path.join(testdataDir, "move_test_src_2"); - const destDir = path.join(testdataDir, "move_test_dest_2"); - - await Deno.mkdir(srcDir, { recursive: true }); - - // if dest directory not exist - await assertThrowsAsync( - async (): Promise<void> => { - await move(srcDir, destDir); - throw new Error("should not throw error"); - }, - Error, - "should not throw error", - ); - - await Deno.remove(destDir); -}); - -Deno.test( - "moveDirectoryIfDestNotExistsAndOverwrite", - async function (): Promise<void> { - const srcDir = path.join(testdataDir, "move_test_src_2"); - const destDir = path.join(testdataDir, "move_test_dest_2"); - - await Deno.mkdir(srcDir, { recursive: true }); - - // if dest directory not exist - await assertThrowsAsync( - async (): Promise<void> => { - await move(srcDir, destDir, { overwrite: true }); - throw new Error("should not throw error"); - }, - Error, - "should not throw error", - ); - - await Deno.remove(destDir); - }, -); - -Deno.test("moveFileIfSrcNotExists", async function (): Promise<void> { - const srcFile = path.join(testdataDir, "move_test_src_3", "test.txt"); - const destFile = path.join(testdataDir, "move_test_dest_3", "test.txt"); - - // if src directory not exist - await assertThrowsAsync( - async (): Promise<void> => { - await move(srcFile, destFile); - }, - ); -}); - -Deno.test("moveFileIfDestExists", async function (): Promise<void> { - const srcDir = path.join(testdataDir, "move_test_src_4"); - const destDir = path.join(testdataDir, "move_test_dest_4"); - const srcFile = path.join(srcDir, "test.txt"); - const destFile = path.join(destDir, "test.txt"); - const srcContent = new TextEncoder().encode("src"); - const destContent = new TextEncoder().encode("dest"); - - // make sure files exists - await Promise.all([ensureFile(srcFile), ensureFile(destFile)]); - - // write file content - await Promise.all([ - Deno.writeFile(srcFile, srcContent), - Deno.writeFile(destFile, destContent), - ]); - - // make sure the test file have been created - assertEquals(new TextDecoder().decode(await Deno.readFile(srcFile)), "src"); - assertEquals(new TextDecoder().decode(await Deno.readFile(destFile)), "dest"); - - // move it without override - await assertThrowsAsync( - async (): Promise<void> => { - await move(srcFile, destFile); - }, - Error, - "dest already exists", - ); - - // move again with overwrite - await assertThrowsAsync( - async (): Promise<void> => { - await move(srcFile, destFile, { overwrite: true }); - throw new Error("should not throw error"); - }, - Error, - "should not throw error", - ); - - assertEquals(await exists(srcFile), false); - assertEquals(new TextDecoder().decode(await Deno.readFile(destFile)), "src"); - - // clean up - await Promise.all([ - Deno.remove(srcDir, { recursive: true }), - Deno.remove(destDir, { recursive: true }), - ]); -}); - -Deno.test("moveDirectory", async function (): Promise<void> { - const srcDir = path.join(testdataDir, "move_test_src_5"); - const destDir = path.join(testdataDir, "move_test_dest_5"); - const srcFile = path.join(srcDir, "test.txt"); - const destFile = path.join(destDir, "test.txt"); - const srcContent = new TextEncoder().encode("src"); - - await Deno.mkdir(srcDir, { recursive: true }); - assertEquals(await exists(srcDir), true); - await Deno.writeFile(srcFile, srcContent); - - await move(srcDir, destDir); - - assertEquals(await exists(srcDir), false); - assertEquals(await exists(destDir), true); - assertEquals(await exists(destFile), true); - - const destFileContent = new TextDecoder().decode( - await Deno.readFile(destFile), - ); - assertEquals(destFileContent, "src"); - - await Deno.remove(destDir, { recursive: true }); -}); - -Deno.test( - "moveIfSrcAndDestDirectoryExistsAndOverwrite", - async function (): Promise<void> { - const srcDir = path.join(testdataDir, "move_test_src_6"); - const destDir = path.join(testdataDir, "move_test_dest_6"); - const srcFile = path.join(srcDir, "test.txt"); - const destFile = path.join(destDir, "test.txt"); - const srcContent = new TextEncoder().encode("src"); - const destContent = new TextEncoder().encode("dest"); - - await Promise.all([ - Deno.mkdir(srcDir, { recursive: true }), - Deno.mkdir(destDir, { recursive: true }), - ]); - assertEquals(await exists(srcDir), true); - assertEquals(await exists(destDir), true); - await Promise.all([ - Deno.writeFile(srcFile, srcContent), - Deno.writeFile(destFile, destContent), - ]); - - await move(srcDir, destDir, { overwrite: true }); - - assertEquals(await exists(srcDir), false); - assertEquals(await exists(destDir), true); - assertEquals(await exists(destFile), true); - - const destFileContent = new TextDecoder().decode( - await Deno.readFile(destFile), - ); - assertEquals(destFileContent, "src"); - - await Deno.remove(destDir, { recursive: true }); - }, -); - -Deno.test("moveIntoSubDir", async function (): Promise<void> { - const srcDir = path.join(testdataDir, "move_test_src_7"); - const destDir = path.join(srcDir, "nest"); - - await ensureDir(destDir); - - await assertThrowsAsync( - async (): Promise<void> => { - await move(srcDir, destDir); - }, - Error, - `Cannot move '${srcDir}' to a subdirectory of itself, '${destDir}'.`, - ); - await Deno.remove(srcDir, { recursive: true }); -}); - -Deno.test("moveSyncDirectoryIfSrcNotExists", function (): 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); - }); -}); - -Deno.test("moveSyncDirectoryIfDestNotExists", function (): void { - const srcDir = path.join(testdataDir, "move_sync_test_src_2"); - const destDir = path.join(testdataDir, "move_sync_test_dest_2"); - - Deno.mkdirSync(srcDir, { recursive: true }); - - // if dest directory not exist - assertThrows( - (): void => { - moveSync(srcDir, destDir); - throw new Error("should not throw error"); - }, - Error, - "should not throw error", - ); - - Deno.removeSync(destDir); -}); - -Deno.test("moveSyncDirectoryIfDestNotExistsAndOverwrite", function (): void { - const srcDir = path.join(testdataDir, "move_sync_test_src_2"); - const destDir = path.join(testdataDir, "move_sync_test_dest_2"); - - Deno.mkdirSync(srcDir, { recursive: true }); - - // if dest directory not exist width overwrite - assertThrows( - (): void => { - moveSync(srcDir, destDir, { overwrite: true }); - throw new Error("should not throw error"); - }, - Error, - "should not throw error", - ); - - Deno.removeSync(destDir); -}); - -Deno.test("moveSyncFileIfSrcNotExists", function (): void { - const srcFile = path.join(testdataDir, "move_sync_test_src_3", "test.txt"); - const destFile = path.join(testdataDir, "move_sync_test_dest_3", "test.txt"); - - // if src directory not exist - assertThrows((): void => { - moveSync(srcFile, destFile); - }); -}); - -Deno.test("moveSyncFileIfDestExists", function (): void { - const srcDir = path.join(testdataDir, "move_sync_test_src_4"); - const destDir = path.join(testdataDir, "move_sync_test_dest_4"); - const srcFile = path.join(srcDir, "test.txt"); - const destFile = path.join(destDir, "test.txt"); - const srcContent = new TextEncoder().encode("src"); - const destContent = new TextEncoder().encode("dest"); - - // make sure files exists - ensureFileSync(srcFile); - ensureFileSync(destFile); - - // write file content - Deno.writeFileSync(srcFile, srcContent); - Deno.writeFileSync(destFile, destContent); - - // make sure the test file have been created - assertEquals(new TextDecoder().decode(Deno.readFileSync(srcFile)), "src"); - assertEquals(new TextDecoder().decode(Deno.readFileSync(destFile)), "dest"); - - // move it without override - assertThrows( - (): void => { - moveSync(srcFile, destFile); - }, - Error, - "dest already exists", - ); - - // move again with overwrite - assertThrows( - (): void => { - moveSync(srcFile, destFile, { overwrite: true }); - throw new Error("should not throw error"); - }, - Error, - "should not throw error", - ); - - assertEquals(existsSync(srcFile), false); - assertEquals(new TextDecoder().decode(Deno.readFileSync(destFile)), "src"); - - // clean up - Deno.removeSync(srcDir, { recursive: true }); - Deno.removeSync(destDir, { recursive: true }); -}); - -Deno.test("moveSyncDirectory", function (): void { - const srcDir = path.join(testdataDir, "move_sync_test_src_5"); - const destDir = path.join(testdataDir, "move_sync_test_dest_5"); - const srcFile = path.join(srcDir, "test.txt"); - const destFile = path.join(destDir, "test.txt"); - const srcContent = new TextEncoder().encode("src"); - - Deno.mkdirSync(srcDir, { recursive: true }); - assertEquals(existsSync(srcDir), true); - Deno.writeFileSync(srcFile, srcContent); - - moveSync(srcDir, destDir); - - assertEquals(existsSync(srcDir), false); - assertEquals(existsSync(destDir), true); - assertEquals(existsSync(destFile), true); - - const destFileContent = new TextDecoder().decode(Deno.readFileSync(destFile)); - assertEquals(destFileContent, "src"); - - Deno.removeSync(destDir, { recursive: true }); -}); - -Deno.test("moveSyncIfSrcAndDestDirectoryExistsAndOverwrite", function (): void { - const srcDir = path.join(testdataDir, "move_sync_test_src_6"); - const destDir = path.join(testdataDir, "move_sync_test_dest_6"); - const srcFile = path.join(srcDir, "test.txt"); - const destFile = path.join(destDir, "test.txt"); - const srcContent = new TextEncoder().encode("src"); - const destContent = new TextEncoder().encode("dest"); - - Deno.mkdirSync(srcDir, { recursive: true }); - Deno.mkdirSync(destDir, { recursive: true }); - assertEquals(existsSync(srcDir), true); - assertEquals(existsSync(destDir), true); - Deno.writeFileSync(srcFile, srcContent); - Deno.writeFileSync(destFile, destContent); - - moveSync(srcDir, destDir, { overwrite: true }); - - assertEquals(existsSync(srcDir), false); - assertEquals(existsSync(destDir), true); - assertEquals(existsSync(destFile), true); - - const destFileContent = new TextDecoder().decode(Deno.readFileSync(destFile)); - assertEquals(destFileContent, "src"); - - Deno.removeSync(destDir, { recursive: true }); -}); - -Deno.test("moveSyncIntoSubDir", function (): void { - const srcDir = path.join(testdataDir, "move_sync_test_src_7"); - const destDir = path.join(srcDir, "nest"); - - ensureDirSync(destDir); - - assertThrows( - (): void => { - moveSync(srcDir, destDir); - }, - Error, - `Cannot move '${srcDir}' to a subdirectory of itself, '${destDir}'.`, - ); - Deno.removeSync(srcDir, { recursive: true }); -}); diff --git a/std/fs/test.ts b/std/fs/test.ts deleted file mode 100644 index 590417055..000000000 --- a/std/fs/test.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import "./mod.ts"; diff --git a/std/fs/testdata/0-link b/std/fs/testdata/0-link deleted file mode 120000 index 937f1e899..000000000 --- a/std/fs/testdata/0-link +++ /dev/null @@ -1 +0,0 @@ -0.ts
\ No newline at end of file diff --git a/std/fs/testdata/0.ts b/std/fs/testdata/0.ts deleted file mode 100644 index e69de29bb..000000000 --- a/std/fs/testdata/0.ts +++ /dev/null diff --git a/std/fs/testdata/copy_dir/0.txt b/std/fs/testdata/copy_dir/0.txt deleted file mode 100644 index f3a34851d..000000000 --- a/std/fs/testdata/copy_dir/0.txt +++ /dev/null @@ -1 +0,0 @@ -text
\ No newline at end of file diff --git a/std/fs/testdata/copy_dir/nest/0.txt b/std/fs/testdata/copy_dir/nest/0.txt deleted file mode 100644 index cd1b98cb3..000000000 --- a/std/fs/testdata/copy_dir/nest/0.txt +++ /dev/null @@ -1 +0,0 @@ -nest
\ No newline at end of file diff --git a/std/fs/testdata/copy_dir_link_file/0.txt b/std/fs/testdata/copy_dir_link_file/0.txt deleted file mode 120000 index 63413ea1c..000000000 --- a/std/fs/testdata/copy_dir_link_file/0.txt +++ /dev/null @@ -1 +0,0 @@ -./fs/testdata/copy_dir/0.txt
\ No newline at end of file diff --git a/std/fs/testdata/copy_file.txt b/std/fs/testdata/copy_file.txt deleted file mode 100644 index 84c22fd8a..000000000 --- a/std/fs/testdata/copy_file.txt +++ /dev/null @@ -1 +0,0 @@ -txt
\ No newline at end of file diff --git a/std/fs/testdata/empty_dir.ts b/std/fs/testdata/empty_dir.ts deleted file mode 100644 index f8fcc1ceb..000000000 --- a/std/fs/testdata/empty_dir.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { emptyDir } from "../empty_dir.ts"; - -emptyDir(Deno.args[0]) - .then(() => { - Deno.stdout.write(new TextEncoder().encode("success")); - }) - .catch((err) => { - Deno.stdout.write(new TextEncoder().encode(err.message)); - }); diff --git a/std/fs/testdata/empty_dir_sync.ts b/std/fs/testdata/empty_dir_sync.ts deleted file mode 100644 index 0bef81e91..000000000 --- a/std/fs/testdata/empty_dir_sync.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { emptyDirSync } from "../empty_dir.ts"; - -try { - emptyDirSync(Deno.args[0]) - Deno.stdout.write(new TextEncoder().encode("success")) -} catch (err) { - Deno.stdout.write(new TextEncoder().encode(err.message)) -}
\ No newline at end of file diff --git a/std/fs/testdata/exists.ts b/std/fs/testdata/exists.ts deleted file mode 100644 index 93812a703..000000000 --- a/std/fs/testdata/exists.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { exists } from "../exists.ts"; - -exists(Deno.args[0]) - .then(isExist => { - Deno.stdout.write(new TextEncoder().encode(isExist ? 'exist' :'not exist')) - }) - .catch((err) => { - Deno.stdout.write(new TextEncoder().encode(err.message)) - }) - diff --git a/std/fs/testdata/exists_sync.ts b/std/fs/testdata/exists_sync.ts deleted file mode 100644 index 8cc51e9f8..000000000 --- a/std/fs/testdata/exists_sync.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { existsSync } from "../exists.ts"; - -try { - const isExist = existsSync(Deno.args[0]); - Deno.stdout.write(new TextEncoder().encode(isExist ? "exist" : "not exist")); -} catch (err) { - Deno.stdout.write(new TextEncoder().encode(err.message)); -} diff --git a/std/fs/testdata/expand_wildcard.js b/std/fs/testdata/expand_wildcard.js deleted file mode 100644 index a30a17536..000000000 --- a/std/fs/testdata/expand_wildcard.js +++ /dev/null @@ -1,6 +0,0 @@ -import { expandGlob } from "../expand_glob.ts"; - -const glob = new URL("*", import.meta.url).pathname; -for await (const { filename } of expandGlob(glob)) { - console.log(filename); -} diff --git a/std/fs/testdata/glob/abc b/std/fs/testdata/glob/abc deleted file mode 100644 index e69de29bb..000000000 --- a/std/fs/testdata/glob/abc +++ /dev/null diff --git a/std/fs/testdata/glob/abcdef b/std/fs/testdata/glob/abcdef deleted file mode 100644 index e69de29bb..000000000 --- a/std/fs/testdata/glob/abcdef +++ /dev/null diff --git a/std/fs/testdata/glob/abcdefghi b/std/fs/testdata/glob/abcdefghi deleted file mode 100644 index e69de29bb..000000000 --- a/std/fs/testdata/glob/abcdefghi +++ /dev/null diff --git a/std/fs/testdata/glob/subdir/abc b/std/fs/testdata/glob/subdir/abc deleted file mode 100644 index e69de29bb..000000000 --- a/std/fs/testdata/glob/subdir/abc +++ /dev/null diff --git a/std/fs/testdata/json_empty.json b/std/fs/testdata/json_empty.json deleted file mode 100644 index e69de29bb..000000000 --- a/std/fs/testdata/json_empty.json +++ /dev/null diff --git a/std/fs/testdata/json_invalid.json b/std/fs/testdata/json_invalid.json deleted file mode 100644 index dd9f98ff0..000000000 --- a/std/fs/testdata/json_invalid.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - [ - "here is a invalid json file" - ] -}
\ No newline at end of file diff --git a/std/fs/testdata/json_valid_array.json b/std/fs/testdata/json_valid_array.json deleted file mode 100644 index 904968e15..000000000 --- a/std/fs/testdata/json_valid_array.json +++ /dev/null @@ -1,5 +0,0 @@ -[ - "1", - "2", - "3" -]
\ No newline at end of file diff --git a/std/fs/testdata/json_valid_obj.json b/std/fs/testdata/json_valid_obj.json deleted file mode 100644 index 88b3d7123..000000000 --- a/std/fs/testdata/json_valid_obj.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "key1": "value1", - "key2": "value2" -}
\ No newline at end of file diff --git a/std/fs/walk.ts b/std/fs/walk.ts deleted file mode 100644 index 4ce564435..000000000 --- a/std/fs/walk.ts +++ /dev/null @@ -1,188 +0,0 @@ -// Documentation and interface for walk were adapted from Go -// https://golang.org/pkg/path/filepath/#Walk -// Copyright 2009 The Go Authors. All rights reserved. BSD license. -import { assert } from "../_util/assert.ts"; -import { basename, join, normalize } from "../path/mod.ts"; - -/** Create WalkEntry for the `path` synchronously */ -export function _createWalkEntrySync(path: string): WalkEntry { - path = normalize(path); - const name = basename(path); - const info = Deno.statSync(path); - return { - path, - name, - isFile: info.isFile, - isDirectory: info.isDirectory, - isSymlink: info.isSymlink, - }; -} - -/** Create WalkEntry for the `path` asynchronously */ -export async function _createWalkEntry(path: string): Promise<WalkEntry> { - path = normalize(path); - const name = basename(path); - const info = await Deno.stat(path); - return { - path, - name, - isFile: info.isFile, - isDirectory: info.isDirectory, - isSymlink: info.isSymlink, - }; -} - -export interface WalkOptions { - maxDepth?: number; - includeFiles?: boolean; - includeDirs?: boolean; - followSymlinks?: boolean; - exts?: string[]; - match?: RegExp[]; - skip?: RegExp[]; -} - -function include( - path: string, - exts?: string[], - match?: RegExp[], - skip?: RegExp[], -): boolean { - if (exts && !exts.some((ext): boolean => path.endsWith(ext))) { - return false; - } - if (match && !match.some((pattern): boolean => !!path.match(pattern))) { - return false; - } - if (skip && skip.some((pattern): boolean => !!path.match(pattern))) { - return false; - } - return true; -} - -export interface WalkEntry extends Deno.DirEntry { - path: string; -} - -/** Walks the file tree rooted at root, yielding each file or directory in the - * tree filtered according to the given options. The files are walked in lexical - * order, which makes the output deterministic but means that for very large - * directories walk() can be inefficient. - * - * Options: - * - maxDepth?: number = Infinity; - * - includeFiles?: boolean = true; - * - includeDirs?: boolean = true; - * - followSymlinks?: boolean = false; - * - exts?: string[]; - * - match?: RegExp[]; - * - skip?: RegExp[]; - * - * - * for await (const entry of walk(".")) { - * console.log(entry.path); - * assert(entry.isFile); - * } - */ -export async function* walk( - root: string, - { - maxDepth = Infinity, - includeFiles = true, - includeDirs = true, - followSymlinks = false, - exts = undefined, - match = undefined, - skip = undefined, - }: WalkOptions = {}, -): AsyncIterableIterator<WalkEntry> { - if (maxDepth < 0) { - return; - } - if (includeDirs && include(root, exts, match, skip)) { - yield await _createWalkEntry(root); - } - if (maxDepth < 1 || !include(root, undefined, undefined, skip)) { - return; - } - for await (const entry of Deno.readDir(root)) { - assert(entry.name != null); - let path = join(root, entry.name); - - if (entry.isSymlink) { - if (followSymlinks) { - path = await Deno.realPath(path); - } else { - continue; - } - } - - if (entry.isFile) { - if (includeFiles && include(path, exts, match, skip)) { - yield { path, ...entry }; - } - } else { - yield* walk(path, { - maxDepth: maxDepth - 1, - includeFiles, - includeDirs, - followSymlinks, - exts, - match, - skip, - }); - } - } -} - -/** Same as walk() but uses synchronous ops */ -export function* walkSync( - root: string, - { - maxDepth = Infinity, - includeFiles = true, - includeDirs = true, - followSymlinks = false, - exts = undefined, - match = undefined, - skip = undefined, - }: WalkOptions = {}, -): IterableIterator<WalkEntry> { - if (maxDepth < 0) { - return; - } - if (includeDirs && include(root, exts, match, skip)) { - yield _createWalkEntrySync(root); - } - if (maxDepth < 1 || !include(root, undefined, undefined, skip)) { - return; - } - for (const entry of Deno.readDirSync(root)) { - assert(entry.name != null); - let path = join(root, entry.name); - - if (entry.isSymlink) { - if (followSymlinks) { - path = Deno.realPathSync(path); - } else { - continue; - } - } - - if (entry.isFile) { - if (includeFiles && include(path, exts, match, skip)) { - yield { path, ...entry }; - } - } else { - yield* walkSync(path, { - maxDepth: maxDepth - 1, - includeFiles, - includeDirs, - followSymlinks, - exts, - match, - skip, - }); - } - } -} diff --git a/std/fs/walk_test.ts b/std/fs/walk_test.ts deleted file mode 100644 index 5eb6ebd69..000000000 --- a/std/fs/walk_test.ts +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. -import { walk, WalkEntry, WalkOptions, walkSync } from "./walk.ts"; -import { assert, assertEquals, assertThrowsAsync } from "../testing/asserts.ts"; - -export function testWalk( - setup: (arg0: string) => void | Promise<void>, - t: () => void | Promise<void>, - ignore = false, -): void { - const name = t.name; - async function fn(): Promise<void> { - const origCwd = Deno.cwd(); - const d = await Deno.makeTempDir(); - Deno.chdir(d); - try { - await setup(d); - await t(); - } finally { - Deno.chdir(origCwd); - await Deno.remove(d, { recursive: true }); - } - } - Deno.test({ ignore, name: `[walk] ${name}`, fn }); -} - -function normalize({ path }: WalkEntry): string { - return path.replace(/\\/g, "/"); -} - -export async function walkArray( - root: string, - options: WalkOptions = {}, -): Promise<string[]> { - const arr: string[] = []; - for await (const w of walk(root, { ...options })) { - arr.push(normalize(w)); - } - arr.sort(); // TODO(ry) Remove sort. The order should be deterministic. - const arrSync = Array.from(walkSync(root, options), normalize); - arrSync.sort(); // TODO(ry) Remove sort. The order should be deterministic. - assertEquals(arr, arrSync); - return arr; -} - -export async function touch(path: string): Promise<void> { - const f = await Deno.create(path); - f.close(); -} - -function assertReady(expectedLength: number): void { - const arr = Array.from(walkSync("."), normalize); - - assertEquals(arr.length, expectedLength); -} - -testWalk( - async (d: string): Promise<void> => { - await Deno.mkdir(d + "/empty"); - }, - async function emptyDir(): Promise<void> { - const arr = await walkArray("."); - assertEquals(arr, [".", "empty"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/x"); - }, - async function singleFile(): Promise<void> { - const arr = await walkArray("."); - assertEquals(arr, [".", "x"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/x"); - }, - async function iteratable(): Promise<void> { - let count = 0; - for (const _ of walkSync(".")) { - count += 1; - } - assertEquals(count, 2); - for await (const _ of walk(".")) { - count += 1; - } - assertEquals(count, 4); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await Deno.mkdir(d + "/a"); - await touch(d + "/a/x"); - }, - async function nestedSingleFile(): Promise<void> { - const arr = await walkArray("."); - assertEquals(arr, [".", "a", "a/x"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await Deno.mkdir(d + "/a/b/c/d", { recursive: true }); - await touch(d + "/a/b/c/d/x"); - }, - async function depth(): Promise<void> { - assertReady(6); - const arr3 = await walkArray(".", { maxDepth: 3 }); - assertEquals(arr3, [".", "a", "a/b", "a/b/c"]); - const arr5 = await walkArray(".", { maxDepth: 5 }); - assertEquals(arr5, [".", "a", "a/b", "a/b/c", "a/b/c/d", "a/b/c/d/x"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/a"); - await Deno.mkdir(d + "/b"); - await touch(d + "/b/c"); - }, - async function includeDirs(): Promise<void> { - assertReady(4); - const arr = await walkArray(".", { includeDirs: false }); - assertEquals(arr, ["a", "b/c"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/a"); - await Deno.mkdir(d + "/b"); - await touch(d + "/b/c"); - }, - async function includeFiles(): Promise<void> { - assertReady(4); - const arr = await walkArray(".", { includeFiles: false }); - assertEquals(arr, [".", "b"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/x.ts"); - await touch(d + "/y.rs"); - }, - async function ext(): Promise<void> { - assertReady(3); - const arr = await walkArray(".", { exts: [".ts"] }); - assertEquals(arr, ["x.ts"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/x.ts"); - await touch(d + "/y.rs"); - await touch(d + "/z.py"); - }, - async function extAny(): Promise<void> { - assertReady(4); - const arr = await walkArray(".", { exts: [".rs", ".ts"] }); - assertEquals(arr, ["x.ts", "y.rs"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/x"); - await touch(d + "/y"); - }, - async function match(): Promise<void> { - assertReady(3); - const arr = await walkArray(".", { match: [/x/] }); - assertEquals(arr, ["x"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/x"); - await touch(d + "/y"); - await touch(d + "/z"); - }, - async function matchAny(): Promise<void> { - assertReady(4); - const arr = await walkArray(".", { match: [/x/, /y/] }); - assertEquals(arr, ["x", "y"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/x"); - await touch(d + "/y"); - }, - async function skip(): Promise<void> { - assertReady(3); - const arr = await walkArray(".", { skip: [/x/] }); - assertEquals(arr, [".", "y"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await touch(d + "/x"); - await touch(d + "/y"); - await touch(d + "/z"); - }, - async function skipAny(): Promise<void> { - assertReady(4); - const arr = await walkArray(".", { skip: [/x/, /y/] }); - assertEquals(arr, [".", "z"]); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await Deno.mkdir(d + "/a"); - await Deno.mkdir(d + "/b"); - await touch(d + "/a/x"); - await touch(d + "/a/y"); - await touch(d + "/b/z"); - }, - async function subDir(): Promise<void> { - assertReady(6); - const arr = await walkArray("b"); - assertEquals(arr, ["b", "b/z"]); - }, -); - -testWalk( - async (_d: string): Promise<void> => {}, - async function nonexistentRoot(): Promise<void> { - await assertThrowsAsync(async () => { - await walkArray("nonexistent"); - }, Deno.errors.NotFound); - }, -); - -testWalk( - async (d: string): Promise<void> => { - await Deno.mkdir(d + "/a"); - await Deno.mkdir(d + "/b"); - await touch(d + "/a/x"); - await touch(d + "/a/y"); - await touch(d + "/b/z"); - await Deno.symlink(d + "/b", d + "/a/bb"); - }, - async function symlink(): Promise<void> { - assertReady(6); - const files = await walkArray("a"); - assertEquals(files.length, 3); - assert(!files.includes("a/bb/z")); - - const arr = await walkArray("a", { followSymlinks: true }); - assertEquals(arr.length, 5); - assert(arr.some((f): boolean => f.endsWith("/b/z"))); - }, -); |