Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add corepack cleanup command #363

Merged
merged 9 commits into from
Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions sources/commands/Cleanup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import {Command} from 'clipanion';
import fs from 'fs';
import path from 'path';
import semver from 'semver';

import * as debugUtils from '../debugUtils';
import {getInstallFolder} from '../folderUtils';
import type {Context} from '../main';
import type {NodeError} from '../nodeUtils';
import {parseSpec} from '../specUtils';

export class CleanupCommand extends Command<Context> {
static paths = [
[`cleanup`],
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
];

static usage = Command.Usage({
description: `Cleans Corepack cache`,
details: `
When run, this commmand will check what are the versions required by the package.json files it knows of, and remove from the cache all the versions that are in used.
`,
});

async execute() {
const installFolder = getInstallFolder();
const listFile = await fs.promises.open(path.join(installFolder, `packageJsonList.json`), `r+`);

const previousList = JSON.parse(await listFile.readFile(`utf8`)) as Array<string>;
const listFilteredOffOfInvalidManifests = new Set<string>();
const inusedSpecs = [];

for (const pkgPath of previousList) {
let pkgContent: string;
try {
pkgContent = await fs.promises.readFile(pkgPath, `utf8`);
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
} catch (err) {
if ((err as NodeError)?.code === `ENOENT`)
continue;

throw err;
}
let packageManager: string;
try {
packageManager = JSON.parse(pkgContent).packageManager;
} catch {
continue;
}

if (!packageManager) continue;

try {
inusedSpecs.push(parseSpec(packageManager, pkgPath));
listFilteredOffOfInvalidManifests.add(pkgPath);
} catch {
continue;
}
}

await listFile.truncate(0);
await listFile.write(JSON.stringify(Array.from(listFilteredOffOfInvalidManifests)), 0);
await listFile.close();

const cacheDir = await fs.promises.opendir(path.join(installFolder));
const deletionPromises = [];
for await (const dirent of cacheDir) {
if (!dirent.isDirectory() || dirent.name[0] === `.`) continue;
deletionPromises.push(this.cleanUpCacheFolder(
path.join(installFolder, dirent.name),
inusedSpecs.flatMap(spec => spec.name === dirent.name ? spec.range : []),
));
}
await Promise.all(deletionPromises);
}

async cleanUpCacheFolder(dirPath: string, ranges: Array<string>) {
const dirIterator = await fs.promises.opendir(dirPath);
const deletionPromises = [];
for await (const dirent of dirIterator) {
if (!dirent.isDirectory() || dirent.name[0] === `.`) continue;
const p = path.join(dirPath, dirent.name);
if (ranges.every(range => !semver.satisfies(dirent.name, range))) {
debugUtils.log(`Removing ${p}`);
deletionPromises.push(fs.promises.rm(p));
} else {
debugUtils.log(`Keeping ${p}`);
}
}
await Promise.all(deletionPromises);
}
}
2 changes: 2 additions & 0 deletions sources/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {BaseContext, Builtins, Cli, Command, Option, UsageError} from 'clipanion
import {version as corepackVersion} from '../package.json';

import {Engine} from './Engine';
import {CleanupCommand} from './commands/Cleanup';
import {DisableCommand} from './commands/Disable';
import {EnableCommand} from './commands/Enable';
import {InstallGlobalCommand} from './commands/InstallGlobal';
Expand Down Expand Up @@ -117,6 +118,7 @@ export async function runMain(argv: Array<string>) {
cli.register(Builtins.HelpCommand);
cli.register(Builtins.VersionCommand);

cli.register(CleanupCommand);
cli.register(DisableCommand);
cli.register(EnableCommand);
cli.register(InstallGlobalCommand);
Expand Down
23 changes: 23 additions & 0 deletions sources/specUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import fs from 'fs';
import path from 'path';
import semver from 'semver';

import * as debugUtils from './debugUtils';
import {getInstallFolder} from './folderUtils';
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
import {NodeError} from './nodeUtils';
import {Descriptor, Locator, isSupportedPackageManager} from './types';

Expand Down Expand Up @@ -123,6 +125,27 @@ export async function loadSpec(initialCwd: string): Promise<LoadSpecResult> {
if (typeof rawPmSpec === `undefined`)
return {type: `NoSpec`, target: selection.manifestPath};

const pathToListFile = path.join(getInstallFolder(), `packageJsonList.json`);
try {
const file = await fs.promises.open(pathToListFile, `r+`);
const list = JSON.parse(await file.readFile(`utf8`)) as Array<string>;
if (!list?.includes(selection.manifestPath)) {
list.push(selection.manifestPath);
await file.truncate(0);
await file.write(JSON.stringify(list), 0);
}
await file.close();
} catch (err) {
if ((err as NodeError)?.code === `ENOENT`) {
// If the file doesn't exist yet, we can create it.
await fs.promises.writeFile(pathToListFile, JSON.stringify([selection.manifestPath]))
.catch(debugUtils.log);
} else {
// In case of another error, ignore it.
debugUtils.log(`Failed to update packageJsonList file because of the following error: ${err}`);
}
}

aduh95 marked this conversation as resolved.
Show resolved Hide resolved
return {
type: `Found`,
target: selection.manifestPath,
Expand Down
Loading