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

Implement the --help command #5409

Merged
merged 4 commits into from
Jun 24, 2024
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: 4 additions & 1 deletion pnpm-lock.yaml

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

12 changes: 6 additions & 6 deletions v-next/core/test/internal/hook-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ describe("HookManager", () => {
plugins: [],
},
hooks: hookManager,
globalArguments: {},
globalOptions: {},
interruptions: userInterruptionsManager,
});

Expand Down Expand Up @@ -295,7 +295,7 @@ describe("HookManager", () => {
plugins: [],
},
hooks: hookManager,
globalArguments: {},
globalOptions: {},
interruptions: userInterruptionsManager,
});

Expand Down Expand Up @@ -509,7 +509,7 @@ describe("HookManager", () => {
plugins: [],
},
hooks: hookManager,
globalArguments: {},
globalOptions: {},
interruptions: userInterruptionsManager,
});

Expand Down Expand Up @@ -634,7 +634,7 @@ describe("HookManager", () => {
plugins: [],
},
hooks: hookManager,
globalArguments: {},
globalOptions: {},
interruptions: userInterruptionsManager,
});

Expand Down Expand Up @@ -778,7 +778,7 @@ describe("HookManager", () => {
plugins: [],
},
hooks: hookManager,
globalArguments: {},
globalOptions: {},
interruptions: userInterruptionsManager,
});

Expand Down Expand Up @@ -935,7 +935,7 @@ function buildMockHardhatRuntimeEnvironment(
plugins: [],
},
tasks: mockTaskManager,
globalArguments: {},
globalOptions: {},
interruptions: mockInteruptionManager,
};

Expand Down
48 changes: 43 additions & 5 deletions v-next/hardhat/example.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,51 @@ import {
overrideTask,
configVariable,
task,
emptyTask,
} from "./src/config.js";

const exampleTaskOverride = overrideTask("example")
.setAction(async (args, _hre, runSuper) => {
const exampleEmptyTask = emptyTask("empty", "An example empty task").build();

const exampleEmptySubtask = task(["empty", "task"])
.setDescription("An example empty subtask task")
.setAction(async (_, _hre) => {
console.log("empty task");
})
.build();

const exampleTaskOverride = task("example2")
.setAction(async (_, _hre) => {
console.log("from an override");
await runSuper(args);
})
.setDescription("An example task")
.addVariadicParameter({
name: "testFiles",
description: "An optional list of files to test",
// defaultValue: [],
})
.addOption({
name: "noCompile",
description: "Don't compile before running this task",
})
.addFlag({
name: "parallel",
description: "Run tests in parallel",
})
.addFlag({
name: "bail",
description: "Stop running tests after the first test failure",
})
.addOption({
name: "grep",
description: "Only run tests matching the given string or regexp",
})
.build();

const testTask = task("test", "Runs mocha tests")
.addVariadicParameter({
name: "testFiles",
description: "An optional list of files to test",
defaultValue: [],
// defaultValue: [],
})
.addOption({
name: "noCompile",
Expand Down Expand Up @@ -52,6 +83,13 @@ const testSolidityTask = task(["test", "solidity"], "Runs Solidity tests")
.build();

export default {
tasks: [exampleTaskOverride, testTask, testTaskOverride, testSolidityTask],
tasks: [
exampleTaskOverride,
testTask,
testTaskOverride,
testSolidityTask,
exampleEmptyTask,
exampleEmptySubtask,
],
privateKey: configVariable("privateKey"),
} satisfies HardhatUserConfig;
1 change: 1 addition & 0 deletions v-next/hardhat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
"@nomicfoundation/hardhat-errors": "workspace:^3.0.0",
"@nomicfoundation/hardhat-utils": "workspace:^3.0.0",
"@nomicfoundation/hardhat-zod-utils": "workspace:^3.0.0",
"chalk": "^5.3.0",
"tsx": "^4.11.0",
"zod": "^3.23.8"
}
Expand Down
42 changes: 42 additions & 0 deletions v-next/hardhat/src/internal/cli/helpers/getGlobalHelpString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { Task } from "@nomicfoundation/hardhat-core/types/tasks";

import { getHardhatVersion } from "../../utils/package.js";

import {
GLOBAL_NAME_PADDING,
GLOBAL_OPTIONS,
getLongestNameLength,
getSection,
parseTasks,
} from "./utils.js";

export async function getGlobalHelpString(
rootTasks: Map<string, Task>,
): Promise<string> {
const version = await getHardhatVersion();

const { tasks, subtasks } = parseTasks(rootTasks);

const namePadding =
getLongestNameLength([...tasks, ...subtasks, ...GLOBAL_OPTIONS]) +
GLOBAL_NAME_PADDING;

let output = `Hardhat version ${version}

Usage: hardhat [GLOBAL OPTIONS] <TASK> [SUBTASK] [TASK OPTIONS] [--] [TASK ARGUMENTS]
`;

if (tasks.length > 0) {
output += getSection("AVAILABLE TASKS", tasks, namePadding);
}

if (subtasks.length > 0) {
output += getSection("AVAILABLE SUBTASKS", subtasks, namePadding);
}

output += getSection("GLOBAL OPTIONS", GLOBAL_OPTIONS, namePadding);

output += `\nTo get help for a specific task run: npx hardhat <TASK> [SUBTASK] --help`;

return output;
}
60 changes: 60 additions & 0 deletions v-next/hardhat/src/internal/cli/helpers/getHelpString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import type { Task } from "@nomicfoundation/hardhat-core/types/tasks";

import {
GLOBAL_NAME_PADDING,
parseOptions,
getLongestNameLength,
getSection,
parseSubtasks,
getUsageString,
} from "./utils.js";

export async function getHelpString(task: Task): Promise<string> {
const { default: chalk } = await import("chalk");

const { options, positionalArguments } = parseOptions(task);

const subtasks = parseSubtasks(task);

const namePadding =
getLongestNameLength([...options, ...positionalArguments, ...subtasks]) +
GLOBAL_NAME_PADDING;

let output = `${chalk.bold(task.description)}`;

if (task.isEmpty) {
output += `\n\nUsage: hardhat [GLOBAL OPTIONS] ${task.id.join(" ")} <SUBTASK> [SUBTASK OPTIONS] [--] [SUBTASK POSITIONAL ARGUMENTS]\n`;

if (subtasks.length > 0) {
output += getSection("AVAILABLE SUBTASKS", subtasks, namePadding);

output += `\nTo get help for a specific task run: npx hardhat ${task.id.join(" ")} <SUBTASK> --help`;
}

return output;
}

const usage = getUsageString(task, options, positionalArguments);

output += `\n\n${usage}\n`;

if (options.length > 0) {
output += getSection("OPTIONS", options, namePadding);
}

if (positionalArguments.length > 0) {
output += getSection(
"POSITIONAL ARGUMENTS",
positionalArguments,
namePadding,
);
}

if (subtasks.length > 0) {
output += getSection("AVAILABLE SUBTASKS", subtasks, namePadding);
}

output += `\nFor global options help run: hardhat --help`;

return output;
}
129 changes: 129 additions & 0 deletions v-next/hardhat/src/internal/cli/helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import type { ParameterType } from "@nomicfoundation/hardhat-core/config";
import type { Task } from "@nomicfoundation/hardhat-core/types/tasks";

export const GLOBAL_OPTIONS = [
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a note: I think we can handle this and reserved words differently so that they are more unified with the rest of the global options.

For a follow up pr though

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I created an issue for this

{
name: "--config",
description: "A Hardhat config file.",
},
{
name: "--help",
description: "Shows this message, or a task's help if its name is provided",
},
{
name: "--show-stack-traces",
description: "Show stack traces (always enabled on CI servers).",
},
{
name: "--version",
description: "Shows hardhat's version.",
},
];

export const GLOBAL_NAME_PADDING = 6;

export function parseTasks(taskMap: Map<string, Task>): {
tasks: Array<{ name: string; description: string }>;
subtasks: Array<{ name: string; description: string }>;
} {
const tasks = [];
const subtasks = [];

for (const [taskName, task] of taskMap) {
subtasks.push(...parseSubtasks(task));

if (task.isEmpty) {
continue;
}

tasks.push({ name: taskName, description: task.description });
}

return { tasks, subtasks };
}

export function parseSubtasks(
task: Task,
): Array<{ name: string; description: string }> {
const subtasks = [];

for (const [, subtask] of task.subtasks) {
subtasks.push({
name: subtask.id.join(" "),
description: subtask.description,
});
}

return subtasks;
}

export function parseOptions(task: Task): {
options: Array<{ name: string; description: string; type: ParameterType }>;
positionalArguments: Array<{
name: string;
description: string;
isRequired: boolean;
}>;
} {
const options = [];
const positionalArguments = [];

for (const [optionName, option] of task.options) {
options.push({
name: formatOptionName(optionName),
description: option.description,
type: option.parameterType,
});
}

for (const argument of task.positionalParameters) {
positionalArguments.push({
name: argument.name,
description: argument.description,
isRequired: argument.defaultValue === undefined,
});
}

return { options, positionalArguments };
}

export function formatOptionName(str: string): string {
return `--${str
.split("")
.map((letter, idx) => {
return letter.toUpperCase() === letter
? `${idx !== 0 ? "-" : ""}${letter.toLowerCase()}`
: letter;
})
Comment on lines +93 to +97
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@schaable do we have a utility for this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we have the opposite (kebabToCamel). We should add this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added an issue to track it #5465

.join("")}`;
}

export function getLongestNameLength(tasks: Array<{ name: string }>): number {
return tasks.reduce((acc, { name }) => Math.max(acc, name.length), 0);
}

export function getSection(
title: string,
items: Array<{ name: string; description: string }>,
namePadding: number,
): string {
return `\n${title}:\n\n${items.map(({ name, description }) => ` ${name.padEnd(namePadding)}${description}`).join("\n")}\n`;
}

export function getUsageString(
task: Task,
options: ReturnType<typeof parseOptions>["options"],
positionalArguments: ReturnType<typeof parseOptions>["positionalArguments"],
): string {
let output = `Usage: hardhat [GLOBAL OPTIONS] ${task.id.join(" ")}`;

if (options.length > 0) {
output += ` ${options.map((o) => `[${o.name}${o.type === "BOOLEAN" ? "" : ` <${o.type}>`}]`).join(" ")}`;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Options and positional arguments can be optional if they have a default value. In that case, they need to be wrapped around "[]`, otherwise they don't.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed, these options may all be, well... optional

#5419

}

if (positionalArguments.length > 0) {
output += ` [--] ${positionalArguments.map((a) => (a.isRequired ? a.name : `[${a.name}]`)).join(" ")}`;
}

return output;
}
Loading
Loading