Skip to content

Commit

Permalink
Implements enable / disable (#11)
Browse files Browse the repository at this point in the history
* Implements enable / disable

* Adds tests

* Debugs GH-only crash

* Fixes CI by running the build beforehand

* Fixes build
  • Loading branch information
arcanis authored Sep 29, 2020
1 parent b56df30 commit 1a3db68
Show file tree
Hide file tree
Showing 19 changed files with 485 additions and 48 deletions.
16 changes: 16 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# EditorConfig is awesome!

# Mark this as the root editorconfig file
root = true

# Base ruleset for all files
[*]
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 2

# Override rules for markdown
[*.md]
# trailing whitespace is significant in markdown -> do not remove
trim_trailing_whitespace = false
1 change: 1 addition & 0 deletions .github/workflows/nodejs.yml → .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ jobs:
node-version: ${{ matrix.node-version }}

- run: yarn install --immutable
- run: yarn build # We need the stubs to run the tests
- run: yarn eslint
- run: yarn jest
17 changes: 15 additions & 2 deletions .pnp.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,9 @@
"**/.pnp.*": true
},
"eslint.nodePath": ".yarn/sdks",
"typescript.enablePromptUseWorkspaceTsdk": true
"typescript.enablePromptUseWorkspaceTsdk": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.fixAll.eslint": true
}
}
Binary file not shown.
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@types/node": "^13.9.2",
"@types/semver": "^7.1.0",
"@types/tar": "^4.0.3",
"@types/which": "^1.3.2",
"@typescript-eslint/eslint-plugin": "^2.0.0",
"@typescript-eslint/parser": "^4.2.0",
"@yarnpkg/eslint-config": "^0.1.0",
Expand All @@ -39,13 +40,15 @@
"ts-node": "^8.10.2",
"typescript": "^3.9.7",
"webpack": "next",
"webpack-cli": "^3.3.11"
"webpack-cli": "^3.3.11",
"which": "^2.0.2"
},
"scripts": {
"build": "rm -rf dist && webpack && ts-node ./mkshims.ts",
"corepack": "ts-node ./sources/main.ts",
"prepack": "node ./.yarn/releases/*.*js build",
"postpack": "rm -rf dist shims"
"postpack": "rm -rf dist shims",
"test": "yarn jest"
},
"files": [
"dist",
Expand Down
35 changes: 26 additions & 9 deletions sources/Engine.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
import {UsageError} from 'clipanion';
import fs from 'fs';
import path from 'path';
import semver from 'semver';
import {UsageError} from 'clipanion';
import fs from 'fs';
import path from 'path';
import semver from 'semver';

import defaultConfig from '../config.json';
import defaultConfig from '../config.json';

import * as folderUtils from './folderUtils';
import * as pmmUtils from './pmmUtils';
import {Config, Descriptor, Locator, SupportedPackageManagers, SupportedPackageManagerSet} from './types';
import * as folderUtils from './folderUtils';
import * as pmmUtils from './pmmUtils';
import {SupportedPackageManagers, SupportedPackageManagerSet} from './types';
import {Config, Descriptor, Locator} from './types';


export class Engine {
constructor(private config: Config = defaultConfig as Config) {
constructor(public config: Config = defaultConfig as Config) {
}

getBinariesFor(name: SupportedPackageManagers) {
const binNames = new Set<string>();

for (const rangeDefinition of Object.values(this.config.definitions[name]!.ranges)) {
const bins = Array.isArray(rangeDefinition.bin)
? rangeDefinition.bin
: Object.keys(rangeDefinition.bin);

for (const name of bins) {
binNames.add(name);
}
}

return binNames;
}

async getDefaultDescriptors() {
Expand Down
77 changes: 77 additions & 0 deletions sources/commands/Disable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import {Command, UsageError} from 'clipanion';
import fs from 'fs';
import path from 'path';
import which from 'which';

import {Context} from '../main';
import {isSupportedPackageManager, SupportedPackageManagerSet} from '../types';

export class DisableCommand extends Command<Context> {
static usage = Command.Usage({
description: `Remove the Corepack shims from the install directory`,
details: `
When run, this command will remove the shims for the specified package managers from the install directory, or all shims if no parameters are passed.
By default it will locate the install directory by running the equivalent of \`which corepack\`, but this can be tweaked by explicitly passing the install directory via the \`--bin-folder\` flag.
`,
examples: [[
`Disable all shims, removing them if they're next to the \`coreshim\` binary`,
`$0 disable`,
], [
`Disable all shims, removing them from the specified directory`,
`$0 disable --install-directory /path/to/bin`,
], [
`Disable the Yarn shim only`,
`$0 disable yarn`,
]],
});

@Command.String(`--install-directory`)
installDirectory?: string;

@Command.Rest()
names: Array<string> = [];

@Command.Path(`disable`)
async execute() {
let installDirectory = this.installDirectory;

// Node always call realpath on the module it executes, so we already
// lost track of how the binary got called. To find it back, we need to
// iterate over the PATH variable.
if (typeof installDirectory === `undefined`)
installDirectory = path.dirname(await which(`corepack`));

if (process.platform === `win32`) {
return this.executeWin32(installDirectory);
} else {
return this.executePosix(installDirectory);
}
}

async executePosix(installDirectory: string) {
const names = this.names.length === 0
? SupportedPackageManagerSet
: this.names;

for (const name of new Set(names)) {
if (!isSupportedPackageManager(name))
throw new UsageError(`Invalid package manager name '${name}'`);

for (const binName of this.context.engine.getBinariesFor(name)) {
const file = path.join(installDirectory, binName);
try {
await fs.promises.unlink(file);
} catch (err) {
if (err.code !== `ENOENT`) {
throw err;
}
}
}
}
}

async executeWin32(installDirectory: string) {
throw new UsageError(`This command isn't available on Windows at this time`);
}
}
89 changes: 89 additions & 0 deletions sources/commands/Enable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import {Command, UsageError} from 'clipanion';
import fs from 'fs';
import path from 'path';
import which from 'which';

import {Context} from '../main';
import {isSupportedPackageManager, SupportedPackageManagerSet} from '../types';

export class EnableCommand extends Command<Context> {
static usage = Command.Usage({
description: `Add the Corepack shims to the install directories`,
details: `
When run, this commmand will check whether the shims for the specified package managers can be found with the correct values inside the install directory. If not, or if they don't exist, they will be created.
By default it will locate the install directory by running the equivalent of \`which corepack\`, but this can be tweaked by explicitly passing the install directory via the \`--bin-folder\` flag.
`,
examples: [[
`Enable all shims, putting them next to the \`corepath\` binary`,
`$0 enable`,
], [
`Enable all shims, putting them in the specified directory`,
`$0 enable --bin-folder /path/to/folder`,
], [
`Enable the Yarn shim only`,
`$0 enable yarn`,
]],
});

@Command.String(`--install-directory`)
installDirectory?: string;

@Command.Rest()
names: Array<string> = [];

@Command.Path(`enable`)
async execute() {
let installDirectory = this.installDirectory;

// Node always call realpath on the module it executes, so we already
// lost track of how the binary got called. To find it back, we need to
// iterate over the PATH variable.
if (typeof installDirectory === `undefined`)
installDirectory = path.dirname(await which(`corepack`));

if (process.platform === `win32`) {
return this.executeWin32(installDirectory);
} else {
return this.executePosix(installDirectory);
}
}

async executePosix(installDirectory: string) {
// We use `eval` so that Webpack doesn't statically transform it.
const manifestPath = eval(`require`).resolve(`corepack/package.json`);

const stubFolder = path.join(path.dirname(manifestPath), `shims`);
if (!fs.existsSync(stubFolder))
throw new Error(`Assertion failed: The stub folder doesn't exist`);

const names = this.names.length === 0
? SupportedPackageManagerSet
: this.names;

for (const name of new Set(names)) {
if (!isSupportedPackageManager(name))
throw new UsageError(`Invalid package manager name '${name}'`);

for (const binName of this.context.engine.getBinariesFor(name)) {
const file = path.join(installDirectory, binName);
const symlink = path.relative(installDirectory, path.join(stubFolder, binName));

if (fs.existsSync(file)) {
const currentSymlink = await fs.promises.readlink(file);
if (currentSymlink !== symlink) {
await fs.promises.unlink(file);
} else {
return;
}
}

await fs.promises.symlink(symlink, file);
}
}
}

async executeWin32(target: string) {
throw new UsageError(`This command isn't available on Windows at this time`);
}
}
4 changes: 2 additions & 2 deletions sources/commands/Hydrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ export class HydrateCommand extends Command<Context> {
static usage = Command.Usage({
description: `Import a package manager into the cache`,
details: `
This command unpacks a package manager archive into the cache. The archive must have been generated by the \`corepack pack\` command - no other will work.
`,
This command unpacks a package manager archive into the cache. The archive must have been generated by the \`corepack pack\` command - no other will work.
`,
examples: [[
`Import a package manager in the cache`,
`$0 hydrate corepack-yarn-2.2.2.tgz`,
Expand Down
6 changes: 3 additions & 3 deletions sources/commands/Prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ export class PrepareCommand extends Command<Context> {
static usage = Command.Usage({
description: `Generate a package manager archive`,
details: `
This command generates an archive for the specified package manager, in a format suitable for later hydratation via the \`corepack hydrate\` command.
This command generates an archive for the specified package manager, in a format suitable for later hydratation via the \`corepack hydrate\` command.
If run without parameter, it'll extract the package manager spec from the active project. Otherwise an explicit spec string is required, that Corepack will resolve before installing and packing.
`,
If run without parameter, it'll extract the package manager spec from the active project. Otherwise an explicit spec string is required, that Corepack will resolve before installing and packing.
`,
examples: [[
`Generate an archive from the active project`,
`$0 prepare`,
Expand Down
4 changes: 4 additions & 0 deletions sources/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {BaseContext, Cli, Command, UsageError} from 'clipanion';

import {Engine} from './Engine';
import {DisableCommand} from './commands/Disable';
import {EnableCommand} from './commands/Enable';
import {HydrateCommand} from './commands/Hydrate';
import {PrepareCommand} from './commands/Prepare';
import * as miscUtils from './miscUtils';
Expand Down Expand Up @@ -69,6 +71,8 @@ export async function main(argv: Array<string>, context: CustomContext & Partial

cli.register(Command.Entries.Help as any);

cli.register(EnableCommand);
cli.register(DisableCommand);
cli.register(HydrateCommand);
cli.register(PrepareCommand);

Expand Down
Loading

0 comments on commit 1a3db68

Please sign in to comment.