@angular-devkit/schematics#Tree TypeScript Examples

The following examples show how to use @angular-devkit/schematics#Tree. 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: app.utils.ts    From nx-plugins with MIT License 7 votes vote down vote up
export function createApplication(
  testRunner: SchematicTestRunner,
  projectName: string,
  applicationType: 'nest' | 'express' | 'angular' | 'react',
  tree: Tree
) {
  return testRunner
    .runExternalSchematicAsync(
      `@nrwl/${applicationType}`,
      'application',
      {
        name: projectName
      },
      tree
    )
    .toPromise();
}
Example #2
Source File: utility.ts    From ngx-electronify with MIT License 7 votes vote down vote up
function createHost(tree: Tree): workspaces.WorkspaceHost {
  return {
    async readFile(path: string): Promise<string> {
      const data = tree.read(path);
      if (!data) {
        throw new Error('File not found.');
      }

      return virtualFs.fileBufferToString(data);
    },
    async writeFile(path: string, data: string): Promise<void> {
      return tree.overwrite(path, data);
    },
    async isDirectory(path: string): Promise<boolean> {
      // approximate a directory check
      return !tree.exists(path) && tree.getDir(path).subfiles.length > 0;
    },
    async isFile(path: string): Promise<boolean> {
      return tree.exists(path);
    }
  };
}
Example #3
Source File: utils.ts    From elements with MIT License 7 votes vote down vote up
function createHost(tree: Tree): workspaces.WorkspaceHost {
  return {
    async readFile(path: string): Promise<string> {
      const data = tree.read(path);
      if (!data) {
        throw new SchematicsException('File not found.');
      }
      return virtualFs.fileBufferToString(data);
    },
    async writeFile(path: string, data: string): Promise<void> {
      return tree.overwrite(path, data);
    },
    async isDirectory(path: string): Promise<boolean> {
      return !tree.exists(path) && tree.getDir(path).subfiles.length > 0;
    },
    async isFile(path: string): Promise<boolean> {
      return tree.exists(path);
    },
  };
}
Example #4
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 #5
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
function mergePulumiProjectIntoTree(adapter: BaseAdapter) {
  return (host: Tree) => {
    const infraDir = join(adapter.project.root, 'infrastructure');

    const PulumiFile = join(infraDir, 'Pulumi.yaml');
    const pulumiContent = readFileSync(PulumiFile);
    unlinkSync(PulumiFile);
    host.create(PulumiFile, pulumiContent);

    return host;
  };
}
Example #6
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
export default function(options: PackageSchematicOptions): Rule {
  return (_tree: Tree) => {
    let { projectName } = options;

    if (!projectName) {
      throw new SchematicsException('projectName option is required.');
    }

    const { projects } = readJson(_tree, 'garment.json');

    if (!projects[projectName]) {
      throw new SchematicsException(
        `Couldn't find project ${projectName} in garment.json`
      );
    }

    const packagePath = projects[projectName].path;

    let source = apply(url('../../templates/runner/__tests__'), [
      applyTemplates(
        {
          dot: '.',
          ...strings
        },
        { interpolationStart: '___', interpolationEnd: '___' }
      ),
      move(Path.join(packagePath, '__tests__'))
    ]);

    return chain([
      mergeWith(source),
      addPackageJsonDependencies(
        `${packagePath}/package.json`,
        'utils/fixture-helper/package.json'
      )
    ]);
  };
}
Example #7
Source File: change.ts    From router with MIT License 6 votes vote down vote up
export function createChangeRecorder(
  tree: Tree,
  path: string,
  changes: Change[]
): UpdateRecorder {
  const recorder = tree.beginUpdate(path);
  for (const change of changes) {
    if (change instanceof InsertChange) {
      recorder.insertLeft(change.pos, change.toAdd);
    } else if (change instanceof RemoveChange) {
      recorder.remove(change.pos, change.end - change.pos);
    } else if (change instanceof ReplaceChange) {
      recorder.remove(change.pos, change.oldText.length);
      recorder.insertLeft(change.pos, change.newText);
    }
  }
  return recorder;
}
Example #8
Source File: find-module.ts    From fab-menu with MIT License 6 votes vote down vote up
/**
 * Function to find the "closest" module to a generated file's path.
 */
export function findModule(
  host: Tree,
  generateDir: string,
  moduleExt = MODULE_EXT,
  routingModuleExt = ROUTING_MODULE_EXT
): Path {
  return originalFindModule(host, generateDir, moduleExt, routingModuleExt);
}
Example #9
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 #10
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 #11
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 #12
Source File: index.ts    From form-schematic with MIT License 6 votes vote down vote up
function addTreeModulesToModule(options: any) {
	return (host: Tree) => {
		const modulePath = findModuleFromOptions(host, options)!;
		addModuleImportToModule(
			host,
			modulePath,
			'ReactiveFormsModule',
			'@angular/forms'
		);
		addModuleImportToModule(
			host,
			modulePath,
			'FormsModule',
			'@angular/forms'
		);
		addModuleImportToModule(
			host,
			modulePath,
			'NgbModule',
			'@ng-bootstrap/ng-bootstrap'
		);

		return host;
	};
}
Example #13
Source File: index.ts    From elements with MIT License 6 votes vote down vote up
function addAsset(
  host: Tree,
  projectName: string,
  architect: string,
  asset: string | { glob: string; input: string; output: string }
) {
  const config = readConfig(host);
  const appConfig = getAngularAppConfig(config, projectName);

  const targetConfig = appConfig.architect[architect];

  // use process.stdout in order to write in the same line
  process.stdout.write(
    `Adding the ino-icons to ${projectName}/architect/${architect} in your angular.json ... `
  );

  if (!targetConfig) {
    process.stdout.write('Not found. Skipping.\n');
    return;
  }

  targetConfig.options.assets.push(asset);
  writeConfig(host, config);
  process.stdout.write('Done.\n');
}
Example #14
Source File: index.ts    From open-source with MIT License 6 votes vote down vote up
function readIntoSourceFile(host: Tree, modulePath: string): ts.SourceFile {
   const text = host.read(modulePath);
   if (text === null) {
     throw new SchematicsException(`File ${modulePath} does not exist.`);
   }
   const sourceText = text.toString('utf-8');

   return ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
 }
Example #15
Source File: index.ts    From edit-in-place with MIT License 6 votes vote down vote up
export function getModuleFile(host: Tree, options: SchemaOptions): SourceFile {
  const modulePath = options.module;

  if (!host.exists(modulePath)) {
    throw new SchematicsException(`File ${modulePath} does not exist.`);
  }

  const text = host.read(modulePath);
  if (text === null) {
    throw new SchematicsException(`File ${modulePath} does not exist.`);
  }
  const sourceText = text.toString('utf-8');

  return createSourceFile(modulePath, sourceText, ScriptTarget.Latest, true);
}
Example #16
Source File: workspace.ts    From source-map-analyzer with MIT License 6 votes vote down vote up
/* Below code reference is taken from Angular CLI project. 
  https://github.com/angular/angular-cli/blob/master/packages/schematics/angular/utility/workspace.ts

  These methods are not part of public APIs so we should not be referencing those methods.
  that's why added below method here.
*/

function createHost(tree: Tree): workspaces.WorkspaceHost {
    return {
        async readFile(path: string): Promise<string> {
            const data = tree.read(path);
            if (!data) {
                throw new SchematicsException('File not found.');
            }
            return virtualFs.fileBufferToString(data);
        },
        async writeFile(path: string, data: string): Promise<void> {
            return tree.overwrite(path, data);
        },
        async isDirectory(path: string): Promise<boolean> {
            return !tree.exists(path) && tree.getDir(path).subfiles.length > 0;
        },
        async isFile(path: string): Promise<boolean> {
            return tree.exists(path);
        },
    };
}
Example #17
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 #18
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 #19
Source File: schematic.ts    From nx-plugins with MIT License 5 votes vote down vote up
function addDependenciesFromPulumiProjectToPackageJson(
  adapter: BaseAdapter
): Rule {
  return (host: Tree): Rule => {
    const pulumiPackageJson = host.read(
      join(adapter.project.root, 'infrastructure', 'package.json')
    );
    if (!pulumiPackageJson) {
      throw new Error('Can not find generated pulumi package.json');
    }
    const pulumiCloudProviderDependencies = JSON.parse(
      pulumiPackageJson.toString()
    ).dependencies;
    const packageJson = readJsonInTree(host, 'package.json');
    const dependencyList: { name: string; version: string }[] = [];

    for (const name in pulumiCloudProviderDependencies) {
      const version = pulumiCloudProviderDependencies[name];
      if (version) {
        if (!packageJson.dependencies[name]) {
          dependencyList.push({
            name,
            version,
          });
        }
      }
    }

    dependencyList.push(...adapter.addRequiredDependencies());

    if (!dependencyList.length) {
      return noop();
    }

    return addDepsToPackageJson(
      dependencyList.reduce((dictionary, value) => {
        dictionary[value.name] = value.version;
        return dictionary;
      }, {}),
      {}
    );
  };
}
Example #20
Source File: index.ts    From garment with MIT License 5 votes vote down vote up
function addDependency(
  workspace: Workspace,
  projectName: string,
  depName: string,
  dev: boolean
) {
  const { projects } = workspace;

  let from: Project | undefined;
  let to: Project['nodePackage'];

  for (const project of projects) {
    const { nodePackage } = project;
    if (
      !from &&
      (project.name === projectName ||
        (nodePackage && nodePackage.name === projectName))
    ) {
      from = project;
    }
    if (
      !to &&
      (project.name === depName ||
        (nodePackage && nodePackage.name === depName))
    ) {
      if (!nodePackage) {
        throw new Error(`Dependency project "${depName}" is not node package`);
      }
      to = nodePackage;
    }
  }

  return (tree: Tree) => {
    if (!from) {
      throw new Error(`Couldn't find project "${projectName}"`);
    }
    if (!to) {
      throw new Error(`Couldn't find project "${depName}"`);
    }

    const depField = dev ? 'devDependencies' : 'dependencies';

    const packageJsonPath = Path.join(from.path, 'package.json');
    const packageJsonContent = tree.read(packageJsonPath)!.toString();
    const packageJson = JSON.parse(packageJsonContent);

    const dependencies = sortObject({
      ...(packageJson[depField] || {}),
      [to.name]: `^${to.version}`
    });

    packageJson[depField] = dependencies;

    tree.overwrite(packageJsonPath, JSON.stringify(packageJson, null, 2));
  };
}