@angular-devkit/schematics#Rule TypeScript Examples

The following examples show how to use @angular-devkit/schematics#Rule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
fnGenerateModalModule = function (tree: Tree, path: string, name: string): Rule {
    return chain([
        async () => {
            // 读取文件
            let tsFile = tree.read(path)?.toString()!;
            // 转换成抽象语法树
            // let ast = ts.createSourceFile('default-routing.module', tsFile, ScriptTarget.Latest)
            let selector = createCssSelectorForTs(tsFile)
            let result = selector.queryOne(`SourceFile ClassDeclaration Decorator CallExpression ObjectLiteralExpression PropertyAssignment[name=imports] ArrayLiteralExpression Identifier`) as (ts.Identifier);
            let recorder = tree.beginUpdate(path);
            recorder.insertLeft(result.pos, `
    ${classify(name)}ModalModule,`);
            await tree.commitUpdate(recorder);
        }
    ]);
}
Example #2
Source File: dependencies.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function allowCommonJsDependencies(options: CoveoSchema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const workspaceBuffer = tree.read(normalize('./angular.json'));
    if (workspaceBuffer === null || !options.project) {
      return;
    }
    try {
      const workspaceConfig = JSON.parse(workspaceBuffer.toString());

      const allowedCommonJsDependencies =
        workspaceConfig.projects[options.project].architect.build.options[
          'allowedCommonJsDependencies'
        ] || [];

      allowedCommonJsDependencies.push('@coveo/headless');

      workspaceConfig.projects[options.project].architect.build.options[
        'allowedCommonJsDependencies'
      ] = allowedCommonJsDependencies;

      tree.overwrite(
        normalize('./angular.json'),
        JSON.stringify(workspaceConfig, null, 4)
      );
    } catch (error) {
      console.error(
        `Unable to update the Angular workspace configuration by adding @coveo/headless as a "allowedCommonJsDependencies".
Make sure your angular.json file is valid and contains a "build" target (see https://angular.io/guide/glossary#target).`,
        error
      );
    }
  };
}
Example #3
Source File: angular-universal.adapter.ts    From nx-plugins with MIT License 6 votes vote down vote up
getApplicationTypeTemplate(): Rule {
    const buildTarget = this.project.targets.get('build') as TargetDefinition;
    return applyTemplates({
      getRootDirectory: () => '',
      buildPath: join(
        `../../../${(buildTarget.options as JsonObject).outputPath}`
      ),
      projectName: this.options.project
    });
  }
Example #4
Source File: ng-module.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function updateNgModule(
  _options: CoveoSchema,
  _project: ProjectDefinition
): Rule {
  return (tree: Tree) => {
    const appModulePath = getAppModulePath(tree, getProjectMainFile(_project));

    const appModuleContent =
      tree.get(appModulePath)?.content.toString() ||
      getDefaultAppModuleContent();

    const source = createSourceFile(
      appModulePath,
      appModuleContent,
      ScriptTarget.Latest,
      true
    );
    const updateRecorder = tree.beginUpdate(appModulePath);

    const changes = getAdditionalImports(source, appModulePath);

    changes.map((change) => {
      if (change instanceof InsertChange) {
        updateRecorder.insertLeft(change.pos, change.toAdd);
      }
    });

    tree.commitUpdate(updateRecorder);

    return tree;
  };
}
Example #5
Source File: get-angular-sub-dir.rule.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export function getAngularSubDirRuleFactory(options: HookOptions): Rule {
  return async (tree: Tree, context: SchematicContext) => {
    const dirs = tree.getDir(
      join(normalize(options.sourceInSchematicsPath), options.subDir)
    );
    if (dirs.subdirs.length && dirs.subfiles.length) {
      return;
    }
    await cloneSpecifiedDir(options);
  };
}
Example #6
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
function oneLevelRule(_options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        const sourceTemplates = url('./files'); // 使用範本
        const sourceParametrizedTemplates = apply(sourceTemplates, [
            // renameTemplateFiles(), // 去掉后缀
            applyTemplates({
                ...strings,
                ..._options, // 使用者所輸入的參數
            })
        ]);
        return mergeWith(sourceParametrizedTemplates);
    };

}
Example #7
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
export default function(options: Options): Rule {
  return () => {
    if (!options.getWorkspace) {
      throw new Error('getWorkspace option is missing');
      return;
    }
    const workspace = options.getWorkspace();

    const baseTsConfigPath = Path.join(workspace.cwd, 'tsconfig.base.json');

    return chain([syncTsConfigs(workspace, baseTsConfigPath, options.name)]);
  };
}
Example #8
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
export default function (options: NxDeployItInitSchematicSchema) {
  return async (host: Tree, context: SchematicContext): Promise<Rule> => {
    const workspace = await getWorkspace(host);
    const project = workspace.projects.get(options.project);

    if (!project) {
      context.logger.error(`Project doesn't exist`);
      return chain([]);
    }

    if (project.targets.has('deploy')) {
      context.logger.error(
        `Your project is already configured with a deploy job`
      );
      return chain([]);
    }

    if (host.exists(join(project.root, 'infrastructure', 'Pulumi.yaml'))) {
      context.logger.error(`This project already has an infrastructure`);
      return chain([]);
    }

    const adapter = getAdapter(project, options, host);
    await adapter.extendOptionsByUserInput();

    return chain([initializeCloudProviderApplication(adapter)]);
  };
}
Example #9
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
export default function(options: Options): Rule {
  return () => {
    if (!options.getWorkspace) {
      return;
    }
    const { project, dep, dev = false } = options;
    if (!project) {
      throw new Error('Provide project name');
    }
    if (!dep) {
      throw new Error('Provide dependency name');
    }
    const workspace = options.getWorkspace();

    return chain([addDependency(workspace, project, dep, dev)]);
  };
}
Example #10
Source File: index.ts    From angular-git-info with MIT License 6 votes vote down vote up
function updateDependencies(): Rule {
    return (tree: Tree, context: SchematicContext): Observable<Tree> => {
        context.logger.debug('Updating dependencies...');
        context.addTask(new NodePackageInstallTask());

        const fixedDependencies = of({name: 'fs-extra', version: '6.0.1'})
            .pipe(
                map((packageFromRegistry: NodePackage) => {
                    const {name, version} = packageFromRegistry;
                    context.logger.debug(`Adding ${name}:${version} to ${NodeDependencyType.Dev}`);

                    addPackageJsonDependency(tree, {
                        type: NodeDependencyType.Dev,
                        name,
                        version,
                    });

                    return tree;
                })
            );
        const addLatestDependencies = of('git-describe').pipe(
            concatMap((packageName: string) => getLatestNodeVersion(packageName)),
            map((packageFromRegistry: NodePackage) => {
                const {name, version} = packageFromRegistry;
                context.logger.debug(`Adding ${name}:${version} to ${NodeDependencyType.Dev}`);

                addPackageJsonDependency(tree, {
                    type: NodeDependencyType.Dev,
                    name,
                    version,
                });

                return tree;
            })
        );

        return concat(addLatestDependencies, fixedDependencies);
    };
}
Example #11
Source File: workspace.ts    From source-map-analyzer with MIT License 6 votes vote down vote up
export function updateWorkspace(
    updaterOrWorkspace:
      | workspaces.WorkspaceDefinition
      | ((workspace: workspaces.WorkspaceDefinition) => void | Rule | PromiseLike<void | Rule>),
  ): Rule {
    return async (tree: Tree) => {
      const host = createHost(tree);
  
      if (typeof updaterOrWorkspace === 'function') {
        const { workspace } = await workspaces.readWorkspace('/', host);
  
        const result = await updaterOrWorkspace(workspace);
  
        await workspaces.writeWorkspace(workspace, host);
  
        return result || noop;
      } else {
        await workspaces.writeWorkspace(updaterOrWorkspace, host);
  
        return noop;
      }
    };
  }
Example #12
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
function generateNewPulumiProject(adapter: BaseAdapter): Rule {
  return (): Rule => {
    const template = getCloudTemplateName(adapter.options.provider);
    const args = [
      'new',
      template,
      '--name',
      adapter.options.project,
      '--dir',
      resolve(join(adapter.project.root, 'infrastructure')),
      '--description',
      'Infrastructure as Code based on Pulumi - managed by @dev-thought/nx-deploy-it',
      '--generate-only',
      '--yes',
    ];

    spawnSync(getPulumiBinaryPath(), args, {
      env: { ...process.env, PULUMI_SKIP_UPDATE_CHECK: '1' },
    });

    return addDependenciesFromPulumiProjectToPackageJson(adapter);
  };
}
Example #13
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
export default function(options: Options): Rule {
  return () => {
    if (!options.getWorkspace) {
      return;
    }
    const { field, value, projects, merge } = options;
    if (!field) {
      throw new Error('Provide field name');
    }
    if (!value) {
      throw new Error('Provide value');
    }
    const workspace = options.getWorkspace();
    const projectNames = projects.split(',').map(_ => _.trim());

    return chain([
      syncPackageJson(workspace, field, value, projectNames, Boolean(merge))
    ]);
  };
}
Example #14
Source File: index.ts    From edit-in-place with MIT License 6 votes vote down vote up
export default function(options: SchemaOptions): Rule {
  return (host: Tree, context: SchematicContext) => {
    const project = getProject(host, options.project);
    const sourceRoot = (project && project.sourceRoot) || 'src';
    options.module = findRootModule(host, options.module, sourceRoot) as string;

    return chain([
      addImportsToModuleFile(options, ['EditableModule']),
      addImportsToModuleDeclaration(options, ['EditableModule'])
    ])(host, context);
  };
}
Example #15
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function updateProject(adapter: BaseAdapter): Rule {
  return async () => {
    return chain([
      updateWorkspace((workspace) => {
        const project = workspace.projects.get(adapter.options.project);
        project.targets.add({
          name: 'deploy',
          ...adapter.getDeployActionConfiguration(),
        });
        project.targets.add({
          name: 'destroy',
          ...adapter.getDestroyActionConfiguration(),
        });
      }),
      updateJsonInTree(
        join(adapter.project.root, 'tsconfig.app.json'),
        (json) => {
          const exclude: string[] = json.exclude;
          const excludePaths = 'infrastructure/**/*.ts';

          if (!exclude) {
            json.exclude = [excludePaths];
          } else {
            exclude.push(excludePaths);
          }
          return json;
        }
      ),
    ]);
  };
}
Example #16
Source File: build-component.ts    From fab-menu with MIT License 6 votes vote down vote up
/**
 * Rule that copies and interpolates the files that belong to this schematic context. Additionally
 * a list of file paths can be passed to this rule in order to expose them inside the EJS
 * template context.
 *
 * This allows inlining the external template or stylesheet files in EJS without having
 * to manually duplicate the file content.
 */
export function buildComponent(options: ComponentOptions, additionalFiles: { [key: string]: string } = {}): Rule {
  return originalBuildComponent(options, additionalFiles);
}
Example #17
Source File: nestjs.adapter.ts    From nx-plugins with MIT License 6 votes vote down vote up
getApplicationTypeTemplate(): Rule {
    return applyTemplates({
      rootDir: 'src',
      getRootDirectory: () => 'src',
      stripTsExtension: (s: string) => s.replace(/\.ts$/, ''),
      getRootModuleName: () => 'AppModule',
      getRootModulePath: () => 'app/app.module',
      projectName: this.options.project
    });
  }
Example #18
Source File: index.ts    From fab-menu with MIT License 6 votes vote down vote up
export function addModuleToImports(options: any): Rule {
  return (host: Tree, context: SchematicContext) => {
    const workspace = getWorkspace(host);
    const project = getProjectFromWorkspace(
      workspace,
      // Takes the first project in case it's not provided by CLI
      options.project ? options.project : Object.keys(workspace.projects)[0]
    );

    const moduleName = `MatFabMenuModule`;

    addModuleImportToRootModule(host, moduleName, '@angular-material-extensions/fab-menu', project);

    context.logger.log('info', `✅️ "${moduleName}" is imported`);

    return host;
  };
}
Example #19
Source File: dependencies.ts    From cli with Apache License 2.0 5 votes vote down vote up
export function addMaterialAngular(_options: CoveoSchema): Rule {
  console.log('\nConfigure your Material Project');
  // For more information about @angular/material schema options:
  // https://github.com/angular/components/blob/e99ca0ac9b0088d20d5d680092cd7ea5624934c0/src/material/schematics/ng-add/schema.json
  return externalSchematic('@angular/material', 'install', _options);
}
Example #20
Source File: index.ts    From angular-git-info with MIT License 5 votes vote down vote up
function addScriptsToPackageJson(): Rule {
    return (tree: Tree, context: SchematicContext) => {
        addPropertyToPackageJson(tree, context, 'scripts', {
            'postinstall': 'node git-version.js'
        });
        return tree;
    };
}
Example #21
Source File: index.ts    From open-source with MIT License 5 votes vote down vote up
export default function (options: ComponentOptions): Rule {
   return async (host: Tree) => {
     const workspace = await getWorkspace(host);
     const project = workspace.projects.get(options.project as string);

     if (options.path === undefined && project) {
       options.path = buildDefaultPath(project);
     }

     if (options.prefix === undefined && project) {
       options.prefix = project.prefix || '';
     }

     options.module = findModuleFromOptions(host, options);

     const parsedPath = parseName(options.path as string, options.name);
     options.name = parsedPath.name;
     options.path = parsedPath.path;
     options.selector =
       options.selector || buildSelector(options, (project && project.prefix) || '');

     validateName(options.name);
     validateHtmlSelector(options.selector);

     const templateSource = apply(url('./files'), [
       options.skipTests ? filter((path) => !path.endsWith('.spec.ts.template')) : noop(),
       applyTemplates({
         ...strings,
         'if-flat': (s: string) => (options.flat ? '' : s),
         ...options,
       }),
       !options.type
         ? forEach(((file) => {
             return file.path.includes('..')
               ? {
                   content: file.content,
                   path: file.path.replace('..', '.'),
                 }
               : file;
           }) as FileOperator)
         : noop(),
       move(parsedPath.path),
     ]);

     return chain([
       addDeclarationToNgModule(options),
       mergeWith(templateSource),
       options.lintFix ? applyLintFix(options.path) : noop(),
     ]);
   };
 }
Example #22
Source File: index.ts    From angular-git-info with MIT License 5 votes vote down vote up
function addVersionGeneratorFile(): Rule {
    return (tree: Tree, context: SchematicContext) => {
        context.logger.debug('adding file to host dir');

        return chain([mergeWith(apply(url('./files'), [move('./')]))])(tree, context);
    };
}
Example #23
Source File: index.ts    From form-schematic with MIT License 5 votes vote down vote up
// You don't have to export the function as default. You can also have more than one rule factory
// per file.
export function forms(_options: OptionsFormSchema): Rule {
	return (tree: Tree, _context: SchematicContext) => {
		// Log
		// context.logger.info('Info message');
		// context.logger.warn('Warn message');
		// context.logger.error('Error message');
		const workspaceConfig = tree.read('/angular.json');

		if (!workspaceConfig) {
			throw new NotValidAngularWorkspace();
		}

		const workspaceContent = workspaceConfig.toString();

		const workspace: workspace.WorkspaceSchema = JSON.parse(
			workspaceContent
		);

		if (!_options.project) {
			_options.project = workspace.defaultProject || '';
		}

		const projectName = _options.project;
		const project = workspace.projects[projectName];

		const jsonFormConfig = tree.read(`${_options.config}`);

		if (!jsonFormConfig) {
			throw new FormJsonNotFoundError();
		}

		const jsonFormContent = jsonFormConfig.toString();

		const formJsonObj = new FormJson(JSON.parse(jsonFormContent));

		const projectType =
			project.projectType === 'application'
				? ProjetTypeEnum.APP
				: ProjetTypeEnum.LIB;

		if (!_options.path) {
			_options.path = `${project.sourceRoot}/${projectType}`;
		}
		const parsedOptions = parseName(_options.path, _options.name);
		_options = { ..._options, ...parsedOptions };

		const templateSource = apply(url('./templates/forms'), [
			renameTemplateFiles(),
			template({
				...strings,
				..._options,
				formJsonObj
			}),
			move(normalize((_options.path + '/' + _options.name) as string))
		]);

		return chain([
			branchAndMerge(chain([mergeWith(templateSource)])),
			addTreeModulesToModule(_options),
			addDeclarationsToModule(_options)
		])(tree, _context);
	};
}
Example #24
Source File: index.ts    From source-map-analyzer with MIT License 5 votes vote down vote up
export function ngAdd(options: NgAddOptions): Rule {
    return async (host: Tree) => {
        const workspace = await getWorkspace(host);

        // Get project name 
        if (!options.project) {
            if (workspace.extensions.defaultProject) {
                options.project = workspace.extensions.defaultProject as string;
            } else {
                throw new SchematicsException(
                    'No Angular project selected and no default project in the workspace'
                );
            }
        }

        // Validating project name
        const project = workspace.projects.get(options.project);
        if (!project) {
            throw new SchematicsException(`The specified Angular project is not defined in this workspace`);
        }

        // Checking if it is application
        if (project.extensions['projectType'] !== 'application') {
            throw new SchematicsException(`source-map-analyzer requires an Angular project type of "application" in angular.json`);
        }
        
        const outputPath: string | undefined = project.targets.get('build')?.options?.outputPath as string;

        if (!outputPath) {
            const message: string = `Cannot read the output path(architect.build.options.outputPath) of the Angular project "${options.project}" in angular.json`;
            throw new SchematicsException(message);
        }

        var targetDefinition: TargetDefinition = {
            builder: "@ngx-builders/analyze:analyze",
            options: {
                outputPath: outputPath
            }
        }

        project.targets.add({ name: 'analyze', ...targetDefinition });

        return chain([updateWorkspace(workspace)]);
    };
}
Example #25
Source File: index.ts    From edit-in-place with MIT License 5 votes vote down vote up
export function addImportsToModuleDeclaration(options: SchemaOptions, imports: string[]): Rule {
  return host => {
    const module = getModuleFile(host, options);

    const importChanges = imports.map(imp => addImportToModule(module, options.module, imp, LIB_NAME)[0]);
    return applyChanges(host, options.module, importChanges as InsertChange[]);
  };
}
Example #26
Source File: index.ts    From open-source with MIT License 5 votes vote down vote up
export default function (options: ModuleOptions): Rule {
  return async (host: Tree) => {
    const workspace = await getWorkspace(host);
    const project = workspace.projects.get(options.project as string);

    if (options.path === undefined) {
      options.path = await createDefaultPath(host, options.project as string);
    }

    if (options.module) {
      options.module = findModuleFromOptions(host, options);
    }

    if (options.prefix === undefined) {
      options.prefix = project?.prefix || '';
    }

    const parsedPath = parseName(options.path, options.name);
    options.name = parsedPath.name;
    options.path = parsedPath.path;

    const templateSource = apply(url('./files'), [
      applyTemplates({
        ...strings,
        'if-flat': (s: string) => (options.flat ? '' : s),
        ...options,
      }),
      move(parsedPath.path),
    ]);
    const moduleDasherized = strings.dasherize(options.name);
    const controlDasherized = strings.dasherize(options.controlName);
    const controlPath = `${options.path}/${
      !options.flat ? `${moduleDasherized}/` : ''
    }${options.controlPath}${options.flat ? `/${controlDasherized}` : ''}`;

    const controlOptions: ControlOptions = {
      project: options.project,
      path: controlPath,
      name: controlDasherized,
      type: options.type,
      id: options.id || 'CONTROL',
      instance: options.instance || 'Control',
      flat: options.flat,
      prefix: options.prefix,
      prefixInterface: options.prefixInterface,
      prefixClass: options.prefixClass,
    };

    return chain([
      mergeWith(templateSource),
      schematic('control', controlOptions),
      options.lintFix ? applyLintFix(options.path) : noop(),
    ]);
  };
}
Example #27
Source File: index.ts    From elements with MIT License 5 votes vote down vote up
export function ngAdd(): Rule {
  return chain([
    addIcons(),
    // install freshly added dependencies
    installNodeDeps(),
  ]);
}
Example #28
Source File: index.ts    From open-source with MIT License 5 votes vote down vote up
function addDeclarationToNgModule(options: ComponentOptions): Rule {
   return (host: Tree) => {
     if (!options.module) {
       return host;
     }

     options.type = options.type != null ? options.type : 'Component';

     const modulePath = options.module;
     const source = readIntoSourceFile(host, modulePath);

     const componentPath =
       `/${options.path}/` +
       (options.flat ? '' : strings.dasherize(options.name) + '/') +
       strings.dasherize(options.name) +
       (options.type ? '.' : '') +
       strings.dasherize(options.type);
     const relativePath = buildRelativePath(modulePath, componentPath);
     const classifiedName = strings.classify(options.prefix!) + strings.classify(options.name) + strings.classify(options.type);
     const declarationChanges = addDeclarationToModule(
       source,
       modulePath,
       classifiedName,
       relativePath,
     );

     const declarationRecorder = host.beginUpdate(modulePath);
     for (const change of declarationChanges) {
       if (change instanceof InsertChange) {
         declarationRecorder.insertLeft(change.pos, change.toAdd);
       }
     }
     host.commitUpdate(declarationRecorder);

     if (options.export) {
       // Need to refresh the AST because we overwrote the file in the host.
       const source = readIntoSourceFile(host, modulePath);

       const exportRecorder = host.beginUpdate(modulePath);
       const exportChanges = addExportToModule(
         source,
         modulePath,
         strings.classify(options.name) + strings.classify(options.type),
         relativePath,
       );

       for (const change of exportChanges) {
         if (change instanceof InsertChange) {
           exportRecorder.insertLeft(change.pos, change.toAdd);
         }
       }
       host.commitUpdate(exportRecorder);
     }

     return host;
   };
 }
Example #29
Source File: addProjectToGarmentJson.ts    From garment with MIT License 5 votes vote down vote up
export function addProjectToGarmentJson(options: {
  garmentJsonPath: string;
  name: string;
  path: string;
  extendProjects?: string[];
}): Rule {
  const { garmentJsonPath, name, path, extendProjects } = options;
  return (tree: Tree) => {
    const garmentJsonContent = tree.read(garmentJsonPath);
    if (!garmentJsonContent) {
      throw new Error(`"${garmentJsonPath}" is not found`);
    }
    const garmentJson: Config = JSON.parse(
      garmentJsonContent.toString('utf-8')
    );

    const project: { path: string; extends?: string[] } = {
      path
    };
    if (extendProjects) {
      project.extends = extendProjects;
    }

    garmentJson.projects = {
      ...garmentJson.projects,
      [name]: project
    };

    const sortedProjects: { [key: string]: ProjectConfig } = {};
    Array.from(Object.entries<{ path: string }>(garmentJson.projects))
      .sort(([, { path: pathA }], [, { path: pathB }]) =>
        pathA < pathB ? -1 : pathA > pathB ? 1 : 0
      )
      .forEach(([key, value]) => {
        sortedProjects[key] = value;
      });

    garmentJson.projects = sortedProjects;

    tree.overwrite(
      garmentJsonPath,
      prettier.format(JSON.stringify(garmentJson, null, 2), {
        parser: 'json'
      })
    );
  };
}