jscodeshift icon indicating copy to clipboard operation
jscodeshift copied to clipboard

Unexpected behavior when removing comments

Open ameyms opened this issue 3 years ago • 1 comments

See example in ASTExplorer. I'm trying to prune comment paths that contain a certain string but looks like some other node also gets displaced in the process!

Code

// @flow strict
const LIST = [
  'a',
  'b',
  'c',
  // @start hello
  // @start fubar
  'd',
  // @end fubar
  // @end hello
];

Code Mod:


export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);
  
  
 return root
    .find(j.Comment)
    .filter(path => {
      return path.value.value.includes('fubar') 
    })
    .forEach(path => {
      path.prune();
    })
    .toSource();

}

Expected

// @flow strict
const LIST = [
  'a',
  'b',
  'c',
  // @start hello
  'd',
  // @end hello
];

Actual

// @flow strict
const LIST = [
  'a',
  'b',
  'c',
  // @start hello
  // @end hello
  'd',
];

ameyms avatar Apr 23 '21 18:04 ameyms

I am experiencing a similar but inverted behavior. When I remove a piece of code, for example, an import declaration it also removes the comment (flow annotation) directly above it. This seems to be because the comment it's "attached" to the piece of code directly below.

For example, if you do this:

  console.log(root.find(j.VariableDeclaration).nodes())

Yo will see this on the console:

image

I think they should be considered independent nodes like everything else

danielo515 avatar May 29 '21 15:05 danielo515