// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { join } from "jsr:/@std/path@^0.224.0/join";
import { toPathString } from "./_to_path_string.ts";

/**
 * Asynchronously ensures that a directory is empty deletes the directory
 * contents it 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.
 *
 * @param dir The path of the directory to empty, as a string or URL.
 * @returns A void promise that resolves once the directory is empty.
 *
 * @example
 * ```ts
 * import { emptyDir } from "@std/fs/empty-dir";
 *
 * await emptyDir("./foo");
 * ```
 */
export async function emptyDir(dir: string | URL) {
  try {
    const items = await Array.fromAsync(Deno.readDir(dir));

    await Promise.all(items.map((item) => {
      if (item && item.name) {
        const filepath = join(toPathString(dir), item.name);
        return 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 });
  }
}

/**
 * Synchronously ensures that a directory is empty deletes the directory
 * contents it 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.
 *
 * @param dir The path of the directory to empty, as a string or URL.
 * @returns A void value that returns once the directory is empty.
 *
 * @example
 * ```ts
 * import { emptyDirSync } from "@std/fs/empty-dir";
 *
 * emptyDirSync("./foo");
 * ```
 */
export function emptyDirSync(dir: string | URL) {
  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(toPathString(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 });
  }
}

// denoCacheMetadata={"headers":{"etag":"\"65e3ab28a490150638de4e84783e0949\"","vary":"Origin","cf-ray":"a223e656afd57db6-LAX","cross-origin-resource-policy":"cross-origin","x-robots-tag":"noindex","alt-svc":"h3=\":443\"; ma=86400","set-cookie":"__cf_bm=rvKW0TGV0SVa2bDoHiwMvx86tBcRpZ7oJzJyCU24eNg-1785241874.99714-1.0.1.1-Kynz9T5_EjJlvBp6t0N8vGt2hCe6Oa4hdC7.lpEOK8LbQzsuZLgrX8tzoA8T1KuNkRc_hrDFKuAFSGlYVOtopzF_GzhkgOoukYPUvXGEcdzl3hiJCzyk5pkZePa65Ng4; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cf-cache-status":"HIT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=%2BZcZ80mAtuKDP7P1s0e%2FgwI6AmdRYkTMu7y6wiSqK6gbLHGdAJgH4L%2FCqz%2Fao5xxorbP7ujSyycr0BLpBsqDjCsBOn5TWD0fR%2FQBDwjCOl23M4Zt6milEsw%3D\"}]}","age":"804698","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","server":"cloudflare","content-length":"2291","cache-control":"public, max-age=31536000, immutable","date":"Tue, 28 Jul 2026 12:31:15 GMT","content-type":"text/typescript","access-control-expose-headers":"*","x-content-type-options":"nosniff","x-jsr-backend":"modules","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","accept-ranges":"bytes","access-control-allow-origin":"*"},"url":"https://jsr.io/@std/fs/0.224.0/empty_dir.ts","time":1785241875}