Search code examples
typescriptabstract-syntax-treeangular-librarytypescript-compiler-apiangular-schematics

Migrating breaking change using angular ng-update schematic


Unable to run custom ng update schematic. The goal is to traverse html files and search for certain dom attributes, however I am unsure how to properly traverse the Tree structure in an angular application. I have not found a great deal online regarding this and am hoping for some results here. Below is my Rule factory for how I am currently trying to access the file system.

export default function MigrationUpdate(_options: any): Rule {
  return (host: Tree, _context: SchematicContext) => {
    
    //Traverse file system in angular application
    //Searching for html files 
    host.getDir('/files').visit(filePath => {
      if (!filePath.endsWith('.html')) {
        return;
      }
      const text = host.read(filePath);
      if (text === null) {
        throw new SchematicsException('Unable to read file path.');
      }
    });

    return host;
  };
}

Solution

  • Posting this here as I have seen other developers come across this issue. To properly access a projects file structure, getDir() takes a string argument which represents the file path for that project. First retrieve the appropriate project using getWorkSpace(), found from here. Set the options.path that will be passed into getDir() as the src directory file.

    export default function (options: any): Rule {
      return (host: Tree, context: SchematicContext) => {
        
        const workspace = getWorkspace(host);
        if(!options.project){
          options.project = Object.keys(workspace.projects)[0];
        }
        const project = workspace.projects[options.project];
        options.path = join(normalize(project.root), 'src');
    
        host.getDir(options.path).visit(file => {
          if (file.endsWith('component.html')) {
            context.logger.log('info','Successfully found HTML files'); 
          }
        });
    
        return host;
      };
    }