All files / executors/prettier check.ts

52% Statements 13/25
37.5% Branches 6/16
100% Functions 1/1
52% Lines 13/25

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                            4x   4x 1x     3x 3x 3x 3x 1x   2x 2x       2x   2x 2x                                                
import { type ExecutorContext, getProjects, logger } from '@nx/devkit';
import { execFileSync } from 'child_process';
import { FsTree } from 'nx/src/generators/tree';
 
import type { IExecutorOptions } from './schema';
import { findFiles } from './utils/find-html-files.util';
 
/**
 * Execute prettier checks.
 * @param options executor options
 * @param context executor context
 * @returns execution result
 */
export default async function check(options: IExecutorOptions, context: ExecutorContext): Promise<{ success: boolean }> {
  const projectName = context.projectName;
 
  if (typeof projectName === 'undefined') {
    throw new Error('Project name is not defined.');
  }
 
  const tree = new FsTree(context.root, false);
  const projects = getProjects(tree);
  const project = projects.get(projectName);
  if (typeof project === 'undefined') {
    throw new Error('Project does not exist.');
  }
  const src = project.sourceRoot;
  Iif (typeof src === 'undefined') {
    throw new Error('Project root does not exist.');
  }
 
  const htmlFiles = findFiles(tree, src);
 
  Eif (htmlFiles.stderr.length !== 0) {
    throw new Error(htmlFiles.stderr);
  }
 
  const jsonFiles = findFiles(tree, `${src}/..`, '.json');
 
  if (jsonFiles.stderr.length !== 0) {
    throw new Error(jsonFiles.stderr);
  }
 
  const files = `${htmlFiles.stdout} ${jsonFiles.stdout}`.trim();
 
  if (files.length > 0) {
    const input = files.split(' ');
    logger.log('files', input);
    const cmd = 'npx';
    const args =
      options.dryRun === true
        ? ['prettier', '--config', options.config, '-c', ...input]
        : ['prettier', '--config', options.config, '-c', '--write', ...input];
    execFileSync(cmd, args, { stdio: 'inherit', cwd: process.cwd(), env: process.env, shell: true });
  }
 
  return { success: htmlFiles.stderr === '' && jsonFiles.stderr === '' };
}