benjamn / benjamn/recast

Extra blank lines added when adding a property

Open
#370 7 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
5.3k
Forks
363
Avg merge
3d 8h
Merged PRs (30d)
3

Description

If I add a new line to an array, recast adds unwanted additional lines and changes the original formatting.

The following code adds a property at the end of two objects and then prints them.

```
const recast = require('recast'),
types = require("ast-types");

const code1 =
`set({
prop1: 100,
prop2: [],
prop3: 100,
});`;

const code2 =
`set({
prop1: 100,
prop2: [
],
prop3: 100
});`;

const ast1 = recast.parse(code1);
const ast2 = recast.parse(code2);

const addProp = (ast, name, value) => {
const b = recast.types.builders,
properties = ast.program.body[0].expression.arguments[0].properties,
newProperty = b.property('init', b.identifier(name), b.literal(value));

properties.splice(properties.length, 0, newProperty);
};

addProp(ast1, 'prop4', 'string');
addProp(ast2, 'prop4', 'string');

console.log(recast.print(ast1).code);
console.log(recast.print(ast2).code);

```

The result is:

```
set({
prop1: 100,
prop2: [],
prop3: 100,
prop4: "string"
});
set({
prop1: 100,

prop2: [
],

prop3: 100,
prop4: "string"
});
```

while the expected result is:

```
set({
prop1: 100,
prop2: [],
prop3: 100,
prop4: "string"
});
set({
prop1: 100,
prop2: [
],
prop3: 100,
prop4: "string"
});
```

Adding a property (= adding just a line at the end of the object in this case) should not change the previous code. It could be an option if someone would need to add these lines there.

Contributor guide

No contributing guide indexed for this repository

Research direction

Reproduce the behavior with the supplied recast.parse and recast.print example, then trace the object-property printing path responsible for preserving blank lines. Add a regression test for both object forms and verify that appending prop4 matches the expected output without changing existing formatting.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.