MCPcopy Create free account
hub / github.com/donghaxkim/react-rewrite / replaceStringLiteralInFile

Function replaceStringLiteralInFile

packages/cli/src/batch-transform.ts:644–699  ·  view source on GitHub ↗

* Fallback for text edits where the text lives in a JS string literal * (e.g. `description: "some text"`) rather than inline JSX. * Searches all StringLiteral/Literal nodes in the file for an exact match.

(
  j: any,
  root: any,
  originalText: string,
  newText: string,
)

Source from the content-addressed store, hash-verified

642 * Searches all StringLiteral/Literal nodes in the file for an exact match.
643 */
644function replaceStringLiteralInFile(
645 j: any,
646 root: any,
647 originalText: string,
648 newText: string,
649): { replaced: boolean; ambiguous: boolean } {
650 const trimmedOriginal = originalText.trim();
651 if (!trimmedOriginal) return { replaced: false, ambiguous: false };
652
653 const literalMatches: Array<{ apply: () => void }> = [];
654
655 // Search StringLiteral nodes (babel parser)
656 root.find(j.StringLiteral).forEach((p: any) => {
657 if (p.node.value === trimmedOriginal) {
658 literalMatches.push({
659 apply: () => {
660 p.node.value = newText.trim();
661 },
662 });
663 }
664 });
665
666 // Search Literal nodes (typescript/flow parser)
667 try {
668 root.find(j.Literal).forEach((p: any) => {
669 if (typeof p.node.value === "string" && p.node.value === trimmedOriginal) {
670 literalMatches.push({
671 apply: () => {
672 p.node.value = newText.trim();
673 },
674 });
675 }
676 });
677 } catch {
678 // j.Literal may not exist in all parsers
679 }
680
681 // Search TemplateLiteral quasis for the text as a substring
682 root.find(j.TemplateLiteral).forEach((p: any) => {
683 for (const quasi of p.node.quasis ?? []) {
684 if ((p.node.expressions?.length ?? 0) === 0 && quasi.value?.raw === trimmedOriginal) {
685 literalMatches.push({
686 apply: () => {
687 quasi.value.raw = newText.trim();
688 quasi.value.cooked = newText.trim();
689 },
690 });
691 }
692 }
693 });
694
695 if (literalMatches.length === 0) return { replaced: false, ambiguous: false };
696 if (literalMatches.length > 1) return { replaced: false, ambiguous: true };
697 literalMatches[0].apply();
698 return { replaced: true, ambiguous: false };
699}
700
701function collapseVisibleWhitespace(value: string): string {

Callers 1

applyOpFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected