it('should find a module', () => {
   tree.create('/projects/my-proj/src/app.module.ts', '');
   options.module = 'app.module.ts';
   options.path = '/projects/my-proj/src';
   const modPath = findModuleFromOptions(tree, options);
   expect(modPath).toEqual('/projects/my-proj/src/app.module.ts' as Path);
 });
 it('should find a module if nameFormatter is provided', () => {
   tree.create('/projects/my-proj/src/app_test.module.ts', '');
   options.path = '/projects/my-proj/src';
   options.nameFormatter = strings.underscore;
   const modPath = findModuleFromOptions(tree, options);
   expect(modPath).toEqual('/projects/my-proj/src/app_test.module.ts' as Path);
 });
Example #3
0
    it('should not overwrite existing custom theme files', () => {
      appTree.create('/projects/material/custom-theme.scss', 'custom-theme');
      const tree = runner.runSchematic('ng-add-setup-project', {theme: 'custom'}, appTree);

      expect(tree.readContent('/projects/material/custom-theme.scss')).toBe('custom-theme',
          'Expected the old custom theme content to be unchanged.');
    });
Example #4
0
  return (host: Tree, context: SchematicContext) => {
    const oldConfigPath = getConfigPath(host);
    const configPath = normalize('angular.json');
    context.logger.info(`Updating configuration`);
    const config: JsonObject = {
      '$schema': './node_modules/@angular/cli/lib/config/schema.json',
      version: 1,
      newProjectRoot: 'projects',
      projects: extractProjectsConfig(oldConfig, host, logger),
    };
    const defaultProject = extractDefaultProject(oldConfig);
    if (defaultProject !== null) {
      config.defaultProject = defaultProject;
    }
    const cliConfig = extractCliConfig(oldConfig);
    if (cliConfig !== null) {
      config.cli = cliConfig;
    }
    const schematicsConfig = extractSchematicsConfig(oldConfig);
    if (schematicsConfig !== null) {
      config.schematics = schematicsConfig;
    }
    const targetsConfig = extractTargetsConfig(oldConfig);
    if (targetsConfig !== null) {
      config.architect = targetsConfig;
    }

    context.logger.info(`Removing old config file (${oldConfigPath})`);
    host.delete(oldConfigPath);
    context.logger.info(`Writing config file (${configPath})`);
    host.create(configPath, JSON.stringify(config, null, 2));

    return host;
  };
Example #5
0
/**
 * Insert a custom theme to project style file. If no valid style file could be found, a new
 * Scss file for the custom theme will be created.
 */
function insertCustomTheme(project: WorkspaceProject, projectName: string, host: Tree,
                           workspace: WorkspaceSchema) {

  const stylesPath = getProjectStyleFile(project, 'scss');
  const themeContent = createCustomTheme(projectName);

  if (!stylesPath) {
    if (!project.sourceRoot) {
      throw new SchematicsException(`Could not find source root for project: "${projectName}". ` +
        `Please make sure that the "sourceRoot" property is set in the workspace config.`);
    }

    // Normalize the path through the devkit utilities because we want to avoid having
    // unnecessary path segments and windows backslash delimiters.
    const customThemePath = normalize(join(project.sourceRoot, defaultCustomThemeFilename));

    if (host.exists(customThemePath)) {
      console.warn(yellow(`Cannot create a custom Angular Material theme because
          ${bold(customThemePath)} already exists. Skipping custom theme generation.`));
      return;
    }

    host.create(customThemePath, themeContent);
    addThemeStyleToTarget(project, 'build', host, customThemePath, workspace);
    return;
  }

  const insertion = new InsertChange(stylesPath, 0, themeContent);
  const recorder = host.beginUpdate(stylesPath);

  recorder.insertLeft(insertion.pos, insertion.toAdd);
  host.commitUpdate(recorder);
}
Example #6
0
  return (host: Tree, context: SchematicContext) => {
    const name = options.name || getWorkspace(host).defaultProject;
    if (!name) {
      throw new Error('Please provide a name for Bazel workspace');
    }
    validateProjectName(name);

    if (!host.exists('yarn.lock')) {
      host.create('yarn.lock', '');
    }

    const workspaceVersions = {
      'RULES_NODEJS_VERSION': '0.18.6',
      'RULES_NODEJS_SHA256': '1416d03823fed624b49a0abbd9979f7c63bbedfd37890ddecedd2fe25cccebc6',
      'RULES_SASS_VERSION': '1.17.0',
    };

    return mergeWith(apply(url('./files'), [
      applyTemplates({
        utils: strings,
        name,
        'dot': '.', ...workspaceVersions,
        routing: hasRoutingModule(host),
        sass: hasSassStylesheet(host),
      }),
    ]));
  };
Example #7
0
 it('should import Store into the component', () => {
   const options = { ...defaultOptions, state: 'reducers' };
   appTree.create('/src/app/reducers', '');
   const tree = schematicRunner.runSchematic('container', options, appTree);
   const content = getFileContent(tree, '/src/app/foo/foo.component.ts');
   expect(content).toMatch(/import\ {\ Store\ }\ from\ '@ngrx\/store';/);
 });
Example #8
0
 it('should import the state path if provided', () => {
   const options = { ...defaultOptions, state: 'reducers' };
   appTree.create('/src/app/reducers', '');
   const tree = schematicRunner.runSchematic('container', options, appTree);
   const content = getFileContent(tree, '/src/app/foo/foo.component.ts');
   expect(content).toMatch(/import \* as fromStore from '..\/reducers';/);
 });
function createFile(remoteFiles: Tree, { path, file }: { path: string, file: FileEntry }) {
    if (!file) {
        console.log(`missing: ${path}`)
    }

    remoteFiles.create(path, file.content);
}
Example #10
0
export function createAppModuleWithEffects(
  tree: Tree,
  path: string,
  effects?: string
): Tree {
  tree.create(
    path || '/src/app/app.module.ts',
    `
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { EffectsModule } from '@ngrx/effects';

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        ${effects}
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
  `
  );

  return tree;
}
Example #11
0
 it('should find a module when name has uppercase', () => {
   tree.create('/projects/my-proj/src/featureModule/appTest.module.ts', '');
   options.path = '/projects/my-proj/src';
   options.name = 'featureModule/newComponent';
   const modPath = findModuleFromOptions(tree, options);
   expect(modPath).toEqual('/projects/my-proj/src/featureModule/appTest.module.ts' as Path);
 });
Example #12
0
export function createReducers(tree: Tree, path?: string) {
  tree.create(
    path || '/src/app/reducers/index.ts',
    `
    import {
      ActionReducer,
      ActionReducerMap,
      createFeatureSelector,
      createSelector,
      MetaReducer
    } from '@ngrx/store';
    import { environment } from '../../environments/environment';
    
    export interface State {
    
    }
    
    export const reducers: ActionReducerMap<State> = {
    
    };
    
    
    export const metaReducers: MetaReducer<State>[] = !environment.production ? [] : [];
  `
  );

  return tree;
}
Example #13
0
 it('should find a module if flat is true', () => {
   tree.create('/projects/my-proj/src/module/app_test.module.ts', '');
   options.path = '/projects/my-proj/src';
   options.flat = true;
   options.name = '/module/directive';
   const modPath = findModuleFromOptions(tree, options);
   expect(modPath).toEqual('/projects/my-proj/src/module/app_test.module.ts' as Path);
 });
Example #14
0
 return (tree: Tree, context: SchematicContext) => {
   debugger;
   // We pass information back to the test.
   tree.create(
     (context.schematic.description as any).extra,  // tslint:disable-line:no-any
     (context.schematic.collection.description as any).extra,  // tslint:disable-line:no-any
   );
 };
Example #15
0
 it('should find a module in a sub dir (2)', () => {
   tree.create('/projects/my-proj/src/admin/foo.module.ts', '');
   options.name = 'admin/hello';
   options.module = 'foo';
   options.path = '/projects/my-proj/src';
   const modPath = findModuleFromOptions(tree, options);
   expect(modPath).toEqual('/projects/my-proj/src/admin/foo.module.ts' as Path);
 });
Example #16
0
 it('should update the component constructor if the state path if provided', () => {
   const options = { ...defaultOptions, state: 'reducers' };
   appTree.create('/src/app/reducers', '');
   const tree = schematicRunner.runSchematic('container', options, appTree);
   const content = getFileContent(tree, '/src/app/foo/foo.component.ts');
   expect(content).toMatch(
     /constructor\(private store\: Store\<fromStore\.State\>\) { }\n\n/
   );
 });
Example #17
0
    (tree: Tree, context: SchematicContext) => {
      // Show the options for this Schematics.
      context.logger.info('My Other Schematic: ' + JSON.stringify(options));

      // Create a single file. Since this tree is not branched, we are working in the
      // same staging area as the other schematic, and as such cannot create the same
      // file twice.
      tree.create('hola', 'mundo');
    },
Example #18
0
 it('should throw if no modules found', () => {
   host.create('/foo/src/app/oops.module.ts', 'app module');
   try {
     findModule(host, 'foo/src/app/bar');
     throw new Error('Succeeded, should have failed');
   } catch (err) {
     expect(err.message).toMatch(/More than one module matches/);
   }
 });
Example #19
0
 return (host: Tree, context: SchematicContext) => {
   const tsconfigPath = 'tsconfig.json';
   if (!host.exists(tsconfigPath)) {
     return;
   }
   host.create(
       `${tsconfigPath}.bak`, '// This is a backup file of the original tsconfig.json. ' +
           'This file is needed in case you want to revert to the workflow without Bazel.\n\n' +
           host.read(tsconfigPath));
 };
Example #20
0
 return (host: Tree, context: SchematicContext) => {
   const workspacePath = getWorkspacePath(host);
   if (!workspacePath) {
     return;
   }
   host.create(
       `${workspacePath}.bak`, '// This is a backup file of the original angular.json. ' +
           'This file is needed in case you want to revert to the workflow without Bazel.\n\n' +
           host.read(workspacePath));
 };
Example #21
0
/** 将预设样式写入 theme.less,并添加到 angular.json */
function insertCustomTheme(project: Project, host: Tree, workspace: Workspace): void {
  const themePath = 'src/theme.less';
  host.create(themePath, createCustomTheme());
  if (project.architect) {
    addStyleToTarget(project.architect.build, host, themePath, workspace);
    addStyleToTarget(project.architect.test, host, themePath, workspace);
  } else {
    throw new SchematicsException(`${project.name} does not have an architect configuration`);
  }
}
Example #22
0
function envConfig(host: Tree, options: PluginOptions) {
  const defEnvPath = `${options.sourceRoot}/environments/environment.ts`;
  const defContent = host.get(defEnvPath).content;
  if (!host.exists(defEnvPath)) return ;
  // 1. update default env file
  addValueToVariable(host, defEnvPath, 'environment', 'hmr: false');
  // 2. update prod env file
  addValueToVariable(host, `${options.sourceRoot}/environments/environment.prod.ts`, 'environment', 'hmr: false');
  // 3. copy default env file to hmr file
  const hmrEnvPath = `${options.sourceRoot}/environments/environment.hmr.ts`;
  host.create(hmrEnvPath, defContent);
  addValueToVariable(host, hmrEnvPath, 'environment', 'hmr: true');
}
Example #23
0
  return (host: Tree, context: SchematicContext) => {
    if (host.exists(npmrc)) {
      host.delete(npmrc);
    }

    if (options.type === 'remove') {
      return ;
    }

    host.create(npmrc, `sass_binary_site=https://npm.taobao.org/mirrors/node-sass/
phantomjs_cdnurl=https://npm.taobao.org/mirrors/phantomjs/
electron_mirror=https://npm.taobao.org/mirrors/electron/
registry=https://registry.npm.taobao.org`);
  };
Example #24
0
    it('should ignore custom ext if module or ${module}.ts exists', () => {
      tree.create('/projects/my-proj/src/app.module.ts', '');
      options.path = '/projects/my-proj/src';
      options.moduleExt = '_module.ts';
      let modPath;

      // moduleExt ignored because exact path is found
      options.module = 'app.module.ts';
      modPath = findModuleFromOptions(tree, options);
      expect(modPath).toBe('/projects/my-proj/src/app.module.ts' as Path);

      // moduleExt ignored because module + .ts is found
      options.module = 'app.module';
      modPath = findModuleFromOptions(tree, options);
      expect(modPath).toBe('/projects/my-proj/src/app.module.ts' as Path);
    });
Example #25
0
 it('should find a module using custom ext', () => {
   tree.create('/projects/my-proj/src/app_module.ts', '');
   options.module = 'app';
   options.path = '/projects/my-proj/src';
   options.moduleExt = '_module.ts';
   // Should find module using custom moduleExt
   const modPath = findModuleFromOptions(tree, options);
   expect(modPath).toBe('/projects/my-proj/src/app_module.ts' as Path);
   // Should not find module if using invalid ext
   options.moduleExt = '-module.ts';
   expect(() => findModuleFromOptions(tree, options)).toThrowError(
     /Specified module 'app' does not exist/);
   // Should not find module if using default ext
   options.moduleExt = undefined;   // use default ext
   expect(() => findModuleFromOptions(tree, options)).toThrowError(
     /Specified module 'app' does not exist/);
 });
Example #26
0
  return (host: Tree, context: SchematicContext) => {
    const name = options.name || getWorkspace(host).defaultProject;
    if (!name) {
      throw new Error('Please provide a name for Bazel workspace');
    }
    validateProjectName(name);

    // If the project already has some deps installed, Bazel should use existing
    // versions.
    const existingVersions = {
      Angular: findVersion('@angular/core', host),
      RxJs: findVersion('rxjs', host),
    };

    Object.keys(existingVersions).forEach((name: 'Angular' | 'RxJs') => {
      const version = existingVersions[name] as string;
      if (version) {
        context.logger.info(`Bazel will reuse existing version for ${name}: ${version}`);
      }
    });

    if (!host.exists('yarn.lock')) {
      host.create('yarn.lock', '');
    }

    const workspaceVersions = {
      'RULES_NODEJS_VERSION': '0.18.6',
      'RULES_NODEJS_SHA256': '1416d03823fed624b49a0abbd9979f7c63bbedfd37890ddecedd2fe25cccebc6',
      'ANGULAR_VERSION': existingVersions.Angular || clean(latestVersions.Angular),
      'RXJS_VERSION': existingVersions.RxJs || clean(latestVersions.RxJs),
      // TODO(kyliau): Consider moving this to latest-versions.ts
      'RULES_SASS_VERSION': '1.17.0',
    };

    return mergeWith(apply(url('./files'), [
      applyTemplates({
        utils: strings,
        name,
        'dot': '.', ...workspaceVersions,
        routing: hasRoutingModule(host),
        sass: hasSassStylesheet(host),
      }),
    ]));
  };
Example #27
0
  return (tree: Tree, context: SchematicContext) => {
    // Show the options for this Schematics.
    // The logging here is at the discretion of the tooling. It can be ignored or only showing
    // info/warnings/errors. If you use console.log() there is not guarantee it will be
    // propagated to a user in any way (for example, an IDE running this schematic might
    // have a logging window but no support for console.log).
    context.logger.info('My Schematic: ' + JSON.stringify(options));

    // Create a single file. This is the simplest example of transforming the tree.
    // If a file with that name already exists, the generation will NOT fail until the tool
    // is trying to commit this to disk. This is because we allow you to work on what is
    // called a "staging" area, and only finalize those changes when the schematics is
    // done. This allows you to create files without having to verify if they exist
    // already, then rename them later. Templating works in a similar fashion.
    tree.create('hello', 'world');

    // At the end, you can either return a Tree (that will be used), or an observable of a
    // Tree (if you have some asynchronous tasks).
    return tree;
  };
Example #28
0
File: file.ts Project: wexz/delon
export function overwriteFile(
  host: Tree,
  filePath: string,
  sourcePath?: string,
  overwrite = false,
): Tree {
  const isExists = host.exists(filePath);
  if (overwrite || isExists) {
    try {
      const buffer = fs.readFileSync(sourcePath);
      const content = buffer ? buffer.toString('utf-8') : '';
      if (overwrite) {
        if (isExists) {
          host.delete(filePath);
        }
        host.create(filePath, content);
      } else {
        host.overwrite(filePath, content);
      }
    } catch {}
  }
  return host;
}
Example #29
0
 it('should work with weird paths', () => {
   host.create('/foo/src/app/app-routing.module.ts', 'app module');
   const foundModule = findModule(host, 'foo//src//app/bar/');
   expect(foundModule).toEqual(modulePath);
 });
Example #30
0
 it('should ignore routing modules', () => {
   host.create('/foo/src/app/app-routing.module.ts', 'app module');
   const foundModule = findModule(host, 'foo/src/app/bar');
   expect(foundModule).toEqual(modulePath);
 });