All files / libs/tools/plugin/src/generators/helpers project-configuration.ts

48.21% Statements 27/56
50% Branches 1/2
50% Functions 1/2
48.21% Lines 27/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                     1x 1x 1x 13x 13x 13x 13x 13x 13x       13x 13x  
import { readJson, writeJson, type ProjectConfiguration, type Tree } from '@nx/devkit';
import { omit } from 'lodash-es';
 
import { assert } from '@amalia/ext/typescript';
 
export type PackageJson = {
  name?: string;
  version?: string;
  nx?: ProjectConfiguration;
};
 
/**
 * Forked version of `updateProjectConfiguration` that writes the configuration
 * into the project's `package.json` under the `nx` field instead of
 * `project.json`/workspace config.
 */
export function updateProjectConfiguration(tree: Tree, root: string, configuration: ProjectConfiguration) {
  assert(root.includes('/'), `This is not a package root: ${root}`);

  const pkgPath = `${root}/package.json`;

  let packageJson: PackageJson = {};

  if (tree.exists(pkgPath)) {
    packageJson = readJson(tree, pkgPath);
  } else {
    packageJson = {
      name: configuration.name,
      version: '0.0.0',
    };
  }

  const newPackageJson = {
    ...packageJson,
    nx: {
      ...packageJson.nx,
      ...omit(configuration, ['name', 'root']),
    },
  };

  writeJson(tree, pkgPath, newPackageJson);
}
 
export default updateProjectConfiguration;
 
export function readProjectConfiguration(tree: Tree, root: string): ProjectConfiguration | null {
  const path = `${root}/package.json`;
 
  if (!tree.exists(path)) {
    return null;
  }

  const packageJson = readJson<PackageJson>(tree, path);

  return packageJson.nx ?? null;
}