How to use the @schematics/angular/utility/ast-utils.findNodes function in @schematics/angular

To help you get started, we’ve selected a few @schematics/angular examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ng-matero / ng-matero / schematics / utils / ast-utils.ts View on Github external
const text = routesArr.getFullText(source);

  let route: string = routeLiteral;
  if (occurencesCount > 0) {
    const identation = text.match(/\r?\n(\r?)\s*/) || [];
    route = `,${identation[0] || ' '}${routeLiteral}`;
  }

  // Find a route which `path` equals to `''`
  const routeNode = findRouteNode(routesArr, ts.SyntaxKind.Identifier, 'path', '');

  if (!routeNode) {
    throw new Error(`Couldn't find a route definition which path is empty string`);
  }

  const routeNodeArr = findNodes(
    routeNode,
    ts.SyntaxKind.ArrayLiteralExpression,
    1
  )[0] as ts.ArrayLiteralExpression;

  return insertAfterLastOccurrence(
    (routeNodeArr.elements as unknown) as ts.Node[],
    route,
    fileToAdd,
    routeNodeArr.elements.pos,
    ts.SyntaxKind.ObjectLiteralExpression
  );
}
github ng-alain / delon / packages / schematics / plugin / plugin.icon.ts View on Github external
function genCustomIcons(options: PluginOptions, host: Tree) {
  const path = options.sourceRoot + `/style-icons.ts`;
  if (!host.exists(path)) {
    host.create(
      path,
      `// Custom icon static resources

import { } from '@ant-design/icons-angular/icons';

export const ICONS = [ ];
`,
    );
    return;
  }
  const source = getSourceFile(host, path);
  const allImports = findNodes(source as any, ts.SyntaxKind.ImportDeclaration);
  const iconImport = allImports.find((w: ts.ImportDeclaration) =>
    w.moduleSpecifier.getText().includes('@ant-design/icons-angular/icons'),
  ) as ts.ImportDeclaration;
  if (!iconImport) return;
  (iconImport.importClause!.namedBindings as ts.NamedImports)!.elements!.forEach(v => WHITE_ICONS.push(v.getText().trim()));
}
github NativeScript / nativescript-schematics / src / route-utils.ts View on Github external
export function insertImport(
    source: ts.SourceFile,
    fileToEdit: string,
    symbolName: string,
    fileName: string,
    quote: '\"'|'\''|'\`' = '\"',
    isDefault = false,
): Change {
  const rootNode = source;
  const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);

  // get nodes that map to import statements from the file fileName
  const relevantImports = allImports.filter((node) => {
    // StringLiteral of the ImportDeclaration is the import file (fileName in this case).
    const importFiles = node.getChildren()
      .filter((child) => child.kind === ts.SyntaxKind.StringLiteral)
      .map((n) => (n as ts.StringLiteral).text);

    return importFiles.filter((file) => file === fileName).length === 1;
  });

  if (relevantImports.length > 0) {
    let importsAsterisk = false;
    // imports from import file
    const imports: Array = [];
    relevantImports.forEach((n) => {
github NativeScript / nativescript-schematics / src / route-utils.ts View on Github external
importsAsterisk = true;
      }
    });

    // if imports * from fileName, don't add symbolName
    if (importsAsterisk) {
      return new NoopChange();
    }

    const importTextNodes = imports.filter((n) => (n as ts.Identifier).text === symbolName);

    // insert import if it's not there
    if (importTextNodes.length === 0) {
      const fallbackPosition =
        findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() ||
        findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();

      return insertBeforeFirstOccurence(imports, `, ${symbolName}`, fileToEdit, fallbackPosition);
    }

    return new NoopChange();
  }

  // no such import declaration exists
  const useStrict = findNodes(rootNode, ts.SyntaxKind.StringLiteral)
                    .filter((n: ts.StringLiteral) => n.text === 'use strict');
  let fallbackPos = 0;
  if (useStrict.length > 0) {
    fallbackPos = useStrict[0].end;
  }
  const open = isDefault ? '' : '{ ';
  const close = isDefault ? '' : ' }';
github NG-ZORRO / ng-zorro-antd / schematics / ng-add / setup-project / register-locale.ts View on Github external
function registerLocaleData(moduleSource: ts.SourceFile, modulePath: string, locale: string): Change {
  const allImports = findNodes(moduleSource, ts.SyntaxKind.ImportDeclaration);
  const allFun = findNodes(moduleSource, ts.SyntaxKind.ExpressionStatement);

  const registerLocaleDataFun = allFun.filter(node => {
    const fun = node.getChildren();
    return fun[ 0 ].getChildren()[ 0 ] && fun[ 0 ].getChildren()[ 0 ].getText() === 'registerLocaleData';
  });

  if (registerLocaleDataFun.length === 0) {
    return insertAfterLastOccurrence(allImports, `\n\nregisterLocaleData(${locale});`,
      modulePath, 0) as InsertChange;
  } else {
    console.log();
    console.log(chalk.yellow(`Could not add the registerLocaleData to your app.module file (${chalk.blue(modulePath)}).` +
      `because there is already a registerLocaleData function.`));
    console.log(chalk.yellow(`Please manually add the following code to your app.module:`));
    console.log(chalk.cyan(`registerLocaleData(${locale});`));
    return new NoopChange();
github NG-ZORRO / ng-zorro-antd / schematics / ng-add / setup-project / register-locale.ts View on Github external
function registerLocaleData(moduleSource: ts.SourceFile, modulePath: string, locale: string): Change {
  const allImports = findNodes(moduleSource, ts.SyntaxKind.ImportDeclaration);
  const allFun = findNodes(moduleSource, ts.SyntaxKind.ExpressionStatement);

  const registerLocaleDataFun = allFun.filter(node => {
    const fun = node.getChildren();
    return fun[ 0 ].getChildren()[ 0 ] && fun[ 0 ].getChildren()[ 0 ].getText() === 'registerLocaleData';
  });

  if (registerLocaleDataFun.length === 0) {
    return insertAfterLastOccurrence(allImports, `\n\nregisterLocaleData(${locale});`,
      modulePath, 0) as InsertChange;
  } else {
    console.log();
    console.log(chalk.yellow(`Could not add the registerLocaleData to your app.module file (${chalk.blue(modulePath)}).` +
      `because there is already a registerLocaleData function.`));
    console.log(chalk.yellow(`Please manually add the following code to your app.module:`));
    console.log(chalk.cyan(`registerLocaleData(${locale});`));
github mattlewis92 / angular-calendar / projects / angular-calendar / schematics / utils / ast.ts View on Github external
export function insertAfterImports(
  source: ts.SourceFile,
  fileToEdit: string,
  toInsert: string
): Change {
  const allImports = findNodes(source, ts.SyntaxKind.ImportDeclaration);

  return insertAfterLastOccurrence(
    allImports,
    toInsert,
    fileToEdit,
    0,
    ts.SyntaxKind.StringLiteral
  );
}
github NativeScript / nativescript-schematics / src / route-utils.ts View on Github external
relevantImports.forEach((n) => {
      Array.prototype.push.apply(imports, findNodes(n, ts.SyntaxKind.Identifier));
      if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) {
        importsAsterisk = true;
      }
    });
github valor-software / ng2-charts / ng2-charts-schematics / src / ng2-charts-schematics / ng2-process-tree.ts View on Github external
_options.module = findModuleFromOptions(tree, _options);

  const codeAction = tree.actions.filter(r => r.path.endsWith('.component.ts'))[0];
  const markupActions = tree.actions.filter(r => r.path.endsWith('.component.html'));
  const codeSource = readIntoSourceFile(tree, codeAction.path);
  const nodes = getSourceNodes(codeSource);
  const classNodes = nodes.filter(r => findNodes(r, ts.SyntaxKind.ClassDeclaration).length);
  const classDecl = findNodes(classNodes[0], ts.SyntaxKind.ClassDeclaration)[0] as ts.ClassDeclaration;
  let inlineTemplate = false;
  let template: ts.PropertyAssignment;
  const changes = newImports.map(([a, b]) => insertImport(codeSource, codeAction.path, a, b));
  const recorder = tree.beginUpdate(codeAction.path);
  if (classDecl.decorators) {
    const decorator = classDecl.decorators[0];
    const literal = findNodes(decorator.expression, ts.SyntaxKind.ObjectLiteralExpression)[0] as ts.ObjectLiteralExpression;
    template = literal.properties.filter(r => ts.isPropertyAssignment(r) &&
      ts.isIdentifier(r.name) &&
      r.name.escapedText === 'template')[0] as ts.PropertyAssignment;
    if (template) {
      const newNode = ts.createStringLiteral('`' + newMarkup + '`');
      const start = template.initializer.getStart();
      const end = template.initializer.getEnd();
      recorder.remove(start, end - start);
      recorder.insertLeft(start, newNode.text);
      inlineTemplate = true;
    }
  }
  if (!inlineTemplate && markupActions.length) {
    const markupAction = markupActions[0];
    tree.overwrite(markupAction.path, newMarkup);
  }
github NativeScript / nativescript-schematics / src / route-utils.ts View on Github external
relevantImports.forEach((n) => {
      Array.prototype.push.apply(imports, findNodes(n, ts.SyntaxKind.Identifier));
      if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) {
        importsAsterisk = true;
      }
    });