@angular-devkit/schematics#SchematicContext TypeScript Examples

The following examples show how to use @angular-devkit/schematics#SchematicContext. 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: util.ts    From angular-git-info with MIT License 7 votes vote down vote up
export function addPropertyToGitignore(tree: Tree, _context: SchematicContext, file: string) {
    if (tree.exists(GIT_IGNORE_FILE)) {
        const buffer = tree.read(GIT_IGNORE_FILE);
        if (buffer === null) {
            throw new SchematicsException(`Could not read .gitignore`);
        }

        const content = buffer.toString();
        _context.logger.debug('gitignore content' + content);

        const updatedContent = `${content}\n${file}`;

        tree.overwrite(GIT_IGNORE_FILE, updatedContent);
    } else {
        _context.logger.debug('no gitignore found');
    }
}
Example #2
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
// 生成路由代码
export default function (_options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    return chain([
      async () => {
        // 读取文件
        let tsFile = tree.read('src/app/layout/default/default-routing.module.ts')?.toString()!;
        // 转换成抽象语法树
        // let ast = ts.createSourceFile('default-routing.module', tsFile, ScriptTarget.Latest)
        let selector = createCssSelectorForTs(tsFile)
        let result = selector.queryOne(`SourceFile VariableStatement VariableDeclarationList VariableDeclaration ArrayLiteralExpression ObjectLiteralExpression PropertyAssignment ArrayLiteralExpression ObjectLiteralExpression`) as (ts.ObjectLiteralExpression);
        let recorder = tree.beginUpdate('src/app/layout/default/default-routing.module.ts');
        recorder.insertLeft(result.pos, `
      {
        path: '${dasherize(_options.name)}',
        loadChildren: () => import('../../pages/${dasherize(_options.name)}/${dasherize(_options.name)}.module').then(m => m.${classify(_options.name)}Module)
      },`);
        await tree.commitUpdate(recorder);
      }
    ]);
  };
}
Example #3
Source File: index.ts    From cli with Apache License 2.0 6 votes vote down vote up
export default function (options: CoveoSchema): Rule {
  return async (tree: Tree, _context: SchematicContext) => {
    const workspace = await getWorkspace(tree);
    const project = getProjectFromWorkspace(workspace, options.project);

    if (project.extensions.projectType === ProjectType.Application) {
      return chain([
        createServerDirectory(options),
        createFiles(options),
        installServerDependencies(options),
      ]);
    }
    return;
  };
}
Example #4
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 #5
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
function twoLevelRule(_options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        let source = apply(url(`./files/src/app/pages`), [move(`./src/app/pages/${_options.mName}`), applyTemplates({
            ...strings,
            ..._options, // 使用者所輸入的參數
        })]);
        return chain([
            mergeWith(source),
            schematic('b-s', {dirname: _options.mName, filename: _options.name},),
            schematic('b-m', {name: _options.name, isTwoLevel: true},),
            move(`./src/app/pages/${_options.name}`, `./src/app/pages/${_options.mName}/${_options.name}`),
            schematic('component-lazy-m', {mName: _options.mName, name: _options.name},),
        ])
    };

}
Example #6
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
export default function (_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 ng-ant-admin with MIT License 6 votes vote down vote up
export default function (_options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const sourceTemplates = url('./files'); // 使用範本
    const sourceParametrizedTemplates = apply(sourceTemplates, [
      // renameTemplateFiles(), // 去掉后缀
      applyTemplates({
        ...strings,
        ..._options, // 使用者所輸入的參數
      })
    ]);
    return mergeWith(sourceParametrizedTemplates);
  };
}
Example #8
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
export default function (_options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const sourceTemplates = url('./files'); // 使用範本
    const sourceParametrizedTemplates = apply(sourceTemplates, [
      // renameTemplateFiles(), // 去掉后缀
      applyTemplates({
        ...strings,
        ..._options, // 使用者所輸入的參數
      })
    ]);
    return mergeWith(sourceParametrizedTemplates);
  };
}
Example #9
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
export default function (_options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        return chain([
            async () => {
                let path = "";
                // 是一级菜单
                if (_options.mName === _options.name) {
                    path = `src/app/pages/${dasherize(_options.mName)}/${dasherize(_options.mName)}-routing.module.ts`;
                } else {
                    path = `src/app/pages/${dasherize(_options.mName)}/${dasherize(_options.name)}/${dasherize(_options.name)}-routing.module.ts`;

                }
                // 读取文件
                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 VariableStatement VariableDeclarationList VariableDeclaration ArrayLiteralExpression ObjectLiteralExpression
`) as (ts.ObjectLiteralExpression);
                let recorder = tree.beginUpdate(path);
                recorder.remove(result.pos,result.end-result.pos);
                recorder.insertRight(result.pos, `
  {path: '', component: ${classify(_options.name)}Component, data: {title: '${_options.title}', key: '${dasherize(_options.name)}'}}`);
                await tree.commitUpdate(recorder);
            }
        ]);
    };
}
Example #10
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
export default function (_options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        /*是二级菜单*/
        if (_options.isTwoLevel == true) {
            return chain([
                schematic('layout-lazy-m', {name: _options.name}),
                schematic('b-m', {name: _options.name, isTwoLevel: false}),
                generTwoLevelModuleRoute(_options, tree),
                // schematic('component-lazy-m', {name: _options.name, isTwoLevel: false}),
            ]);
        } else {
            /*一级菜单*/
            return chain([
                /* 添加default-routing.module.ts 路由*/
                schematic('layout-lazy-m', {name: _options.name}),
                schematic('b-s', {dirname: _options.name, filename: _options.name}),
                schematic('b-m', {name: _options.name, isTwoLevel: false}),
                schematic('b-c', {name: _options.name, mName: _options.name}),
                fnGenerateImport(_options.name, `src/app/pages/${dasherize(_options.name)}/${dasherize(_options.name)}-routing.module.ts`, tree)
            ]);
        }
    };
}
Example #11
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 #12
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 #13
Source File: index.ts    From angular-git-info with MIT License 6 votes vote down vote up
export function gitInfo(): Rule {
    return (tree: Tree, context: SchematicContext) => {
        return chain([
            updateDependencies(),
            addVersionGeneratorFile(),
            addVersionGeneratorToGitignore(),
            addScriptsToPackageJson(),
        ])(tree, context);
    };
}
Example #14
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 #15
Source File: util.ts    From angular-git-info with MIT License 6 votes vote down vote up
export function addPropertyToPackageJson(
    tree: Tree,
    context: SchematicContext,
    propertyName: string,
    propertyValue: { [key: string]: any }
) {
    const packageJsonAst = parseJsonAtPath(tree, pkgJson.Path);
    const pkgNode = findPropertyInAstObject(packageJsonAst, propertyName);
    const recorder = tree.beginUpdate(pkgJson.Path);

    if (!pkgNode) {
        // outer node missing, add key/value
        appendPropertyInAstObject(
            recorder,
            packageJsonAst,
            propertyName,
            propertyValue,
            Configs.JsonIndentLevel
        );
    } else if (pkgNode.kind === 'object') {
        // property exists, update values
        for (let [key, value] of Object.entries(propertyValue)) {
            const innerNode = findPropertyInAstObject(pkgNode, key);

            if (!innerNode) {
                // script not found, add it
                context.logger.debug(`creating ${key} with ${value}`);

                insertPropertyInAstObjectInOrder(
                    recorder,
                    pkgNode,
                    key,
                    value,
                    Configs.JsonIndentLevel
                );
            } else {
                // script found, overwrite value
                context.logger.debug(`overwriting ${key} with ${value}`);

                const {end, start} = innerNode;

                recorder.remove(start.offset, end.offset - start.offset);
                recorder.insertRight(start.offset, JSON.stringify(value));
            }
        }
    }

    tree.commitUpdate(recorder);
}
Example #16
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export default function (options: CommonHookOptions) {
  options.schematicPath = __dirname;
  return (tree: Tree, context: SchematicContext) => {
    return chain([
      getAngularSubDirRuleFactory(options),
      mergeSourceRuleFactory(options),
      changeStructuralDirectiveRuleFactory(options),
      removeNgComponentOutletRuleFactory(),
      removeI18nRuleFactory(),
      forEach((entry) => {
        if (
          entry.path.startsWith('/src/library/common') &&
          entry.path.endsWith('.ts')
        ) {
          return {
            content: Buffer.from(
              entry.content
                .toString()
                .replace(/@angular\/common/g, `angular-miniprogram/common`)
            ),
            path: entry.path,
          };
        }
        return entry;
      }),
    ]);
  };
}
Example #17
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export default function (options: FormsHookOptions) {
  options.schematicPath = __dirname;
  return (tree: Tree, context: SchematicContext) => {
    return chain([
      getAngularSubDirRuleFactory(options),
      mergeSourceRuleFactory(options),
    ]);
  };
}
Example #18
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 #19
Source File: start.ts    From cli with Apache License 2.0 6 votes vote down vote up
/**
 * Create a npm script in the project root to start both the Angular app and the search token server
 */
export function configureStartCommand(_options: CoveoSchema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const packageJsonBuffer = tree.read(normalize('./package.json'));
    if (packageJsonBuffer === null) {
      return;
    }

    try {
      const packageJson = JSON.parse(packageJsonBuffer.toString());

      packageJson.scripts['allocate-port'] =
        'node ./scripts/port-allocator.mjs';
      packageJson.scripts['start'] =
        'npm run allocate-port && concurrently --raw "npm run start-server" "ng serve"';
      packageJson.scripts['start-server'] = 'node ./scripts/start-server.js';

      tree.overwrite(
        normalize('./package.json'),
        JSON.stringify(packageJson, null, 4)
      );
    } catch (error) {
      console.error(
        'Something wrong happened while reading the package.json',
        error
      );
    }
  };
}
Example #20
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
function generateInfrastructureCode(adapter: BaseAdapter) {
  return (host: Tree, context: SchematicContext) => {
    const template = adapter.getApplicationTypeTemplate();
    if (!template) {
      throw new Error(`Can't find a supported build target for the project`);
    }
    const templateSource = apply(
      url(`./files/${adapter.getApplicationTemplatePath()}`),
      [template, move(join(adapter.project.root))]
    );

    const rule = chain([branchAndMerge(chain([mergeWith(templateSource)]))]);
    return rule(host, context);
  };
}
Example #21
Source File: index.ts    From fab-menu with MIT License 6 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 addPackageJsonDependencies(): Rule {
  return (host: Tree, context: SchematicContext) => {

    const dependencies: NodeDependency[] = [
      {
        type: NodeDependencyType.Default, version: loadPackageVersionGracefully()
          || '1.4.0', name: '@angular-material-extensions/fab-menu'
      },
    ];

    dependencies.forEach(dependency => {
      addPackageJsonDependency(host, dependency);
      context.logger.log('info', `✅️ Added "${dependency.name}" into ${dependency.type}`);
    });

    return host;
  };
}
Example #22
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 #23
Source File: index.ts    From fab-menu with MIT License 6 votes vote down vote up
function addLibAssetsToAssets(options: any) {
  return (host: Tree, context: SchematicContext) => {
    const lib = '@angular-material-extensions/fab-menu';
    const assetPath = 'node_modules/svg-country-flags/svg';

    try {
      const angularJsonFile = host.read('angular.json');

      if (angularJsonFile) {
        const angularJsonFileObject = JSON.parse(angularJsonFile.toString('utf-8'));
        const project = options.project ? options.project : Object.keys(angularJsonFileObject.projects)[0];
        const projectObject = angularJsonFileObject.projects[project];
        const assets = projectObject.architect.build.options.assets;
        context.logger.log('info', `"${assets}`);

        assets.push({
          glob: '**/*',
          input: assetPath,
          output: 'assets/svg-country-flags/svg'
        });
        host.overwrite('angular.json', JSON.stringify(angularJsonFileObject, null, 2));
        context.logger.log('info', `✅️ Added "${lib}" icons to assets`);
      }
    } catch (e) {
      context.logger.log('error', `? Failed to add the icons "${lib}" to assets`);
      context.logger.log('error', e);
    }

    return host;
  };
}
Example #24
Source File: index.ts    From ngx-electronify with MIT License 6 votes vote down vote up
ngAdd =
  (options: NgAddOptions) => async (tree: Tree, _context: SchematicContext) => {
    const { host, workspace } = await getWorkspace(tree);
    const project = workspace.projects.get(options.project);

    if (!project) {
      throw new SchematicsException(
        'The specified Angular project is not defined in this workspace.'
      );
    }

    if (project.extensions.projectType !== 'application') {
      throw new SchematicsException(
        `ngx-electronify requires an Angular project type of "application" in angular.json.`
      );
    }

    // add a new architect entry in the angular.json file of the current project
    project.targets.add({
      name: 'desktop',
      builder: 'ngx-electronify:electron',
      options: {}
    });

    await workspaces.writeWorkspace(workspace, host);
    return tree;
  }
Example #25
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 #26
Source File: tsconfig.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function updateTsConfig(_options: CoveoSchema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const tsconfigBuffer = tree.read(normalize('./tsconfig.json'));
    if (tsconfigBuffer === null) {
      return;
    }
    try {
      const originalTsConfig = tsconfigBuffer.toString();
      const tsConfigComment =
        originalTsConfig.match(commentRegExp)?.[0]?.trim() ?? '';
      const tsConfig = JSON.parse(
        originalTsConfig.replace(commentRegExp, '').trim()
      );

      tsConfig.compilerOptions.skipLibCheck = true;
      tree.overwrite(
        normalize('./tsconfig.json'),
        `${tsConfigComment}
${JSON.stringify(tsConfig, null, 4)}`
      );
    } catch (error) {
      console.error(
        `Unable to update the Angular tsconfig.json file by adding the "allowSyntheticDefaultImports" flag.
Make sure to add this flag to your tsconfig.json. Otherwise, you might experience errors when running the app`,
        error
      );
    }
  };
}
Example #27
Source File: index.ts    From cli with Apache License 2.0 6 votes vote down vote up
export default function (options: CoveoSchema): Rule {
  return async (tree: Tree, context: SchematicContext) => {
    const workspace = await getWorkspace(tree);
    const project = getProjectFromWorkspace(workspace, options.project);

    if (project.extensions.projectType === ProjectType.Application) {
      const dependencyInstallationTaskId = context.addTask(
        new RunSchematicTask('install-project-dependencies', options)
      );
      const setupProjectTaskId = context.addTask(
        new RunSchematicTask('ng-add-setup-project', options),
        [dependencyInstallationTaskId]
      );
      context.addTask(new RunSchematicTask('search-token-server', options), [
        setupProjectTaskId,
      ]);
    }
    return;
  };
}
Example #28
Source File: dependencies.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function addToPackageJson(
  packageName: string,
  version = 'latest'
): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const packageToAdd: NodeDependency = {
      type: NodeDependencyType.Default,
      name: packageName,
      version,
      overwrite: true,
    };

    addPackageJsonDependency(tree, packageToAdd);
  };
}
Example #29
Source File: templates.ts    From cli with Apache License 2.0 6 votes vote down vote up
/**
 * Schematic rule that copies files into the Angular project.
 *
 * @export
 * @param {CoveoSchema} _options
 * @param {string} [workspaceRootPath='./']      The root path from which the applyTemplates function will start pasting files.
 *                                               The default value is "./" because the file structure is already defined within the ./files directories
 * @param {string} [templateFilePath='./files']  Path containing the files to copy into the Angular project
 * @returns {Rule}
 */
export function createFiles(
  _options: CoveoSchema,
  workspaceRootPath = './',
  templateFilePath = './files',
  customFilter = isNotNodeModuleFile
): Rule {
  return (tree: Tree, context: SchematicContext) => {
    const templateSource = apply(url(templateFilePath), [
      filter(customFilter),
      applyTemplates({
        ..._options,
      }),
      move(normalize(workspaceRootPath)),
      overwriteIfExists(tree),
    ]);

    const rule = mergeWith(templateSource);
    return rule(tree, context);
  };
}