Tackle *.hbs
So far, we can read *.{gjs,gts,hbs} files and write back their content. How should we remove test selectors?
Let's take small steps by focusing on *.hbs first.
diff
function removeDataTestAttributes(file: string): string {
return file;
}
let file = readFileSync(join(projectRoot, filePath), 'utf8');
- file = removeDataTestAttributes(file);
+ if (filePath.endsWith('.hbs')) {
+ file = removeDataTestAttributes(file);
+ }1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Use @codemod-utils/ast-template
First, update removeDataTestAttributes so that it uses @codemod-utils/ast-template and remains a no-op.
diff
+ import { AST } from '@codemod-utils/ast-template';
function removeDataTestAttributes(file: string): string {
- return file;
+ const traverse = AST.traverse();
+
+ const ast = traverse(file, {
+ /* Use AST.builders to transform the tree */
+ });
+
+ return AST.print(ast);
}1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
To find the correct visit method, recall that we want to remove attributes if their name starts with data-test.
Solution
diff
import { AST } from '@codemod-utils/ast-template';
function removeDataTestAttributes(file: string): string {
const traverse = AST.traverse();
const ast = traverse(file, {
- /* Use AST.builders to transform the tree */
+ AttrNode(node) {
+ if (!node.name.startsWith('data-test')) {
+ return;
+ }
+
+ return null;
+ },
});
return AST.print(ast);
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Finally, run update-test-fixtures.sh. Only the output fixture app/templates/index.hbs is updated.
diff
- <div data-test-my-component>
+ <div>
<MyComponent />
</div>1
2
3
4
2
3
4