Skip to content

Instantly share code, notes, and snippets.

@ekoneko
Created December 29, 2020 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekoneko/90746dd1ce737612b5a789925406f9ab to your computer and use it in GitHub Desktop.
Save ekoneko/90746dd1ce737612b5a789925406f9ab to your computer and use it in GitHub Desktop.
remove yarn cache
#!/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