Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closes: #138 - Update index.js #139

Closed
wants to merge 4 commits into from

Conversation

frank-dspeed
Copy link

Introduces delAsync and delSync for later esm conversation

Compat with the old v6.0.0 API
Update now all Examples to const { delAsync, delSync } = require('del');
Leads to later import { delAsync, delSync } from 'del';
see: #138

Introduces delAsync and delSync for later esm conversation

Compat with the old v6.0.0 API
Update now all Examples to const { delAsync, delSync } = require('del');
Leads to later import { delAsync, delSync } from 'del';
see: sindresorhus#138
Corrected tab format
The typings for the new api while dropped the typings for the old one
Forgotten to change the import syntax to CJS
@sindresorhus
Copy link
Owner

I appreciate the PR, but I prefer to wait with API changes until the actual ESM migration.

@frank-dspeed
Copy link
Author

@sindresorhus the question was not about the pr i want to adjust your version and my fork so that we have less changes for the case that you or i spot importent bugs i would love to have our both code bases merge able with less effort thats why i wanted to discusse the symbol names thats my current version that i use to create the clean ESM version and the Clean CJS Version

/* eslint-disable no-shadow */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable prettier/prettier */
/* eslint-disable no-param-reassign */
/**
 * Generate .d.ts instructions
 * tsc --allowJs --checkJs --emitDeclarationOnly --declaration *.js
 * https://github.com/stealify-backports/del/blob/stealify-edition/index.js
 */
import { promisify } from 'node:util';
import { resolve as pathResolve } from 'node:path';

import { globby, globbySync } from 'globby';
import isGlob from 'is-glob';
import slash from 'slash';
import gracefulFs from 'graceful-fs';
import isPathCwd from 'is-path-cwd';
import isPathInside from 'is-path-inside';
import rimraf from 'rimraf';
import pMap from 'p-map';

const rimrafP = promisify(rimraf);

const rimrafOptions = {
  glob: false,
  unlink: gracefulFs.unlink,
  unlinkSync: gracefulFs.unlinkSync,
  chmod: gracefulFs.chmod,
  chmodSync: gracefulFs.chmodSync,
  stat: gracefulFs.stat,
  statSync: gracefulFs.statSync,
  lstat: gracefulFs.lstat,
  lstatSync: gracefulFs.lstatSync,
  rmdir: gracefulFs.rmdir,
  rmdirSync: gracefulFs.rmdirSync,
  readdir: gracefulFs.readdir,
  readdirSync: gracefulFs.readdirSync
};

function safeCheck(file, cwd) {
  if (isPathCwd(file)) {
    throw new Error(
      'Cannot delete the current working directory. Can be overridden with the `force` option.'
    );
  }

  if (!isPathInside(file, cwd)) {
    throw new Error(
      'Cannot delete files/directories outside the current working directory. Can be overridden with the `force` option.'
    );
  }
}

function normalizePatterns(patterns) {
  patterns = Array.isArray(patterns) ? patterns : [patterns];

  patterns = patterns.map((pattern) => {
    if (process.platform === 'win32' && isGlob(pattern) === false) {
      return slash(pattern);
    }

    return pattern;
  });

  return patterns;
}

/**
 * @typedef {import('globby').Options} GlobbyOptions
 * @typedef delOptionPropertys
 * @property {boolean} [force] default false
 * @property {boolean} [dryRun] default false
 * @property {string} [cwd] default false
 * @typedef {delOptionPropertys & GlobbyOptions} delOptions - You can specify any of the
 * [`globby` options](https://github.com/sindresorhus/globby#options) in addition to the `delOptions`. In contrast to the `globby` defaults, `expandDirectories`, `onlyFiles`, and `followSymbolicLinks` are `false` by default.
 * @typedef {string | readonly string[]} patterns - See the supported [glob patterns](https://github.com/sindresorhus/globby#globbing-patterns).
 *	- [Pattern examples with expected matches](https://github.com/sindresorhus/multimatch/blob/main/test/test.js)
 *	- [Quick globbing pattern overview](https://github.com/sindresorhus/multimatch#globbing-patterns)
 */
const normalizeDelOptions = (/** @type {delOptions} */ delOptions) => {
  const { force = false, dryRun = false, cwd = process.cwd(), ...inputGlobbyOptions } = delOptions;

  /** @type {GlobbyOptions} */
  const globbyOptions = {
    expandDirectories: false,
    onlyFiles: false,
    followSymbolicLinks: false,
    cwd,
    ...inputGlobbyOptions
  };
  return { force, dryRun, cwd, globbyOptions };
};

/**
 * delete files and directories using glob patterns.
 * Note that glob patterns can only contain forward-slashes, not
 * backward-slashes. Windows file paths can use backward-slashes
 * as long as the path does not contain any glob-like characters,
 * otherwise use `path.posix.join()` instead of `path.join()`.
 * @param {patterns} patterns - See the supported [glob patterns](https://github.com/sindresorhus/globby#globbing-patterns).
 *	- [Pattern examples with expected matches](https://github.com/sindresorhus/multimatch/blob/main/test/test.js)
 *	- [Quick globbing pattern overview](https://github.com/sindresorhus/multimatch#globbing-patterns)
 * @param {delOptions} delOptions - You can specify any of the
 * [`globby` options](https://github.com/sindresorhus/globby#options) in addition to the `delOptions`. In contrast to the `globby` defaults, `expandDirectories`, `onlyFiles`, and `followSymbolicLinks` are `false` by default.
 * @returns {Promise<string[]>} The deleted paths.
 * @example
 * ```
 * import { del } from 'del'; // ESM
 * const { del } = require('del/del.cjs'); // CJS
 *
 * const deleteAndLogPathes = async (pathesToDelete) => {
 *	const deletedPaths = await del(pathesToDelete);
 *	console.log('Deleted files and directories:\n', deletedPaths.join('\n'));
 * };
 * deleteAndLogPathes(['temp/*.js', '!temp/unicorn.js']);
 * ```
 */
const del = async (patterns, delOptions) => {
  const { force, dryRun, cwd, globbyOptions } = normalizeDelOptions(delOptions);

  patterns = normalizePatterns(patterns);

  const files = (await globby(patterns, globbyOptions)).sort((a, b) => b.localeCompare(a));

  const mapper = async (file) => {
    file = pathResolve(cwd, file);

    if (!force) {
      safeCheck(file, cwd);
    }

    if (!dryRun) {
      await rimrafP(file, rimrafOptions);
    }

    return file;
  };

  const removedFiles = await pMap(files, mapper, globbyOptions);

  removedFiles.sort((a, b) => a.localeCompare(b));

  return removedFiles;
};

/**
 * Synchronously delete files and directories using glob patterns.
 * Note that glob patterns can only contain forward-slashes, not
 * backward-slashes. Windows file paths can use backward-slashes
 * as long as the path does not contain any glob-like characters,
 * otherwise use `path.posix.join()` instead of `path.join()`.
 * @param {patterns} patterns
 * @param {delOptions} delOptions - You can specify any of the
 * [`globby` options](https://github.com/sindresorhus/globby#options) in addition to the `delOptions`. In contrast to the `globby` defaults, `expandDirectories`, `onlyFiles`, and `followSymbolicLinks` are `false` by default.
 * @returns {string[]} The deleted paths.
 * @example
 * ```
 * import { delSync } from 'del'; // ESM
 * const { delSync } = require('del/del.cjs'); // CJS
 *
 * console.log('Deleted files and directories:\n', delSync(['temp/*.js', '!temp/unicorn.js']).join('\n'));
 * ```
 */
const delSync = (/** @type {patterns} */ patterns, delOptions) => {
  const { force, dryRun, cwd, globbyOptions } = normalizeDelOptions(delOptions);

  patterns = normalizePatterns(patterns);

  const files = globbySync(patterns, globbyOptions).sort((a, b) => b.localeCompare(a));

  const removedFiles = files.map((file) => {
    file = pathResolve(cwd, file);

    if (!force) {
      safeCheck(file, cwd);
    }

    if (!dryRun) {
      rimraf.sync(file, rimrafOptions);
    }

    return file;
  });

  removedFiles.sort((a, b) => a.localeCompare(b));

  return removedFiles;
};

delSync("dd",{})

/**
 * @deprecated
 * use import { delSync } from 'del'; or const { delSync } from 'del/del.cjs';
 * not import del from 'del';
 * del.sync
 *
 */
const sync = (patterns, delOptions) => delSync(patterns, delOptions);

/**
 * @typedef {typeof del & { sync: typeof sync }} deprecatedCjsCompatModuleObject
 */

/**
 * @deprecated use import { del, delSync } from 'del';
 * not import del from 'del';
 */
const delCjsCompat = /** @type {deprecatedCjsCompatModuleObject} */ (
  Object.assign(() => {}, del, {
    sync
  })
);

export { delSync, del };
// Only needed to get good typedefinitions and transpiler results
// will get droped i guess
export default delCjsCompat;

@sindresorhus
Copy link
Owner

I'm not interested in having inline JSDoc comments. I already have TS types in index.d.ts for that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants