Example #1
0
export function findModule(host: Tree, generateDir: string,
                           moduleExt = MODULE_EXT, routingModuleExt = ROUTING_MODULE_EXT): Path {

  let dir: DirEntry | null = host.getDir('/' + generateDir);
  let foundRoutingModule = false;

  while (dir) {
    const allMatches = dir.subfiles.filter(p => p.endsWith(moduleExt));
    const filteredMatches = allMatches.filter(p => !p.endsWith(routingModuleExt));

    foundRoutingModule = foundRoutingModule || allMatches.length !== filteredMatches.length;

    if (filteredMatches.length == 1) {
      return join(dir.path, filteredMatches[0]);
    } else if (filteredMatches.length > 1) {
      throw new Error('More than one module matches. Use skip-import option to skip importing '
        + 'the component into the closest module.');
    }

    dir = dir.parent;
  }

  const errorMsg = foundRoutingModule ? 'Could not find a non Routing NgModule.'
    + `\nModules with suffix '${routingModuleExt}' are strictly reserved for routing.`
    + '\nUse the skip-import option to skip importing in NgModule.'
    : 'Could not find an NgModule. Use the skip-import option to skip importing in NgModule.';

  throw new Error(errorMsg);
}
Example #2
0
export function findModule(host: Tree, generateDir: string): Path {
  let dir: DirEntry | null = host.getDir('/' + generateDir);

  const moduleRe = /\.module\.ts$/;
  const routingModuleRe = /-routing\.module\.ts/;

  while (dir) {
    const matches = dir.subfiles.filter(
      p => moduleRe.test(p) && !routingModuleRe.test(p)
    );

    if (matches.length == 1) {
      return join(dir.path, matches[0]);
    } else if (matches.length > 1) {
      throw new Error(
        'More than one module matches. Use skip-import option to skip importing ' +
          'the component into the closest module.'
      );
    }

    dir = dir.parent;
  }

  throw new Error(
    'Could not find an NgModule for the new component. Use the skip-import ' +
      'option to skip importing components in NgModule.'
  );
}
Example #3
0
  return (tree: Tree, context: SchematicContext) => {
    // Find the closest tslint.json or tslint.yaml
    let dir: DirEntry | null = tree.getDir(path.substr(0, path.lastIndexOf('/')));

    do {
      if ((dir.subfiles as string[]).some(f => f === 'tslint.json' || f === 'tslint.yaml')) {
        break;
      }

      dir = dir.parent;
    } while (dir !== null);

    if (dir === null) {
      throw new SchematicsException(
        'Asked to run lint fixes, but could not find a tslint.json or tslint.yaml config file.');
    }

    // Only include files that have been touched.
    const files = tree.actions.reduce((acc: Set<string>, action) => {
      const path = action.path.substr(1);  // Remove the starting '/'.
      if (path.endsWith('.ts') && dir && action.path.startsWith(dir.path)) {
        acc.add(path);
      }

      return acc;
    }, new Set<string>());

    context.addTask(new TslintFixTask({
      ignoreErrors: true,
      tsConfigPath: 'tsconfig.json',
      files: [...files],
    }));
  };
Example #4
0
    return (host: Tree, context: SchematicContext) => {
        let globalStyleExt: string;
        const themeImport = '~igniteui-angular/core/styles/themes';
        const newThemeImport = '~igniteui-angular/lib/core/styles/themes';
        const config = getWorkspace(host);
        const projects = getProjects(config);

        context.logger.info(`Applying migration for Ignite UI for Angular to version ${version}`);

        if (config.schematics && config.schematics['@schematics/angular:component']) {
            // updated projects have global prefix rather than per-project:
            globalStyleExt = config.schematics['@schematics/angular:component'].styleext;
        }

        for (const proj of projects) {
            const dir = host.getDir(proj.sourceRoot);
            let ext = globalStyleExt || 'scss';
            if (proj.schematics && proj.schematics['@schematics/angular:component']) {
                ext = proj.schematics['@schematics/angular:component'].styleext || ext;
            }
            dir.visit((path, entry) => {
                if (path.endsWith('.' + ext)) {
                    let content = entry.content.toString();
                    if (content.indexOf(themeImport) !== -1) {
                        content = content.replace(themeImport, newThemeImport);
                        host.overwrite(path, content);
                    }
                }
            });
        }
    };
Example #5
0
export function findRoutingModule(tree: Tree, path: Path): Path | undefined {
  if (isOutsidePlayground(path)) {
    return;
  }

  const moduleFile = tree.getDir(path).subfiles.find(isRoutingModule);
  return moduleFile ? join(path, moduleFile) : findRoutingModule(tree, dirname(path));
}
function shouldCreateModule(tree: Tree, filePath: Path): boolean {
  const dir = tree.getDir(normalize(dirname(filePath)));
  const fileName = basename(filePath);
  const isModuleExist = isFeatureModule(fileName)
    ? hasFeatureModuleInDir(dir)
    : hasRoutingModuleInDir(dir);

  if (isModuleExist) {
    return false;
  }

  return isFeatureModule(fileName) || hasComponentsInDir(dir);
}
Example #7
0
function processComponent(tree: Tree, context: SchematicContext, componentPath: Path): void {
  const componentDir = tree.getDir(dirname(componentPath));
  const modulePath = findFeatureModule(tree, componentDir.path);
  if (!modulePath) {
    throw new SchematicsException(`Can't find module for component ${componentPath}.`);
  }

  const componentDeclarations = getClassWithDecorator(tree, componentPath, 'Component');
  if (!componentDeclarations.length) {
    return;
  }
  addComponentToModule(tree, componentDeclarations, componentPath, modulePath);

  if (hasRoutingModuleInDir(componentDir)) {
    addComponentRoute(tree, componentDeclarations, modulePath, context, componentPath);
  }
}
Example #8
0
  return (host: Tree, context: SchematicContext) => {
    context.logger.debug('Updating appmodule');

    if (options.path === undefined) {
      return;
    }

    const siblingModules = host.getDir(options.path).subfiles
      // Find all files that start with the same name, are ts files, and aren't spec files.
      .filter(f => f.startsWith(options.name) && f.endsWith('.ts') && !f.endsWith('spec.ts'))
      // Sort alphabetically for consistency.
      .sort();

    if (siblingModules.length === 0) {
      // No module to add in.
      return;
    }

    const siblingModulePath = `${options.path}/${siblingModules[0]}`;
    const logMessage = 'console.log(`page got message: ${data}`);';
    const workerCreationSnippet = tags.stripIndent`
      if (typeof Worker !== 'undefined') {
        // Create a new
        const worker = new Worker('./${options.name}.worker', { type: 'module' });
        worker.onmessage = ({ data }) => {
          ${logMessage}
        };
        worker.postMessage('hello');
      } else {
        // Web Workers are not supported in this environment.
        // You should add a fallback so that your program still executes correctly.
      }
    `;

    // Append the worker creation snippet.
    const originalContent = host.read(siblingModulePath);
    host.overwrite(siblingModulePath, originalContent + '\n' + workerCreationSnippet);

    return host;
  };
Example #9
0
  return (tree: Tree, context: SchematicContext) => {
    // Copy the update schematics to a temporary directory.
    const updateSrcs: FileEntry[] = [];
    tree.getDir(schematicsSrcPath).visit((_, entry) => updateSrcs.push(entry));
    for (let src of updateSrcs) {
      tree.create(src.path.replace(schematicsSrcPath, schematicsTmpPath), src.content);
    }

    // Downgrade @angular/cdk and @angular/material to 5.x. This allows us to use the 5.x type
    // information in the update script.
    const downgradeTask = context.addTask(new NodePackageInstallTask({
      packageName: '@angular/cdk@">=5 <6" @angular/material@">=5 <6"'
    }));

    // Run the update tslint rules.
    const updateTask = context.addTask(new TslintFixTask({
      rulesDirectory: path.join(schematicsTmpPath, 'update/rules'),
      rules: {
        // Automatic fixes.
        "switch-identifiers": true,
        "switch-property-names": true,
        "switch-string-literal-attribute-selectors": true,
        "switch-string-literal-css-names": true,
        "switch-string-literal-element-selectors": true,
        "switch-stylesheet-attribute-selectors": true,
        "switch-stylesheet-css-names": true,
        "switch-stylesheet-element-selectors": true,
        "switch-stylesheet-input-names": true,
        "switch-stylesheet-output-names": true,
        "switch-template-attribute-selectors": true,
        "switch-template-css-names": true,
        "switch-template-element-selectors": true,
        "switch-template-export-as-names": true,
        "switch-template-input-names": true,
        "switch-template-output-names": true,

        // Additional issues we can detect but not automatically fix.
        "check-class-declaration-misc": true,
        "check-identifier-misc": true,
        "check-import-misc": true,
        "check-inheritance": true,
        "check-method-calls": true,
        "check-property-access-misc": true,
        "check-template-misc": true
      }
    }, {
      silent: false,
      ignoreErrors: true,
      tsConfigPath: './src/tsconfig.json',
    }), [downgradeTask]);

    // Upgrade @angular/material back to 6.x.
    const upgradeTask = context.addTask(new NodePackageInstallTask({
      // TODO(mmalerba): Change "next" to ">=6 <7".
      packageName: '@angular/cdk@next @angular/material@next'
    }), [updateTask]);

    // Delete the temporary schematics directory.
    context.addTask(
        new RunSchematicTask('ng-post-update', {
          deleteFiles: updateSrcs
              .map(entry => entry.path.replace(schematicsSrcPath, schematicsTmpPath))
        }), [upgradeTask]);
  };
Example #10
0
export function getPlaygroundRootDir(tree: Tree): DirEntry {
  return tree.getDir(PLAYGROUND_PATH);
}