Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Losing empty lines when using replace function #97

Open
PowerSupply opened this issue Apr 25, 2024 · 1 comment
Open

Losing empty lines when using replace function #97

PowerSupply opened this issue Apr 25, 2024 · 1 comment

Comments

@PowerSupply
Copy link

Problem description
When using replace function to transform code the updated code is said to be printed with the TypeScript Printer.

This seems to get rid of empty lines which are not recovered when formatting the updated code with e.g. Prettier. This results in many diffs in the updated code compared to the original code, even when the same formatter was used before and after.

Suggested solution
Wouldn't it be possible to just do a string replacement if the input to the replace function is a string (not a node)? This would guarantee that the parts of the original string that are not replaced remain the same.

@PowerSupply
Copy link
Author

PowerSupply commented Apr 25, 2024

Here is a wrapper function that does the thing:

import { query } from '@phenomnomnominal/tsquery';

export function exactReplace(originalCode: string, selector: string, mappingFunc: (a: string) => string) {
    let offset = 0;

    query(originalCode, selector).forEach(({ pos, end }) => {
        pos = pos + offset;
        end = end + offset;
        const match = originalCode.substring(pos, end);
        const replacement = mappingFunc(match);
        originalCode = replaceSubstring(originalCode, pos, end, replacement);
        offset = offset + (replacement.length - match.length);
    });

    return originalCode;
}

function replaceSubstring(str: string, start: number, end: number, replacement: string) {
    return str.substring(0, start) + replacement + str.substring(end);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant