<commit_before>
/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

import {dirname, join, relative} from 'canonical-path';
import {writeFileSync} from 'fs';
import {cp, mkdir} from 'shelljs';

import {AbsoluteFsPath} from '../../../src/ngtsc/path';
import {isDtsPath} from '../../../src/ngtsc/util/src/typescript';
import {EntryPoint, EntryPointJsonProperty} from '../packages/entry_point';
import {EntryPointBundle} from '../packages/entry_point_bundle';
import {FileInfo} from '../rendering/renderer';

import {InPlaceFileWriter} from './in_place_file_writer';

const NGCC_DIRECTORY = '__ivy_ngcc__';

/**
 * This FileWriter creates a copy of the original entry-point, then writes the transformed
 * files onto the files in this copy, and finally updates the package.json with a new
 * entry-point format property that points to this new entry-point.
 *
 * If there are transformed typings files in this bundle, they are updated in-place (see the
 * `InPlaceFileWriter`).
 */
export class NewEntryPointFileWriter extends InPlaceFileWriter {
  writeBundle(entryPoint: EntryPoint, bundle: EntryPointBundle, transformedFiles: FileInfo[]) {
    // The new folder is at the root of the overall package
    const relativeEntryPointPath = relative(entryPoint.package, entryPoint.path);
    const relativeNewDir = join(NGCC_DIRECTORY, relativeEntryPointPath);
    const newDir = AbsoluteFsPath.fromUnchecked(join(entryPoint.package, relativeNewDir));
    this.copyBundle(bundle, entryPoint.package, entryPoint.path, newDir);
    transformedFiles.forEach(file => this.writeFile(file, entryPoint.path, newDir));
    this.updatePackageJson(entryPoint, bundle.formatProperty, newDir);
  }

  protected copyBundle(
      bundle: EntryPointBundle, packagePath: AbsoluteFsPath, entryPointPath: AbsoluteFsPath,
      newDir: AbsoluteFsPath) {
    bundle.src.program.getSourceFiles().forEach(sourceFile => {
      const isOutsidePackage = relative(packagePath, sourceFile.fileName).startsWith('..');
      if (!sourceFile.isDeclarationFile && !isOutsidePackage) {
        const relativePath = relative(entryPointPath, sourceFile.fileName);
        const newFilePath = join(newDir, relativePath);
        mkdir('-p', dirname(newFilePath));
        cp(sourceFile.fileName, newFilePath);
      }
    });
  }

  protected writeFile(file: FileInfo, entryPointPath: AbsoluteFsPath, newDir: AbsoluteFsPath):
      void {
    if (isDtsPath(file.path.replace(/\.map$/, ''))) {
      // This is either `.d.ts` or `.d.ts.map` file
      super.writeFileAndBackup(file);
    } else {
      const relativePath = relative(entryPointPath, file.path);
      const newFilePath = join(newDir, relativePath);
      mkdir('-p', dirname(newFilePath));
      writeFileSync(newFilePath, file.contents, 'utf8');
    }
  }

  protected updatePackageJson(
      entryPoint: EntryPoint, formatProperty: EntryPointJsonProperty, newDir: AbsoluteFsPath) {
    const bundlePath = entryPoint.packageJson[formatProperty] !;
    const newBundlePath = relative(entryPoint.path, join(newDir, bundlePath));
    (entryPoint.packageJson as any)[formatProperty + '_ivy_ngcc'] = newBundlePath;
    writeFileSync(join(entryPoint.path, 'package.json'), JSON.stringify(entryPoint.packageJson));
  }
}<commit_msg>refactor(ivy): ngcc - simplify `NewEntryPointFileWriter` code (#30085)<commit_after>
/**
 * @license
 * Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

import {dirname, join, relative} from 'canonical-path';
import {writeFileSync} from 'fs';
import {cp, mkdir} from 'shelljs';

import {AbsoluteFsPath} from '../../../src/ngtsc/path';
import {isDtsPath} from '../../../src/ngtsc/util/src/typescript';
import {EntryPoint, EntryPointJsonProperty} from '../packages/entry_point';
import {EntryPointBundle} from '../packages/entry_point_bundle';
import {FileInfo} from '../rendering/renderer';

import {InPlaceFileWriter} from './in_place_file_writer';

const NGCC_DIRECTORY = '__ivy_ngcc__';

/**
 * This FileWriter creates a copy of the original entry-point, then writes the transformed
 * files onto the files in this copy, and finally updates the package.json with a new
 * entry-point format property that points to this new entry-point.
 *
 * If there are transformed typings files in this bundle, they are updated in-place (see the
 * `InPlaceFileWriter`).
 */
export class NewEntryPointFileWriter extends InPlaceFileWriter {
  writeBundle(entryPoint: EntryPoint, bundle: EntryPointBundle, transformedFiles: FileInfo[]) {
    // The new folder is at the root of the overall package
    const ngccFolder = AbsoluteFsPath.fromUnchecked(join(entryPoint.package, NGCC_DIRECTORY));
    this.copyBundle(bundle, entryPoint.package, ngccFolder);
    transformedFiles.forEach(file => this.writeFile(file, entryPoint.package, ngccFolder));
    this.updatePackageJson(entryPoint, bundle.formatProperty, ngccFolder);
  }

  protected copyBundle(
      bundle: EntryPointBundle, packagePath: AbsoluteFsPath, ngccFolder: AbsoluteFsPath) {
    bundle.src.program.getSourceFiles().forEach(sourceFile => {
      const relativePath = relative(packagePath, sourceFile.fileName);
      const isOutsidePackage = relativePath.startsWith('..');
      if (!sourceFile.isDeclarationFile && !isOutsidePackage) {
        const newFilePath = join(ngccFolder, relativePath);
        mkdir('-p', dirname(newFilePath));
        cp(sourceFile.fileName, newFilePath);
      }
    });
  }

  protected writeFile(file: FileInfo, packagePath: AbsoluteFsPath, ngccFolder: AbsoluteFsPath):
      void {
    if (isDtsPath(file.path.replace(/\.map$/, ''))) {
      // This is either `.d.ts` or `.d.ts.map` file
      super.writeFileAndBackup(file);
    } else {
      const relativePath = relative(packagePath, file.path);
      const newFilePath = join(ngccFolder, relativePath);
      mkdir('-p', dirname(newFilePath));
      writeFileSync(newFilePath, file.contents, 'utf8');
    }
  }

  protected updatePackageJson(
      entryPoint: EntryPoint, formatProperty: EntryPointJsonProperty, ngccFolder: AbsoluteFsPath) {
    const formatPath = join(entryPoint.path, entryPoint.packageJson[formatProperty] !);
    const newFormatPath = join(ngccFolder, relative(entryPoint.package, formatPath));
    const newFormatProperty = formatProperty + '_ivy_ngcc';
    (entryPoint.packageJson as any)[newFormatProperty] = relative(entryPoint.path, newFormatPath);
    writeFileSync(join(entryPoint.path, 'package.json'), JSON.stringify(entryPoint.packageJson));
  }
}
{'fraction_non_alphanumeric': 0.1169945274367697, 'fraction_numerical': 0.0010353498003253957, 'mean_word_length': 4.462035541195476, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3316840', 'n_tokens_mistral': 1956, 'n_tokens_neox': 1916, 'n_words': 510}