@angular-devkit/schematics#SchematicsException TypeScript Examples

The following examples show how to use @angular-devkit/schematics#SchematicsException. 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: 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 #2
Source File: util.ts    From angular-git-info with MIT License 7 votes vote down vote up
export function parseJsonAtPath(tree: Tree, path: string): JsonAstObject {
    const buffer = tree.read(path);

    if (buffer === null) {
        throw new SchematicsException('Could not read package.json.');
    }

    const content = buffer.toString();

    const json = parseJsonAst(content, JsonParseMode.Strict);
    if (json.kind != 'object') {
        throw new SchematicsException(
            'Invalid package.json. Was expecting an object'
        );
    }

    return json;
}
Example #3
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 #4
Source File: utils.ts    From elements with MIT License 7 votes vote down vote up
export function getAngularAppConfig(
  config: any,
  projectName: string
): any | never {
  if (!config.projects.hasOwnProperty(projectName)) {
    throw new SchematicsException(`Could not find project: ${projectName}`);
  }

  return config.projects[projectName];
}
Example #5
Source File: config.ts    From router with MIT License 6 votes vote down vote up
export function getWorkspace(host: Tree): WorkspaceSchema {
  const path = getWorkspacePath(host);
  const configBuffer = host.read(path);
  if (configBuffer === null) {
    throw new SchematicsException(`Could not find (${path})`);
  }
  const config = configBuffer.toString();

  return JSON.parse(config);
}
Example #6
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 #7
Source File: file.ts    From form-schematic with MIT License 6 votes vote down vote up
readIntoSourceFile = (host: Tree, modulePath: string) => {
	const text = host.read(modulePath);
	if (text === null) {
		throw new SchematicsException(`File ${modulePath} does not exist.`);
	}

	return ts.createSourceFile(
		modulePath,
		text.toString('utf-8'),
		ts.ScriptTarget.Latest,
		true
	);
}
Example #8
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 #9
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 #10
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 #11
Source File: projects.ts    From edit-in-place with MIT License 6 votes vote down vote up
export function getWorkspace(host: Tree): WorkspaceSchema {
  const path = getWorkspacePath(host);
  const configBuffer = host.read(path);
  if (configBuffer === null) {
    throw new SchematicsException(`Could not find (${path})`);
  }
  const config = configBuffer.toString();

  return JSON.parse(config);
}
Example #12
Source File: projects.ts    From edit-in-place with MIT License 6 votes vote down vote up
export function getProject(host: Tree, project?: string): any {
  const workspace = getWorkspace(host);
  if (workspace) {
    // @ts-ignore
    return workspace.projects[project || workspace.defaultProject];
  }

  throw new SchematicsException('could not find a workspace project');
}
Example #13
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 #14
Source File: index.ts    From router with MIT License 5 votes vote down vote up
function addImportToNgModule(options: RouterOptions): Rule {
  return (host: Tree) => {
    options.path = getProjectPath(host, options);
    const modulePath = findModuleFromOptions(host, options);

    if (!modulePath) {
      return host;
    }

    if (!host.exists(modulePath)) {
      throw new Error('Specified module 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');

    const source = ts.createSourceFile(
      modulePath,
      sourceText,
      ts.ScriptTarget.Latest,
      true
    );

    const importChanges = addImportToModule(
      source,
      modulePath,
      'ComponentRouterModule.forRoot()',
      '@angular-component/router'
    ).shift();

    const changes = [
      insertImport(
        source,
        modulePath,
        'ComponentRouterModule',
        '@angular-component/router'
      ),
      importChanges,
    ];

    commitChanges(host, source.fileName, changes as Change[]);

    return host;
  };
}
Example #15
Source File: index.ts    From ng-ant-admin with MIT License 5 votes vote down vote up
function readIntoSourceFile(host: Tree, modulePath: string): any {
    const text = host.read(modulePath);
    if (text === null) {
        throw new SchematicsException(`File ${modulePath} does not exist.`);
    }

    return ts.createSourceFile(modulePath, text.toString('utf-8'), ts.ScriptTarget.Latest, true);
}
Example #16
Source File: index.ts    From garment with MIT License 5 votes vote down vote up
export default function(options: PackageSchematicOptions): Rule {
  return (tree: Tree, context: SchematicContext) => {
    const { name, directory } = options;
    if (!options.name) {
      throw new SchematicsException('name option is required.');
    }
    if (!tree.getDir('.').subdirs.includes(directory as any)) {
      throw new SchematicsException(`Directory "${directory}" doesn't exist`);
    }

    const dashedName = strings.dasherize(name);
    const packagePath = Path.join(directory, dashedName);

    context.addTask(
      new NodePackageInstallTask({
        workingDirectory: packagePath,
        packageManager: 'yarn'
      })
    );

    let source = apply(url('../../templates/package'), [
      applyTemplates({
        packageName: dashedName,
        dot: '.',
        camelize: strings.camelize,
        dasherize: strings.dasherize
      }),
      move(packagePath)
    ]);

    return chain([
      mergeWith(source),
      addProjectToGarmentJson({
        garmentJsonPath: '/garment.json',
        name: dashedName,
        path: packagePath,
        extendProjects: ['tspackage']
      })
    ]);
  };
}
Example #17
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 #18
Source File: index.ts    From garment with MIT License 5 votes vote down vote up
export default function(options: PackageSchematicOptions): Rule {
  return (_tree: Tree, context: SchematicContext) => {
    const { name } = options;

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

    const directory = 'plugins';

    const dashedName = strings.dasherize(name);
    const projectName = 'runner-' + dashedName;

    const packagePath = Path.join(directory, projectName);

    context.addTask(
      new NodePackageInstallTask({
        workingDirectory: packagePath,
        packageManager: 'yarn'
      })
    );

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

    return chain([
      mergeWith(source),
      addPackageJsonDependencies(
        `${packagePath}/package.json`,
        'core/runner/package.json',
        'utils/fixture-helper/package.json'
      ),
      addProjectToGarmentJson({
        garmentJsonPath: '/garment.json',
        name: projectName,
        path: packagePath,
        extendProjects: ['tspackage', 'copy-other-files']
      })
    ]);
  };
}
Example #19
Source File: index.ts    From garment with MIT License 5 votes vote down vote up
export default function(options: Options): Rule {
  return (_tree: Tree, context: SchematicContext) => {
    const { name } = options;
    if (!options.name) {
      throw new SchematicsException('name option is required.');
    }

    const directory = 'plugins';

    const dashedName = strings.dasherize(name);
    const projectName = dashedName;

    context.logger.info(`Creating project called "${projectName}"...`);

    const packagePath = Path.join(directory, projectName);

    context.addTask(
      new NodePackageInstallTask({
        workingDirectory: packagePath,
        packageManager: 'yarn'
      })
    );

    let source = apply(url('../../templates/plugin'), [
      applyTemplates({
        name,
        ...strings
      }),
      move(packagePath)
    ]);

    return chain([
      mergeWith(source),
      addPackageJsonDependencies(
        `${packagePath}/package.json`,
        'core/workspace/package.json'
      ),
      addProjectToGarmentJson({
        garmentJsonPath: '/garment.json',
        name: projectName,
        path: packagePath,
        extendProjects: ['tspackage']
      })
    ]);
  };
}