dsherret / dsherret/ts-morph

Remove() - can this be used with options? If so, which options and how?

Open
#1,277 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
6.2k
Forks
238
Avg merge
2m
Merged PRs (30d)
1

Description

**Is your feature request related to a problem? Please describe.**

I'm not sure if this is a bug or not, but it does feel like there must be some way to accomplish what I want. Already accomplished most of what I want, just some lame whitespace I'd like to have preserved. So when I run this code:
`variableDec.remove({ removePrecedingNewLines: false, removeFollowingNewLines: false });`

It still removes all new lines or at least empty lines surrounding the variable dec like this, namely line 10 and 33 on the left side of this diff:
![image](https://user-images.githubusercontent.com/56280950/168461200-d34f525b-c70b-420e-8a5c-f3f07ca03c5a.png)
Do I misunderstand what those options are for or what counts as a new line? So that is why the lines aren't left in? I tried setting the 'preceding' and 'following' newLine options to true for kicks, but the result was the same. I should probably mention that I found these options in the code [here](https://github.com/dsherret/ts-morph/blob/cea07aa7759ecf5a1e9f90b628334b8bd617c624/packages/ts-morph/src/manipulation/textManipulators/RemoveChildrenTextManipulator.ts), but they are not anywhere in the docs that I can tell, so maybe that is an indication that I am misusing them?

**Describe the solution you'd like**

I'd like the whitespace left there. And it would be super convenient if an option like the 'removePrecedingNewLines' facilitated it.

**Describe alternatives you've considered**

I've also tried various forms of "replaceWithText()" (doesn't catch the full declaration and I couldn't figure out if/how 'getText(true)' could be used in this case). Also tried 'file.removeText()', but it presents problems when removing multiple variableDeclarations from a single file.

Here is nearly my full code, in case it helps. I'm trying to remove exported variable declarations that are unused, but not from the whole project. I'm sure a lot of it looks funky or could be improved, but it does work to find all the nodes I want removed, of which there are about 229.
```
let passedPath;
const pathIndex = argv.indexOf('--path');
if (pathIndex > -1) {
passedPath = argv[pathIndex + 1];
}
const pathToFilesToParse = passedPath || './cypress/pages/**/!(*.spec).ts';

const project = new Project({
tsConfigFilePath: './tsconfig.json',
});

let removedExports = 0;
// Gather all applicable page files, and iterate through each to find all unused exports
for (const sourceFile of project.getSourceFiles(pathToFilesToParse)) {
for (const variableDec of sourceFile.getVariableDeclarations()) {
if (variableDec.isExported()) {
for (const referencedSymbol of variableDec.findReferences()) {
const totalReferences = referencedSymbol.getReferences().length - 1;
let file = variableDec.getSourceFile();
// This if() is meant to help avoid deleting any exports that are actually being used
// But it doesn't necessarily cover every situation, so deletions should be reviewed
if (
variableDec.findReferencesAsNodes().filter(n => n.getSourceFile() !== file).length === 0 &&
Node.isReferenceFindable(variableDec) &&
totalReferences === 0
) {
console.log('---------');
console.log(`Export found at: ${shortenPath(file.getFilePath())}`);
console.log(`On line: ${variableDec.getStartLineNumber()}`);
console.log(` ${variableDec.getText()}`);
console.log('');
if (argv.indexOf('--delete') > -1) {
variableDec.remove({ removePrecedingNewLines: false, removeFollowingNewLines: false });
// file.removeText(variableDec.getStartLineNumber(), variableDec.getEndLineNumber());
// variableDec.replaceWithText('\n');
removedExports++;
}
}
}
}
}
}

if (argv.indexOf('--delete') > -1) {
await project.save();
console.log(`Number of removals made: ${removedExports}`);
}

function shortenPath(str) {
const pathHalves = str.split('cypress/');
return pathHalves[1];
}
```

Contributor guide

Open the contributing guide

Research direction

Start with packages/ts-morph/src/manipulation/textManipulators/RemoveChildrenTextManipulator.ts and the variableDec.remove() call in the supplied reproduction. Compare the removePrecedingNewLines and removeFollowingNewLines handling with the requested whitespace behavior; done means the supported semantics are clear and documented, or the behavior is changed with a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.