Created
February 14, 2022 22:16
-
-
Save luavixen/1a4476ab4028865ad216ae730bcc6c0d to your computer and use it in GitHub Desktop.
Node.js script to fix modification times for directories which have been moved between filesystems.
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 paths = require('path'); | |
const fs = require('fs').promises; | |
async function time(path) | |
{ | |
const { mtime, birthtime } = await fs.stat(path); | |
if (mtime.getTime() > birthtime.getTime()) | |
{ | |
return mtime; | |
} | |
else | |
{ | |
return birthtime; | |
} | |
} | |
async function walk(path) | |
{ | |
console.log('Walking directory:', path); | |
const files = await fs.readdir(path, { withFileTypes: true }); | |
const stats = await fs.stat(path); | |
if (!stats.isDirectory()) | |
{ | |
throw new Error('Attempted to walk a file'); | |
} | |
let timeThis = null; | |
for (const file of files) | |
{ | |
const filePath = paths.join(path, file.name); | |
if (file.isDirectory()) | |
{ | |
const fileDir = file; | |
const fileAdj = files.find((file) => | |
{ | |
if (file.isDirectory) | |
{ | |
return; | |
} | |
const level1 = paths.parse(file.name).name; | |
const level2 = paths.parse(level1).name; | |
return fileDir.name === level1 || fileDir.name === level2; | |
}); | |
if (fileAdj != null) | |
{ | |
timeThis = await time(paths.join(path, fileAdj.name)); | |
break; | |
} | |
else | |
{ | |
const timeFile = await walk(filePath); | |
if (timeThis == null || timeFile.getTime() < timeThis.getTime()) | |
{ | |
timeThis = timeFile; | |
} | |
} | |
} | |
else | |
{ | |
const timeFile = await time(filePath); | |
if (timeThis == null || timeFile.getTime() > timeThis.getTime()) | |
{ | |
timeThis = timeFile; | |
} | |
} | |
} | |
if (timeThis == null) | |
{ | |
timeThis = stats.birthtime; | |
} | |
console.log('Setting mtime to:', timeThis); | |
await fs.utimes(path, stats.atime, timeThis); | |
return timeThis; | |
} | |
walk(process.argv[2] || '.') | |
.then(() => { console.log('Done!'); }) | |
.catch((err) => { console.error(err); }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment