"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("@pnpm/logger");
const rimraf = require("@zkochan/rimraf");
const loadJsonFile = require("load-json-file");
const fs = require("mz/fs");
const path = require("path");
const ssri = require("ssri");
const BIG_ONE = BigInt(1);
async function prune(storeDir) {
    const cafsDir = path.join(storeDir, 'files');
    await rimraf(path.join(storeDir, 'metadata'));
    await rimraf(path.join(storeDir, 'metadata-full'));
    logger_1.globalInfo('Removed all cached metadata files');
    const pkgIndexFiles = [];
    const removedHashes = new Set();
    const dirs = await fs.readdir(cafsDir);
    let fileCounter = 0;
    for (const dir of dirs) {
        const subdir = path.join(cafsDir, dir);
        for (const fileName of await fs.readdir(subdir)) {
            const filePath = path.join(subdir, fileName);
            if (fileName.endsWith('-index.json')) {
                pkgIndexFiles.push(filePath);
                continue;
            }
            const stat = await fs.stat(filePath);
            if (stat.nlink === 1 || stat.nlink === BIG_ONE) {
                await fs.unlink(filePath);
                fileCounter++;
                removedHashes.add(ssri.fromHex(`${dir}${fileName}`, 'sha512').toString());
            }
        }
    }
    logger_1.globalInfo(`Removed ${fileCounter} file${fileCounter === 1 ? '' : 's'}`);
    let pkgCounter = 0;
    for (const pkgIndexFilePath of pkgIndexFiles) {
        const { files: pkgFilesIndex } = await loadJsonFile(pkgIndexFilePath);
        if (removedHashes.has(pkgFilesIndex['package.json'].integrity)) {
            await fs.unlink(pkgIndexFilePath);
            pkgCounter++;
        }
    }
    logger_1.globalInfo(`Removed ${pkgCounter} package${pkgCounter === 1 ? '' : 's'}`);
}
exports.default = prune;
//# sourceMappingURL=prune.js.map