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

fix: prevent nested renames #106

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 28 additions & 17 deletions src/utils/search-and-replace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,30 +16,33 @@ export async function searchAndReplace(

async function processFile(filePath: string): Promise<void> {
try {
const content = await readFile(filePath, 'utf8')
let newContent = content
let newContent = await readFile(filePath, 'utf8')
let changesMade = false

for (const [i, fromString] of fromStrings.entries()) {
const regex = new RegExp(fromString, 'g')
newContent = newContent.replace(regex, toStrings[i])
if (regex.test(newContent)) {
newContent = newContent.replace(regex, toStrings[i])
changesMade = true
}
}

if (content !== newContent) {
if (changesMade) {
if (!isDryRun) {
await writeFile(filePath, newContent, 'utf8')
}
if (isVerbose) {
console.log(`${isDryRun ? '[Dry Run] ' : ''}File modified: ${filePath}`)
}
for (const [index, fromStr] of fromStrings.entries()) {
const count = (newContent.match(new RegExp(toStrings[index], 'g')) || []).length
if (count > 0 && isVerbose) {
console.log(` Replaced "${fromStr}" with "${toStrings[index]}" ${count} time(s)`)
for (const [index, fromStr] of fromStrings.entries()) {
const count = (newContent.match(new RegExp(toStrings[index], 'g')) || []).length
if (count > 0) {
console.log(` Replaced "${fromStr}" with "${toStrings[index]}" ${count} time(s)`)
}
}
}
}
} catch (error) {
console.error(`Error processing file ${filePath}:`, error)
console.error(`Error processing file: ${filePath}`, error)
}
}

Expand Down Expand Up @@ -79,6 +82,7 @@ export async function searchAndReplace(
async function renamePaths(directoryPath: string): Promise<void> {
try {
const entries = await readdir(directoryPath, { withFileTypes: true })
const renameQueue: { oldPath: string; newPath: string }[] = []

for (const entry of entries) {
if (EXCLUDED_DIRECTORIES.has(entry.name)) {
Expand All @@ -96,16 +100,23 @@ export async function searchAndReplace(
}

if (oldPath !== newPath) {
if (!isDryRun) {
await rename(oldPath, newPath)
}
if (isVerbose) {
console.log(`${isDryRun ? '[Dry Run] ' : ''}Renamed: ${oldPath} -> ${newPath}`)
}
renameQueue.push({ oldPath, newPath })
}

if (entry.isDirectory()) {
await renamePaths(entry.isDirectory() ? newPath : oldPath)
await renamePaths(oldPath) // Process subdirectories first
}
}

// Sort by descending path length to rename deepest paths first
renameQueue.sort((a, b) => b.oldPath.length - a.oldPath.length)

for (const { oldPath, newPath } of renameQueue) {
if (!isDryRun) {
await rename(oldPath, newPath)
}
if (isVerbose) {
console.log(`${isDryRun ? '[Dry Run] ' : ''}Renamed: ${oldPath} -> ${newPath}`)
}
}
} catch (error) {
Expand Down
5 changes: 3 additions & 2 deletions test/search-and-replace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,9 @@ describe('searchAndReplace', () => {
await searchAndReplace(tempDir, ['Hello', 'Old'], ['Hi', 'New'], false, true)

// Check that log shows correct counts for replacements
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Replaced "Hello" with "Hi" 1 time(s)'))
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('Replaced "Old" with "New" 1 time(s)'))
expect(consoleLogSpy).toHaveBeenNthCalledWith(2, ' Replaced "Hello" with "Hi" 1 time(s)')
expect(consoleLogSpy).toHaveBeenNthCalledWith(4, ' Replaced "Old" with "New" 1 time(s)')
expect(consoleLogSpy).toHaveBeenNthCalledWith(6, ' Replaced "Hello" with "Hi" 1 time(s)')

consoleLogSpy.mockRestore()
})
Expand Down
Loading