Created
July 27, 2022 12:12
-
-
Save jenya239/9ef8f35d1075e06ac1ea99b7427e7fa5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path') | |
const fs = require('fs') | |
const debug = console.log | |
const buildDirMap = (dirPath) => { | |
const map = {} | |
const items = fs.readdirSync(dirPath) | |
for (const name of items) { | |
map[name] = fs.statSync(path.join(dirPath, name), { throwIfNoEntry: false }) | |
} | |
return map | |
} | |
const copyDir = (source, target, level = 1) => { | |
// debug('source', source, 'target', target) | |
// debug(' '.repeat(level - 1) + path.basename(source)) | |
const targetStat = fs.statSync(target, { throwIfNoEntry: false }) | |
const items = fs.readdirSync(source, { withFileTypes: true }) | |
const checkItems = () => { | |
const targetItems = fs.readdirSync(target, { withFileTypes: true }) | |
for (const targetItem of targetItems) { | |
const found = items.find( | |
(item) => item.name === targetItem.name && item.isDirectory() === targetItem.isDirectory() | |
) | |
if (!found) { | |
const itemPath = path.join(target, targetItem.name) | |
fs.rmSync(itemPath, { recursive: true, force: true }) | |
debug('deleted', itemPath) | |
} | |
} | |
} | |
if (targetStat) { | |
if (targetStat.isDirectory()) { | |
checkItems() | |
} else { | |
fs.rmSync(target) | |
fs.mkdirSync(target) | |
} | |
} else { | |
fs.mkdirSync(target) | |
} | |
const sourceMap = buildDirMap(source) | |
const targetMap = buildDirMap(target) | |
for (const name in sourceMap) { | |
const stat = sourceMap[name] | |
const targetStat = targetMap[name] | |
const sourcePath = path.join(source, name) | |
const targetPath = path.join(target, name) | |
if (stat.isDirectory()) { | |
copyDir(path.join(source, name), path.join(target, name), level + 1) | |
} else { | |
if (!targetStat || stat.size !== targetStat.size) { | |
if (targetStat) fs.rmSync(targetPath) | |
fs.copyFileSync(sourcePath, targetPath) | |
debug('copied ' + targetPath) | |
} | |
// debug(' '.repeat(level) + item.name) | |
} | |
} | |
} | |
// copyDir('targets/cep', 'public') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment