How to use the @yarnpkg/fslib.toFilename function in @yarnpkg/fslib

To help you get started, we’ve selected a few @yarnpkg/fslib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yarnpkg / berry / packages / yarnpkg-pnp / sources / loader / makeApi.ts View on Github external
candidates.push(unqualifiedPath);
        stat = opts.fakeFs.statSync(unqualifiedPath);
      } catch (error) {}

      // If the file exists and is a file, we can stop right there

      if (stat && !stat.isDirectory())
        return opts.fakeFs.realpathSync(unqualifiedPath);

      // If the file is a directory, we must check if it contains a package.json with a "main" entry

      if (stat && stat.isDirectory()) {
        let pkgJson;

        try {
          pkgJson = JSON.parse(opts.fakeFs.readFileSync(ppath.join(unqualifiedPath, toFilename(`package.json`)), `utf8`));
        } catch (error) {}

        let nextUnqualifiedPath;

        if (pkgJson && pkgJson.main)
          nextUnqualifiedPath = ppath.resolve(unqualifiedPath, pkgJson.main);

        // If the "main" field changed the path, we start again from this new location

        if (nextUnqualifiedPath && nextUnqualifiedPath !== unqualifiedPath) {
          const resolution = applyNodeExtensionResolution(nextUnqualifiedPath, candidates, {extensions});

          if (resolution !== null) {
            return resolution;
          }
        }
github yarnpkg / berry / packages / plugin-exec / sources / ExecFetcher.ts View on Github external
// Discard the parent fs unless we really need it to access the files
    if (parentFetch !== effectiveParentFetch && parentFetch.releaseFs)
      parentFetch.releaseFs();

    const generatorFs = effectiveParentFetch.packageFs;
    const generatorPath = ppath.resolve(ppath.resolve(generatorFs.getRealPath(), effectiveParentFetch.prefixPath), path);

    // Execute the specified script in the temporary directory
    const cwd = await this.generatePackage(locator, generatorPath, opts);

    // Make sure the script generated the package
    if (!xfs.existsSync(ppath.join(cwd, toFilename(`build`))))
      throw new Error(`The script should have generated a build directory`);

    return await tgzUtils.makeArchiveFromDirectory(ppath.join(cwd, toFilename(`build`)), {
      prefixPath: structUtils.getIdentVendorPath(locator),
    });
  }
github yarnpkg / berry / packages / yarnpkg-core / sources / scriptUtils.ts View on Github external
if (typeof value !== `undefined`)
      scriptEnv[key.toLowerCase() !== `path` ? key : `PATH`] = value;

  const nativeBinFolder = dirSync().name;
  const binFolder = npath.toPortablePath(nativeBinFolder);

  // We expose the base folder in the environment so that we can later add the
  // binaries for the dependencies of the active package
  scriptEnv.BERRY_BIN_FOLDER = nativeBinFolder;

  // Register some binaries that must be made available in all subprocesses
  // spawned by Yarn (we thus ensure that they always use the right version)
  await makePathWrapper(binFolder, toFilename(`node`), process.execPath);

  if (YarnVersion !== null) {
    await makePathWrapper(binFolder, toFilename(`run`), process.execPath, [process.argv[1], `run`]);
    await makePathWrapper(binFolder, toFilename(`yarn`), process.execPath, [process.argv[1]]);
    await makePathWrapper(binFolder, toFilename(`yarnpkg`), process.execPath, [process.argv[1]]);
    await makePathWrapper(binFolder, toFilename(`node-gyp`), process.execPath, [process.argv[1], `run`, `--top-level`, `node-gyp`]);
  }

  if (project)
    scriptEnv.INIT_CWD = project.configuration.startingCwd;

  scriptEnv.PATH = scriptEnv.PATH
    ? `${nativeBinFolder}${npath.delimiter}${scriptEnv.PATH}`
    : `${nativeBinFolder}`;

  scriptEnv.npm_execpath = `${nativeBinFolder}${npath.sep}yarn`;
  scriptEnv.npm_node_execpath = `${nativeBinFolder}${npath.sep}node`;

  const version = YarnVersion !== null
github yarnpkg / berry / packages / acceptance-tests / pkg-tests-core / sources / utils / tests.ts View on Github external
export const getPackageArchivePath = async (name: string, version: string): Promise => {
  const packageEntry = await getPackageEntry(name);
  if (!packageEntry)
    throw new Error(`Unknown package "${name}"`);

  const packageVersionEntry = packageEntry.get(version);
  if (!packageVersionEntry)
    throw new Error(`Unknown version "${version}" for package "${name}"`);

  const archivePath = await fsUtils.createTemporaryFile(toFilename(`${name}-${version}.tar.gz`));

  await fsUtils.packToFile(archivePath, npath.toPortablePath(packageVersionEntry.path), {
    virtualPath: npath.toPortablePath('/package'),
  });

  return archivePath;
};
github yarnpkg / berry / packages / yarnpkg-pnpify / sources / buildNodeModulesTree.ts View on Github external
*
 * Sample contents:
 * /home/user/project/node_modules -> {dirList: ['foo', 'bar']}
 * /home/user/project/node_modules/foo -> {target: '/home/user/project/.yarn/.cache/foo.zip/node_modules/foo', linkType: 'HARD'}
 * /home/user/project/node_modules/bar -> {target: '/home/user/project/packages/bar', linkType: 'SOFT'}
 */
export type NodeModulesTree = Map} | {dirList?: undefined, locator: LocatorKey, size: number, target: PortablePath, linkType: LinkType}>;

export interface NodeModulesTreeOptions {
  optimizeSizeOnDisk?: boolean;
  pnpifyFs?: boolean;
  knownLocatorWeights?: Map;
}

/** node_modules path segment */
const NODE_MODULES = toFilename(`node_modules`);

/** Package locator key for usage inside maps */
type LocatorKey = string;

/**
 * Returns path to archive, if package location is inside the archive.
 *
 * @param packagePath package location
 *
 * @returns path to archive is location is insde the archive or null otherwise
 */
export const getArchivePath = (packagePath: PortablePath): PortablePath | null =>
  packagePath.indexOf(`.zip/${NODE_MODULES}/`) >= 0 ?
    npath.toPortablePath(packagePath.split(`/${NODE_MODULES}/`)[0]) :
    null;
github yarnpkg / berry / packages / plugin-stage / sources / drivers / GitDriver.ts View on Github external
async findRoot(cwd: PortablePath) {
    return await stageUtils.findVcsRoot(cwd, {marker: toFilename(`.git`)});
  },
github yarnpkg / berry / packages / plugin-node-modules / sources / NodeModulesLinker.ts View on Github external
import {Installer, Linker, LinkOptions, MinimalLinkOptions, LinkType}  from '@yarnpkg/core';
import {PortablePath, npath, ppath, toFilename, Filename, xfs, FakeFS} from '@yarnpkg/fslib';
import {NodeFS, VirtualFS, ZipOpenFS}                                  from '@yarnpkg/fslib';
import {parseSyml}                                                     from '@yarnpkg/parsers';
import {NodeModulesLocatorMap, buildLocatorMap, buildNodeModulesTree}  from '@yarnpkg/pnpify';
import {getArchivePath}                                                from '@yarnpkg/pnpify';
import {PackageRegistry, makeRuntimeApi}                               from '@yarnpkg/pnp';

import {UsageError}                                                    from 'clipanion';
import fs                                                              from 'fs';
import mm                                                              from 'micromatch';
import unzipper                                                        from 'unzipper';

import {getPnpPath}                                                    from './index';

const NODE_MODULES = toFilename('node_modules');
const LOCATOR_STATE_FILE = toFilename('.yarn-state.yml');

export class NodeModulesLinker implements Linker {
  supportsPackage(pkg: Package, opts: MinimalLinkOptions) {
    return opts.project.configuration.get('nodeLinker') === 'node-modules';
  }

  async findPackageLocation(locator: Locator, opts: LinkOptions) {
    const pnpPath = getPnpPath(opts.project);
    if (!xfs.existsSync(pnpPath))
      throw new UsageError(`The project in ${opts.project.cwd}/package.json doesn't seem to have been installed - running an install there might help`);

    const physicalPath = npath.fromPortablePath(pnpPath);
    const pnpFile = miscUtils.dynamicRequire(physicalPath);
    delete require.cache[physicalPath];
github yarnpkg / berry / packages / plugin-node-modules / sources / NodeModulesLinker.ts View on Github external
const cloneModule = async (srcDir: PortablePath, dstDir: PortablePath, options?: { keepNodeModules?: boolean, innerLoop?: boolean }) => {
    try {
      if (!options || !options.innerLoop) {
        await removeDir(dstDir, {excludeNodeModules: options && options.keepNodeModules});
        await xfs.mkdirpPromise(dstDir, {chmod: 0o777});
      }

      const entries = await xfs.readdirPromise(srcDir, {withFileTypes: true});
      for (const entry of entries) {
        const entryName = toFilename(entry.name);
        const src = ppath.join(srcDir, entryName);
        const dst = ppath.join(dstDir, entryName);
        if (entryName !== NODE_MODULES || !options || !options.keepNodeModules) {
          if (entry.isDirectory()) {
            await xfs.mkdirPromise(dst);
            await xfs.chmodPromise(dst, 0o777);
            await cloneModule(src, dst, {keepNodeModules: false, innerLoop: true});
          } else {
            await xfs.copyFilePromise(src, dst, fs.constants.COPYFILE_FICLONE);
          }
        }
      }
    } catch (e) {
      if (!options || !options.innerLoop)
        e.message = `While cloning ${srcDir} -> ${dstDir} ${e.message}`;
github yarnpkg / berry / packages / plugin-stage / sources / drivers / MercurialDriver.ts View on Github external
async findRoot(cwd: PortablePath) {
    return await stageUtils.findVcsRoot(cwd, {marker: toFilename(`.hg`)});
  },