Created
December 29, 2020 03:12
-
-
Save ekoneko/90746dd1ce737612b5a789925406f9ab to your computer and use it in GitHub Desktop.
remove yarn cache
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
#!/usr/bin/env node | |
const fs = require("fs"); | |
const path = require("path"); | |
const { execSync } = require("child_process"); | |
function findMetaFile(modulePath) { | |
const name = ".yarn-metadata.json"; | |
function walkDir(dirPath) { | |
const subFiles = fs.readdirSync(dirPath); | |
if (subFiles.includes(name)) { | |
return path.join(dirPath, name); | |
} | |
for (let subFile of subFiles) { | |
const subPath = path.join(dirPath, subFile); | |
if (fs.statSync(subPath).isDirectory()) { | |
const result = walkDir(subPath); | |
if (result) { | |
return result; | |
} | |
} | |
} | |
} | |
return walkDir(modulePath); | |
} | |
function rmRaf(filePath) { | |
if (!filePath.includes(cachePath)) { | |
process.stderr.write(`Can not remove ${filepath}`); | |
process.exit(1); | |
} | |
execSync(`rm -rf ${filePath}`); | |
} | |
const cachePath = process.argv[process.argv.length - 1]; | |
const currentDate = Date.now(); | |
if (!fs.existsSync(cachePath) || !fs.statSync(cachePath).isDirectory()) { | |
process.stderr.write("Cache directory not exists"); | |
process.exit(1); | |
} | |
if (!cachePath.includes(path.join("yarn", "v6"))) { | |
process.stderr.write("Yarn cache version is not v6"); | |
process.exit(1); | |
} | |
const modules = fs.readdirSync(cachePath); | |
const willDeleted = modules.filter((module) => { | |
const modulePath = path.join(cachePath, module); | |
const metaFilePath = findMetaFile(modulePath); | |
if (!metaFilePath) { | |
return false; | |
} | |
const stat = fs.statSync(metaFilePath); | |
return currentDate - stat.atime > 86400000 * 30; | |
}); | |
willDeleted.forEach((module) => { | |
const modulePath = path.join(cachePath, module); | |
rmRaf(modulePath); | |
}); | |
process.stdout.write(`Remove ${willDeleted.length} modules`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment