All files / executors/prettier configure.ts

100% Statements 54/54
96.15% Branches 25/26
100% Functions 7/7
100% Lines 52/52

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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140                            10x       10x                             10x     10x 10x 10x       57x 57x 1x     56x 56x 336x 336x     56x 56x 56x 56x     56x   56x 6x 6x 6x 6x 6x 6x     50x 50x 1x   49x 49x           49x         37x 37x 1x   36x 18x 18x         10x   10x 10x 94x         94x 37x   57x       7x 2x   2x   2x 1x                             1x 1x   1x    
import { type ExecutorContext, getProjects, logger, type ProjectConfiguration, updateProjectConfiguration } from '@nx/devkit';
import { flushChanges, FsTree } from 'nx/src/generators/tree';
 
import type { IExecutorOptions } from './schema';
 
export interface IProjectMetadata {
  name: string;
  config: ProjectConfiguration;
}
 
/**
 * Prettier check executor configurator.
 */
export class AppConfigurePrettierCheckExecutor {
  public options: IExecutorOptions = {
    config: '',
  };
 
  public context: ExecutorContext = {
    cwd: process.cwd(),
    isVerbose: false,
    root: '/root',
    projectsConfigurations: {
      version: 2,
      projects: {},
    },
    nxJsonConfiguration: {},
    projectGraph: {
      nodes: {},
      dependencies: {},
    },
  };
 
  public tree: FsTree = new FsTree(this.context.root, false);
 
  constructor(options: IExecutorOptions, context: ExecutorContext) {
    this.options = { ...options };
    this.context = { ...context };
    this.tree = new FsTree(this.context.root, false);
  }
 
  private addExecutorConfiguration(tree: FsTree, project: IProjectMetadata) {
    const srcRoot = project.config.sourceRoot;
    if (typeof srcRoot === 'undefined') {
      throw new Error(`The project ${project.name} does not have the 'sourceRoot' configuration option defined.`);
    }
 
    const prefixes = ['api', 'client', 'backend', 'elements', 'documentation', 'server'];
    const correctPrefix = prefixes.reduce((accumulator, value) => {
      const correct = new RegExp(`^${value}(-)?`).test(project.name);
      return accumulator || correct;
    }, false);
 
    const suffixes = ['e2e'];
    const correctSuffix = suffixes.reduce((accumulator, value) => {
      const correct = new RegExp(`(-)?${value}$`).test(project.name);
      return accumulator || correct;
    }, false);
 
    const addExecutor = correctPrefix || correctSuffix;
 
    if (!addExecutor) {
      const prefixOptions = prefixes.join(', ').trim();
      const suffixOptions = suffixes.join(', ').trim();
      logger.log(`${project.name}: this executor is required for apps and libs with the following prefixes or suffixes in their names.`);
      logger.log(` - prefixes: ${prefixOptions}`);
      logger.log(` - suffixes: ${suffixOptions}`);
      return;
    }
 
    const config = { ...project.config };
    if (typeof config.targets === 'undefined') {
      throw new Error(`The project ${project.name} does not have the 'targets' configuration option defined.`);
    }
    Eif (typeof config.targets['prettier-check'] === 'undefined' && /\/src$/.test(srcRoot)) {
      config.targets['prettier-check'] = {
        executor: './tools/executors/prettier:check',
        options: {
          config: this.options.config,
        },
      };
      updateProjectConfiguration(tree, project.name, config);
    }
  }
 
  private removeExecutorConfiguration(tree: FsTree, project: IProjectMetadata) {
    const config = { ...project.config };
    if (typeof config.targets === 'undefined') {
      throw new Error(`The project ${project.name} does not have the 'targets' configuration option defined.`);
    }
    if (typeof config.targets['prettier-check'] !== 'undefined') {
      delete config.targets['prettier-check'];
      updateProjectConfiguration(tree, project.name, config);
    }
  }
 
  public configure() {
    const projects = getProjects(this.tree);
 
    const entries = [...projects.entries()];
    for (let i = 0, max = entries.length; i < max; i += 1) {
      const project = {
        name: entries[i][0],
        config: entries[i][1],
      };
 
      if (this.options.cleanup === true) {
        this.removeExecutorConfiguration(this.tree, project);
      } else {
        this.addExecutorConfiguration(this.tree, project);
      }
    }
 
    if (this.options.dryRun !== true) {
      const changes = this.tree.listChanges();
 
      flushChanges(this.context.root, changes);
 
      if (this.options.cleanup === true) {
        logger.warn(
          `Don't forget to remove the executor configuration target from './tools/project.json'. Find a target 'prettier-configure'.`,
        );
      }
    }
  }
}
 
/**
 * Configure prettier executor.
 * @param options executor options
 * @param context executor context
 * @returns execution result
 */
export default async function configure(options: IExecutorOptions, context: ExecutorContext): Promise<{ success: boolean }> {
  const executor = new AppConfigurePrettierCheckExecutor(options, context);
  executor.configure();
 
  return { success: true };
}