Adam Chubbuck
Adam Chubbuck

Reputation: 35

Preserve folders with .gitkeep files when running a custom Angular schematic

I want to keep all of the folders in the files directory of the Angular schematic, also preserving the .gitkeep files. Unfortunately, the directories with only the .gitkeep file in it are being ignored when running the below schematic.

Am I missing something simple here? There seems to be a lack of documentation around this use case online.

import {
  Rule, Tree, SchematicsException,
  apply, url, applyTemplates, move,
  chain, mergeWith
} from '@angular-devkit/schematics';

import { strings, normalize, virtualFs, workspaces } from '@angular-devkit/core';

import { Schema as AspenModuleSchema } from './schema';

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);
    },
  };
}

export function aspenModule(options: AspenModuleSchema): Rule {
  return async (tree: Tree) => {
    const host = createHost(tree);
    const { workspace } = await workspaces.readWorkspace('/', host);

    const project = (options.project != null) ? workspace.projects.get(options.project) : null;
    if (!project) {
      throw new SchematicsException(`Invalid project name: ${options.project}`);
    }

    if (options.path === undefined) {
      options.path = `${project.sourceRoot}/app/modules/${strings.dasherize(options.name)}`;
    }

    const templateSource = apply(url('./files'), [
      applyTemplates({
        classify: strings.classify,
        dasherize: strings.dasherize,
        underscore: strings.underscore,
        capitalize: strings.capitalize,
        name: options.name
      }),
      move(normalize(options.path as string)),
    ]);

    return chain([
      mergeWith(templateSource),
    ]);
  };
}

Upvotes: 0

Views: 29

Answers (0)

Related Questions