private _setupNewGestureConfigInRootModule()

in src/material/schematics/ng-update/migrations/hammer-gestures-v9/hammer-gestures-migration.ts [720:793]


  private _setupNewGestureConfigInRootModule(gestureConfigPath: Path) {
    const {project} = this.context;
    const mainFilePath = getProjectMainFile(project);
    const rootModuleSymbol = this._getRootModuleSymbol(mainFilePath);

    if (rootModuleSymbol === null || rootModuleSymbol.valueDeclaration === undefined) {
      this.failures.push({
        filePath: mainFilePath,
        message:
          `Could not setup Hammer gestures in module. Please ` +
          `manually ensure that the Hammer gesture config is set up.`,
      });
      return;
    }

    const sourceFile = rootModuleSymbol.valueDeclaration.getSourceFile();
    const metadata = getDecoratorMetadata(
      sourceFile,
      'NgModule',
      '@angular/core',
    ) as ts.ObjectLiteralExpression[];

    // If no "NgModule" definition is found inside the source file, we just do nothing.
    if (!metadata.length) {
      return;
    }

    const filePath = this.fileSystem.resolve(sourceFile.fileName);
    const recorder = this.fileSystem.edit(filePath);
    const providersField = getMetadataField(metadata[0], 'providers')[0];
    const providerIdentifiers = providersField
      ? findMatchingChildNodes(providersField, ts.isIdentifier)
      : null;
    const gestureConfigExpr = this._importManager.addImportToSourceFile(
      sourceFile,
      GESTURE_CONFIG_CLASS_NAME,
      getModuleSpecifier(gestureConfigPath, filePath),
      false,
      this._getGestureConfigIdentifiersOfFile(sourceFile),
    );
    const hammerConfigTokenExpr = this._importManager.addImportToSourceFile(
      sourceFile,
      HAMMER_CONFIG_TOKEN_NAME,
      HAMMER_CONFIG_TOKEN_MODULE,
    );
    const newProviderNode = ts.createObjectLiteral([
      ts.createPropertyAssignment('provide', hammerConfigTokenExpr),
      ts.createPropertyAssignment('useClass', gestureConfigExpr),
    ]);

    // If the providers field exists and already contains references to the hammer gesture
    // config token and the gesture config, we naively assume that the gesture config is
    // already set up. We only want to add the gesture config provider if it is not set up.
    if (
      !providerIdentifiers ||
      !(
        this._hammerConfigTokenReferences.some(r => providerIdentifiers.includes(r.node)) &&
        this._gestureConfigReferences.some(r => providerIdentifiers.includes(r.node))
      )
    ) {
      const symbolName = this._printNode(newProviderNode, sourceFile);
      addSymbolToNgModuleMetadata(
        sourceFile,
        sourceFile.fileName,
        'providers',
        symbolName,
        null,
      ).forEach(change => {
        if (change instanceof InsertChange) {
          recorder.insertRight(change.pos, change.toAdd);
        }
      });
    }
  }