Q:

Schematics - Manage template files copy error

I'm managing to copy some files from the schematics files directory to the main project target folder:
function addTplFiles(path: string): Source {
  // copy templates
  return apply(url('./files'), [
    move(path as string)
  ]);
}

export function ngAdd(options: ISchema): Rule {
  return (host: Tree/*, context: SchematicContext*/) => {
    // get the workspace config of the consuming project
    // i.e. angular.json file
    const workspace = getWorkspace(host);
    // identify the project config which is using our library
    // or default to the default project in consumer workspace
    const project = getProjectFromWorkspace(
      workspace,
      options.project || workspace.defaultProject
    );
    const projectType = project.projectType === 'application' ? 'app' : 'lib';
    const path = (options.path === undefined) ? `${project.sourceRoot}/${projectType}` : options.path;

    const templateSource = addTplFiles(project.sourceRoot || '');

    // return updated tree
    try {
      return chain([
        mergeWith(templateSource)
      ]);
    } catch (e) {
      return host;
    }
  };

The code works well, excepts when the files are already in the main app project:

ERROR! src/assets/i18n/en.json already exists. ERROR!
  src/assets/i18n/it.json already exists. The Schematic workflow failed.
  See above.

How could I catch and manage this exception?

A:

You have 2 options : 

use --force option with your schematics command, to force overwritting all existing files.

  ng g @custom/my-schematics:rule --force

check if file already exists into your schematics code, and apply a specific behaviour in this case.

const templateSource = apply(url('./files'), [
  forEach((fileEntry: FileEntry) => {
    if (tree.exists(fileEntry.path)) {
      console.log('File already exists, but it\'s ok');
      return null;
    }
    return fileEntry;
  })
]);

return chain([
  mergeWith(templateSource)
]);

