How to use @yarnpkg/lockfile - 10 common examples

To help you get started, we’ve selected a few @yarnpkg/lockfile 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 ipfs-shipyard / npm-on-ipfs / src / core / commands / rewrite-lock-file.js View on Github external
writeFileSync(lockfilePath, JSON.stringify(lockfile, null, 2))
  } else if (options.packageManager === 'yarn') {
    const lockfilePath = path.join(process.cwd(), 'yarn.lock')

    if (!existsSync(lockfilePath)) {
      console.info(`🤷 No yarn.lock found`) // eslint-disable-line no-console
      return
    }

    console.info(`🔏 Updating yarn.lock`) // eslint-disable-line no-console

    const lockfile = yarnLockfile.parse(readFileSync(lockfilePath, 'utf8'))

    replaceRegistryPath(lockfile.object, new URL(options.registry))

    writeFileSync(lockfilePath, yarnLockfile.stringify(lockfile, null, 2))
  }
}
github pubref / rules_node / node / internal / parse_yarn_lock.js View on Github external
function main() {
  // Read the yarn.lock file and parse it.
  //
  let file = fs.readFileSync('yarn.lock', 'utf8');
  let yarn = lockfile.parse(file);

  if (yarn.type !== 'success') {
    throw new Error('Lockfile parse failed: ' + JSON.stringify(yarn, null, 2));
  }

  // Foreach entry in the lockfile, create an entry object.  We'll
  // supplement/merge this with information from the package.json file
  // in a moment...
  //
  const entries = Object.keys(yarn.object).map(key => makeYarnEntry(key, yarn.object[key]));

  // Scan the node_modules directory and find all top-level ('foo') or scoped (@bar/baz)
  // modules, i.e. folders which contain a package.json file...
  const getModulesIn = p => fs.readdirSync(p).filter(f => isPackage(p, undefined, f));
  const findScopes = p => fs.readdirSync(p).filter(f => f.startsWith("@") && fs.statSync(path.join(p, f)).isDirectory());
  const getModulesInScope = (p, s) => fs.readdirSync(path.join(p, s)).filter(f => isPackage(p, s, f));
github flegall / monopack / packages / monopack-dependency-collector / src / index.js View on Github external
async _getPackageJson(context: string): Promise {
    const packageJsonFile = path.join(context, 'package.json');
    if (await exists(packageJsonFile)) {
      const pkgJson = JSON.parse(await readFile(packageJsonFile, 'utf8'));
      const yarnLockFile = path.join(context, 'yarn.lock');

      let lockFile = null;

      if (await exists(yarnLockFile)) {
        const lockFileContent = await readFile(yarnLockFile, 'utf8');

        // Needs to adjust line encoding on windows :(
        // https://github.com/yarnpkg/yarn/issues/5214#issuecomment-368274679
        const fixedLockFileContent = lockFileContent.replace(/\r/g, '');

        const yarnLock = lockfile.parse(fixedLockFileContent);
        lockFile = {
          path: context,
          dependencies: yarnLock.object,
        };
      }

      return {
        path: context,
        dependencies: pkgJson.dependencies || {},
        devDependencies: pkgJson.devDependencies || {},
        peerDependencies: pkgJson.peerDependencies || {},
        lockFile,
      };
    } else {
      return undefined;
    }
github bazelbuild / rules_nodejs / internal / npm_install / generate_build_file.js View on Github external
let moduleDirs = [
    ...getModulesIn('node_modules'),
    ...findScopes('node_modules').map(scope => getModulesIn(scope)).reduce((a, b) => a.concat(b), [])
  ]
  let nestedModuleDirs = [];
  moduleDirs.forEach(d => {
    nestedModuleDirs.push(...getModulesIn(path.join(d, 'node_modules')));
    nestedModuleDirs.push(...findScopes(path.join(d, 'node_modules')).map(scope => getModulesIn(scope)).reduce((a, b) => a.concat(b), []));
  });
  moduleDirs.push(...nestedModuleDirs);

  const modules = moduleDirs.map(dir => parseNodeModulePackageJson(dir));

  if (fs.existsSync('yarn.lock')) {
    // Read the yarn.lock file and parse it.
    const yarn = lockfile.parse(fs.readFileSync('yarn.lock', {encoding: 'utf8'}));

    if (yarn.type !== 'success') {
      throw new Error('Lockfile parse failed: ' + JSON.stringify(yarn, null, 2));
    }

    validateYarnLock(yarn, modules);
  }

  modules.forEach(module => flattenDependencies(module, module, modules));

  let buildFile = generatedHeader + allFilegroup;
  modules.forEach(module => buildFile += printNodeModule(module));
  fs.writeFileSync('BUILD.bazel', buildFile);
}
github microsoft / rushstack / apps / rush-lib / src / logic / yarn / YarnShrinkwrapFile.ts View on Github external
protected serialize(): string {
    // abstract
    return lockfile.stringify(this._shrinkwrapJson);
  }
github atlassian / yarn-deduplicate / modules / fix-duplicates.js View on Github external
json[`${name}@${p.requestedVersion}`] = dedupedPackage.pkg;
            })
            } else {
            // otherwise dedupe each package to its maxSatisfying version
            packages.forEach(p => {
                const targetVersion = semver.maxSatisfying(versions, p.requestedVersion);
                if (targetVersion === null) return;
                if (targetVersion !== p.pkg.version) {
                    const dedupedPackage = packages.find( p => p.pkg.version === targetVersion);
                    json[`${name}@${p.requestedVersion}`] = dedupedPackage.pkg;
                }
            })
            }
        });

    return lockfile.stringify(json);
}
github atlassian / yarn-deduplicate / __tests__ / index.js View on Github external
library@>=1.0.0:
      version "3.0.0"
      resolved "https://example.net/library@^3.0.0"

    library@>=1.1.0:
      version "3.0.0"
      resolved "https://example.net/library@^3.0.0"

    library@^2.0.0:
      version "2.1.0"
      resolved "https://example.net/library@^2.1.0"
  `;
    const deduped = fixDuplicates(yarn_lock, {
        useMostCommon: true,
    });
    const json = lockfile.parse(deduped).object;

    expect(json['library@>=1.0.0']['version']).toEqual('2.1.0');
    expect(json['library@>=1.1.0']['version']).toEqual('2.1.0');
    expect(json['library@^2.0.0']['version']).toEqual('2.1.0');

    const list = listDuplicates(yarn_lock, {
        useMostCommon: true,
    });

    expect(list).toContain('Package "library" wants >=1.0.0 and could get 2.1.0, but got 3.0.0');
    expect(list).toContain('Package "library" wants >=1.1.0 and could get 2.1.0, but got 3.0.0');
});
github DefinitelyTyped / DefinitelyTyped / types / yarnpkg__lockfile / yarnpkg__lockfile-tests.ts View on Github external
import { parse, stringify, FirstLevelDependency } from '@yarnpkg/lockfile';

function testFirstLevelDependency(obj: FirstLevelDependency) {}

const file = '';
const parseResult = parse(file);
const fileAgain = stringify(parseResult);
fileAgain.toLowerCase();

if (parseResult.type === 'merge' || parseResult.type === 'success') {
  Object.keys(parseResult.object).forEach(k => {
    const value = parseResult.object[k];
    testFirstLevelDependency(value);
  });
}
github atlassian / yarn-deduplicate / index.js View on Github external
const parseYarnLock = file => lockfile.parse(file).object;
github RiseVision / rise-node / .devutils / package-deps / index.ts View on Github external
(packagePath: string = '.'): ILockfile => {
    const file = fs.readFileSync(
      path.join(root(), packagePath, 'yarn.lock'),
      'utf8'
    );
    const lockfile = yarnLockfile.parse(file);

    if (lockfile.type !== 'success') {
      throw new Error(
        `Could not parse lockfile: ${path.join(packagePath, 'yarn.lock')}!`
      );
    }
    return lockfile.object;
  }
);

@yarnpkg/lockfile

The parser/stringifier for Yarn lockfiles.

BSD-2-Clause
Latest version published 6 years ago

Package Health Score

65 / 100
Full package analysis

Popular @yarnpkg/lockfile functions