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

Add support for npm packing a directory #49

Merged
merged 3 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/good-mice-whisper.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@arethetypeswrong/cli": minor
---

Add --pack flag to support running `npm pack` in a directory and deleting the file afterwards
68 changes: 58 additions & 10 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
#!/usr/bin/env node

import * as core from "@arethetypeswrong/core";
import { groupProblemsByKind, parsePackageSpec } from "@arethetypeswrong/core/utils";
import { versions } from "@arethetypeswrong/core/versions";
import { Option, program } from "commander";
import chalk from "chalk";
import { readFile } from "fs/promises";
import { FetchError } from "node-fetch";
import { execSync } from "child_process";
import { Option, program } from "commander";
import { readFile, stat, unlink } from "fs/promises";
import { createRequire } from "module";

import * as render from "./render/index.js";
import { readConfig } from "./readConfig.js";
import { FetchError } from "node-fetch";
import path from "path";
import readline from "readline/promises";
import { problemFlags } from "./problemUtils.js";
import { groupProblemsByKind, parsePackageSpec } from "@arethetypeswrong/core/utils";
import { readConfig } from "./readConfig.js";
import * as render from "./render/index.js";

const packageJson = createRequire(import.meta.url)("../package.json");
const version = packageJson.version;
Expand All @@ -21,6 +23,7 @@ const formats = ["table", "table-flipped", "ascii", "json"] as const;
type Format = (typeof formats)[number];

export interface Opts {
pack?: boolean;
fromNpm?: boolean;
summary?: boolean;
emoji?: boolean;
Expand All @@ -42,7 +45,11 @@ program
)} attempts to analyze npm package contents for issues with their TypeScript types,
particularly ESM-related module resolution issues.`
)
.argument("<file-name>", "the file to check; by default a path to a .tar.gz file, unless --from-npm is set")
.argument(
"[file-directory-or-package-spec]",
"the packed .tgz, or directory containing package.json with --pack, or package spec with --from-npm"
)
.option("-P, --pack", "run `npm pack` in the specified directory and delete the resulting .tgz file afterwards")
.option("-p, --from-npm", "read from the npm registry instead of a local file")
.addOption(new Option("-f, --format <format>", "specify the print format").choices(formats).default("table"))
.option("-q, --quiet", "don't print anything to STDOUT (overrides all other options)")
Expand All @@ -53,7 +60,7 @@ particularly ESM-related module resolution issues.`
.option("--emoji, --no-emoji", "whether to use any emojis")
.option("--color, --no-color", "whether to use any colors (the FORCE_COLOR env variable is also available)")
.option("--config-path <path>", "path to config file (default: ./.attw.json)")
.action(async (fileName: string) => {
.action(async (fileOrDirectory = ".") => {
const opts = program.opts<Opts>();
await readConfig(program, opts.configPath);
opts.ignoreRules = opts.ignoreRules?.map(
Expand All @@ -69,9 +76,13 @@ particularly ESM-related module resolution issues.`
}

let analysis: core.CheckResult;
let deleteTgz;
if (opts.fromNpm) {
if (opts.pack) {
program.error("--pack and --from-npm cannot be used together");
}
try {
const result = parsePackageSpec(fileName);
const result = parsePackageSpec(fileOrDirectory);
if (result.status === "error") {
program.error(result.error);
} else {
Expand All @@ -86,6 +97,39 @@ particularly ESM-related module resolution issues.`
}
} else {
try {
let fileName = fileOrDirectory;
if (
await stat(fileOrDirectory)
.then((stat) => !stat.isFile())
.catch(() => false)
) {
if (!(await stat(path.join(fileOrDirectory, "package.json")).catch(() => false))) {
program.error(
`Specified directory must contain a package.json. No package.json found in ${path.resolve(
fileOrDirectory
)}.`
);
}

if (!opts.pack) {
if (!process.stdout.isTTY) {
program.error(
"Specifying a directory requires the --pack option to confirm that running `npm pack` is ok."
);
}
const rl = readline.createInterface(process.stdin, process.stdout);
const answer = await rl.question(`Run \`npm pack\`? (Pass -P/--pack to skip) (Y/n) `);
rl.close();
if (answer.trim() && !answer.trim().toLowerCase().startsWith("y")) {
process.exit(1);
}
}

fileName = deleteTgz = path.resolve(
fileOrDirectory,
execSync("npm pack", { cwd: fileOrDirectory, encoding: "utf8", stdio: "pipe" }).trim()
);
}
const file = await readFile(fileName);
const data = new Uint8Array(file);
analysis = await core.checkTgz(data);
Expand Down Expand Up @@ -122,6 +166,10 @@ particularly ESM-related module resolution issues.`
} else {
render.untyped(analysis as core.UntypedResult);
}

if (deleteTgz) {
await unlink(deleteTgz);
}
});

program.parse(process.argv);
Expand Down