Advertisement
Guest User

Untitled

a guest
Mar 15th, 2019
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ------- Input -------
  2. import { objectType } from "nexus";
  3.  
  4. // Original comment
  5. export const Toto = objectType({
  6.     name: "Query",
  7.     definition(t) {
  8.         t.string("hello");
  9.     }
  10. });
  11.  
  12. // ------- Expected output -------
  13. import { objectType } from "nexus";
  14. //Improved comment
  15. export const Toto = objectType({
  16.     name: "Query",
  17.     definition(t) {
  18.         t.string("hello");
  19.     }
  20. });
  21.  
  22. // ------- Actual output -------
  23. import { objectType } from "nexus";
  24. //Improved comment
  25. // Original comment
  26. export const Toto = objectType({
  27.     name: "Query",
  28.     definition(t) {
  29.         t.string("hello");
  30.     }
  31. });
  32.  
  33. // ------- Implementation -------
  34. const transformFactoryStack = (context: ts.TransformationContext) => (
  35.   rootNode: ts.SourceFile
  36. ): ts.SourceFile => {
  37.   const visit = (node: ts.Node) => {
  38.     node = ts.visitEachChild(node, visit, context);
  39.  
  40.     if (ts.isVariableStatement(node)) {
  41.       let sourceFileText = node.getSourceFile().text;
  42.       const existingComments = ts.getLeadingCommentRanges(
  43.         sourceFileText,
  44.         node.pos
  45.       );
  46.  
  47.       if (existingComments) {
  48.         // Log existing comments just for fun
  49.         for (const comment of existingComments) {
  50.           console.log({
  51.             existingComment: sourceFileText.substring(comment.pos, comment.end)
  52.           });
  53.         }
  54.  
  55.         ts.setTextRange(node, { pos: node.getStart(), end: node.getEnd() });
  56.         ts.setSyntheticLeadingComments(node, [
  57.           {
  58.             pos: -1,
  59.             end: -1,
  60.             hasTrailingNewLine: false,
  61.             text: "Improved comment",
  62.             kind: ts.SyntaxKind.SingleLineCommentTrivia
  63.           }
  64.         ]);
  65.       }
  66.     }
  67.  
  68.     return node;
  69.   };
  70.  
  71.   return ts.visitNode(rootNode, visit);
  72. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement