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

Refactor copy to use opendir #1028

Merged
merged 3 commits into from Feb 10, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/copy/copy-sync.js
Expand Up @@ -106,7 +106,17 @@ function mkDirAndCopy (srcMode, src, dest, opts) {
}

function copyDir (src, dest, opts) {
fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts))
const dir = fs.opendirSync(src)

try {
let dirent

while ((dirent = dir.readSync()) !== null) {
copyDirItem(dirent.name, src, dest, opts)
}
} finally {
dir.closeSync()
}
}

function copyDirItem (item, src, dest, opts) {
Expand Down
26 changes: 15 additions & 11 deletions lib/copy/copy.js
Expand Up @@ -113,23 +113,27 @@ async function onDir (srcStat, destStat, src, dest, opts) {
await fs.mkdir(dest)
}

const items = await fs.readdir(src)
const promises = []

// loop through the files in the current directory to copy everything
await Promise.all(items.map(async item => {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
for await (const item of await fs.opendir(src)) {
const srcItem = path.join(src, item.name)
const destItem = path.join(dest, item.name)

// skip the item if it is matches by the filter function
const include = await runFilter(srcItem, destItem, opts)
RyanZim marked this conversation as resolved.
Show resolved Hide resolved
if (!include) return

const { destStat } = await stat.checkPaths(srcItem, destItem, 'copy', opts)
if (!include) continue

promises.push(
stat.checkPaths(srcItem, destItem, 'copy', opts).then(({ destStat }) => {
// If the item is a copyable file, `getStatsAndPerformCopy` will copy it
// If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
return getStatsAndPerformCopy(destStat, srcItem, destItem, opts)
})
)
}

// If the item is a copyable file, `getStatsAndPerformCopy` will copy it
// If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
return getStatsAndPerformCopy(destStat, srcItem, destItem, opts)
}))
await Promise.all(promises)

if (!destStat) {
await fs.chmod(dest, srcStat.mode)
Expand Down