scripts/utils/dir.js

const { NamedModulesPlugin } = require("webpack");
("use strict");

const fs = require("fs");
const paths = require("./paths");
const logger = require("./logger");

const { mkdir, access } = fs.promises;

// Check and enforce trailing slash
const ensureSlash = (inputPath, needsSlash) => {
  const hasSlash = inputPath.endsWith("/");
  if (hasSlash && !needsSlash) {
    return inputPath.substr(0, inputPath.length - 1);
  } else if (!hasSlash && needsSlash) {
    return `${inputPath}/`;
  } else {
    return inputPath;
  }
};

const getDirectories = (source) => {
  return fs
    .readdirSync(source, { withFileTypes: true })
    .filter((dirent) => dirent.isDirectory())
    .map((dirent) => dirent.name);
};

/**
 * @deprecated since version 2.42.0 - using static clients.json instead to fetch from backend
 */
const clients = getDirectories(paths.clients)
  .reduce((accu, i) => [...accu, { name: i }], [])
  .filter(({ name }) => name !== "_defaults");

const ensureDir = async (path) => {
  await access(path).catch((e) => {
    logger.warning(`${path} is not accessible, creating...`);
  });
  await mkdir(path, { recursive: true });
};

module.exports = {
  ensureSlash,
  getDirectories,
  clients,
  ensureDir,
};