0

I'm creating an Angular schematics. I want to apply a rule to the current tree, and then modify the tree.

as explained in the following snippet, I want to apply the rule created, so tree.exists("./file.txt") returns true

export default function(options: any): Rule {
  return (tree: Tree, context: SchematicContext) => {
    let tmpl = apply(url("./files"), [template(options),move(".")]);
    let rule = chain([branchAndMerge(chain([mergeWith(tmpl)]))]);
     //how to apply this rule to the current tree, so it contains the files from ./files

    //assume ./files contain a file named myfile.txt
    console.log(tree.exists("./myfile.txt"))    


    tree.create("hello.txt", "");
    return tree;
  };
}

notes

return rule; creates /file.txt, but I want to create both files file.txt (through applying rules) and hello.txt by tree.create() function.

using tree.create() before applying rules, creates both files, but tree.exists('./file.txt') still returns false.

Sh eldeeb
  • 1,589
  • 3
  • 18
  • 41

1 Answers1

1

EDIT

Just call the chain without assigning a variable:

export default function(options: any): Rule {
    return (tree: Tree) => {
        const templateSource = apply(
            url("./files"),
            [template(options), move(".")]
        );

        const rules: Rule[] = [];
        rules.push(mergeWith(templateSource, MergeStrategy.Overwrite));
        rules.push(createFiles());
        return chain(rules);
    };
}

function createFiles(): Rule {
    return (tree: Tree) => {
        // Check if ./files contain a file named myfile.txt
        if (tree.exists("./myfile.txt")) {
            // Do whatever you want.
        }

        // You should check if it exists. If it does, use ovewrite instead.
        tree.create("hello.txt", "");
        return tree;
    }
}

And always try to provide some merge strategy.

KingDarBoja
  • 1,033
  • 6
  • 12
  • didn't work, although returning the rule creating the file i.e: return chain(...), but this method doesn't give the chance to complete the code after returning. also ` chain([branchAndMerge(chain([mergeWith(tmpl)]))]);` didn't work. – Sh eldeeb Jan 07 '20 at 22:29
  • Maybe split the if-create part in another function, return the rule and chaining with the previous one could work. – KingDarBoja Jan 08 '20 at 14:20
  • did you test it yourself? if you did, please give me the tested code. – Sh eldeeb Jan 08 '20 at 20:36
  • Check the edited answer. I didn't test it but that's what I do on most of my schematics. – KingDarBoja Jan 12 '20 at 03:34