Skip to content

Commit

Permalink
interactive, cloudchamber: replace error calls with crash, and crash …
Browse files Browse the repository at this point in the history
…now calls error() and exits
  • Loading branch information
gabivlj committed Jan 17, 2024
1 parent 7155aff commit 0ed1b60
Show file tree
Hide file tree
Showing 13 changed files with 62 additions and 64 deletions.
7 changes: 5 additions & 2 deletions packages/cli/args.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getRenderers, inputPrompt } from "./interactive";
import { logRaw } from ".";
import { crash, logRaw } from ".";
import type { Arg, PromptConfig } from "./interactive";

export const processArgument = async <T>(
Expand All @@ -12,7 +12,10 @@ export const processArgument = async <T>(

// If the value has already been set via args, use that
if (value !== undefined) {
promptConfig.validate?.(value);
const error = promptConfig.validate?.(value);
if (error) {
crash(error);
}

const lines = renderSubmitted({ value });
logRaw(lines.join("\n"));
Expand Down
12 changes: 3 additions & 9 deletions packages/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
dim,
gray,
white,
red,
hidden,
bgRed,
bgYellow,
Expand Down Expand Up @@ -129,22 +128,17 @@ export const stripAnsi = (str: string) => {
return str.replace(regex, "");
};

export const crash: (msg?: string) => never = (msg) => {
if (msg) {
process.stderr.write(red(msg));
process.stderr.write("\n");
}
export const crash: (msg?: string, extra?: string) => never = (msg, extra) => {
error(msg, extra);
exit(1);
};

export const error = (msg?: string, extra?: string): never => {
export const error = (msg?: string, extra?: string) => {
if (msg) {
process.stderr.write(
`${gray(shapes.corners.bl)} ${status.error} ${dim(msg)}\n${
extra ? space() + extra + "\n" : ""
}`
);
}

exit(1);
};
39 changes: 20 additions & 19 deletions packages/cli/interactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import {
ConfirmPrompt,
isCancel,
MultiSelectPrompt,
Prompt,
SelectPrompt,
TextPrompt,
} from "@clack/core";
import { createLogUpdate } from "log-update";
import { blue, bold, brandColor, dim, gray, white } from "./colors";
import SelectRefreshablePrompt from "./select-list";
import { cancel, newline, shapes, space, status } from "./index";
import SelectRefreshablePrompt, { OptionWithDetails } from "./select-list";
import type { OptionWithDetails } from "./select-list";
import type { Prompt } from "@clack/core";

const logUpdate = createLogUpdate(process.stdout);

Expand All @@ -30,7 +31,7 @@ export type BasePromptConfig = {
// Further clarifies the question
helpText?: string;
// The value to use by default
defaultValue?: string | boolean | string[];
defaultValue?: Arg;
// The status label to be shown after submitting
label: string;
// Pretty-prints the value in the interactive prompt
Expand Down Expand Up @@ -280,11 +281,7 @@ const getSelectRenderers = (
return options.length - i <= maxItemsPerPage;
}

if (i >= cursor && cursor + maxItemsPerPage > i) {
return true;
}

return false;
return cursor + maxItemsPerPage > i;
};

return [
Expand Down Expand Up @@ -357,20 +354,20 @@ const getSelectListRenderers = (config: ListPromptConfig) => {
const isInListOfValues =
Array.isArray(value) && value.includes(optionValue);
const color = isInListOfValues || active ? blue : white;
const text = active
? color.underline(optionLabel?.toString() ?? "")
: color(optionLabel?.toString() ?? "");
const text = active ? color.underline(optionLabel) : color(optionLabel);

const indicator =
isInListOfValues || (active && !Array.isArray(value))
? color(shapes.radioActive)
: color(shapes.radioInactive);

const indicatorMargin = 2;
const detailBulletpointMargin = indicatorMargin + 4;
return [
`${space(2)}${indicator} ${text}`,
`${space(indicatorMargin)}${indicator} ${text}`,
...opt.details.map(
(detail, j) =>
`${space(6)}${
`${space(detailBulletpointMargin)}${
j === opt.details.length - 1 ? gray(shapes.corners.bl) : grayBar
} ${detail}`
),
Expand All @@ -384,19 +381,23 @@ const getSelectListRenderers = (config: ListPromptConfig) => {
size: 0,
options: [],
};
for (let index = 0; index < options.length; index++) {
const option = options[index];
if (current.size + option.details.length + 1 > rows - 6) {
const VERTICAL_MARGIN = 6;
for (const option of options) {
// If current accumulation of options + title row + option details size
// is bigger than console rows substracted by a bit of vertical margin,
// add a new page.
const optionHeight = option.details.length + 1;
if (current.size + optionHeight > rows - VERTICAL_MARGIN) {
pages.push(current.options);
current = { size: option.details.length + 1, options: [option] };
current = { size: optionHeight, options: [option] };
continue;
}

current.size += option.details.length + 1;
current.size += optionHeight;
current.options.push(option);
}

// add the last current
// add the last current as the last page
if (current.size !== 0) {
pages.push(current.options);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/create-cloudflare/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
startSection,
updateStatus,
} from "@cloudflare/cli";
import { processArgument } from "@cloudflare/cli/args";
import { bgGreen, blue, brandColor, dim, gray } from "@cloudflare/cli/colors";
import { inputPrompt, spinner } from "@cloudflare/cli/interactive";
import { getFrameworkCli } from "frameworks/index";
Expand All @@ -28,7 +29,6 @@ import { quote } from "shell-quote";
import { version as wranglerVersion } from "wrangler/package.json";
import { version } from "../package.json";
import type { C3Args, PagesGeneratorContext } from "types";
import { processArgument } from "@cloudflare/cli/args";

const { name, npm } = detectPackageManager();

Expand Down
2 changes: 1 addition & 1 deletion packages/create-cloudflare/src/frameworks/next/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { existsSync, mkdirSync } from "fs";
import { crash, updateStatus, warn } from "@cloudflare/cli";
import { processArgument } from "@cloudflare/cli/args";
import { brandColor, dim } from "@cloudflare/cli/colors";
import {
installPackages,
Expand Down Expand Up @@ -28,7 +29,6 @@ import {
readme,
} from "./templates";
import type { C3Args, FrameworkConfig, PagesGeneratorContext } from "types";
import { processArgument } from "@cloudflare/cli/args";

const { npm, npx } = detectPackageManager();

Expand Down
4 changes: 2 additions & 2 deletions packages/wrangler/src/cloudchamber/cli/deployments.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { exit } from "process";
import { error, endSection, log, cancel } from "@cloudflare/cli";
import { crash, endSection, log, cancel } from "@cloudflare/cli";
import { processArgument } from "@cloudflare/cli/args";
import { yellow, brandColor, dim } from "@cloudflare/cli/colors";
import { spinner } from "@cloudflare/cli/interactive";
Expand Down Expand Up @@ -77,7 +77,7 @@ export async function loadDeployments(

stop();

Check warning on line 78 in packages/wrangler/src/cloudchamber/cli/deployments.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/deployments.ts#L78

Added line #L78 was not covered by tests
if (err) {
error(
crash(

Check warning on line 80 in packages/wrangler/src/cloudchamber/cli/deployments.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/deployments.ts#L80

Added line #L80 was not covered by tests
"There has been an error while loading your deployments: \n " +
err.message
);
Expand Down
12 changes: 6 additions & 6 deletions packages/wrangler/src/cloudchamber/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
error,
crash,
updateStatus,
log,
endSection,
Expand Down Expand Up @@ -165,7 +165,7 @@ async function waitForImagePull(deployment: DeploymentV2) {
);
s.stop();

Check warning on line 166 in packages/wrangler/src/cloudchamber/cli/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/index.ts#L166

Added line #L166 was not covered by tests
if (err) {
error(err.message);
crash(err.message);
return;

Check warning on line 169 in packages/wrangler/src/cloudchamber/cli/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/index.ts#L168-L169

Added lines #L168 - L169 were not covered by tests
}

Expand All @@ -179,7 +179,7 @@ async function waitForImagePull(deployment: DeploymentV2) {
}

if (eventPlacement.event.name == "ImagePullError") {
error(
crash(

Check warning on line 182 in packages/wrangler/src/cloudchamber/cli/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/index.ts#L182

Added line #L182 was not covered by tests
"Your container image couldn't be pulled, (404 not found). Did you specify the correct URL?",
`Run ${brandColor(
process.argv0 + " cloudchamber modify " + deployment.id
Expand Down Expand Up @@ -217,7 +217,7 @@ async function waitForVMToStart(deployment: DeploymentV2) {
);
s.stop();

Check warning on line 218 in packages/wrangler/src/cloudchamber/cli/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/index.ts#L218

Added line #L218 was not covered by tests
if (err) {
error(err.message);
crash(err.message);
return;

Check warning on line 221 in packages/wrangler/src/cloudchamber/cli/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/index.ts#L220-L221

Added lines #L220 - L221 were not covered by tests
}

Expand Down Expand Up @@ -276,7 +276,7 @@ async function waitForPlacementInstance(deployment: DeploymentV2) {
}

if (err) {
error(err.message);
crash(err.message);
return;

Check warning on line 280 in packages/wrangler/src/cloudchamber/cli/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/index.ts#L279-L280

Added lines #L279 - L280 were not covered by tests
}

Expand Down Expand Up @@ -312,7 +312,7 @@ export async function waitForPlacement(deployment: DeploymentV2) {
DeploymentsService.getDeploymentV2(deployment.id)
);
if (getDeploymentError) {
error(
crash(

Check warning on line 315 in packages/wrangler/src/cloudchamber/cli/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/index.ts#L315

Added line #L315 was not covered by tests
"Couldn't retrieve a new deployment: " + getDeploymentError.message
);
return;

Check warning on line 318 in packages/wrangler/src/cloudchamber/cli/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/cli/index.ts#L318

Added line #L318 was not covered by tests
Expand Down
22 changes: 11 additions & 11 deletions packages/wrangler/src/cloudchamber/common.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { mkdir } from "fs/promises";
import { exit } from "process";
import { error, logRaw, space, status, updateStatus } from "@cloudflare/cli";
import { crash, logRaw, space, status, updateStatus } from "@cloudflare/cli";
import { dim, brandColor } from "@cloudflare/cli/colors";
import { inputPrompt, spinner } from "@cloudflare/cli/interactive";
import { version as wranglerVersion } from "../../package.json";
Expand Down Expand Up @@ -170,22 +170,22 @@ export async function fillOpenAPIConfiguration(config: Config, json: boolean) {
// This will prompt the user for an accountId being chosen if they haven't configured the account id yet
const [, err] = await wrap(requireAuth(config));

Check warning on line 171 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L171

Added line #L171 was not covered by tests
if (err) {
error("authenticating with the Cloudflare API:", err.message);
crash("authenticating with the Cloudflare API:", err.message);
return;

Check warning on line 174 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L173-L174

Added lines #L173 - L174 were not covered by tests
}
}

// Get the loaded API token
const token = getAPIToken();
if (!token) {
error("unexpected apiToken not existing in credentials");
crash("unexpected apiToken not existing in credentials");
exit(1);

Check warning on line 182 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L181-L182

Added lines #L181 - L182 were not covered by tests
}

const val = "apiToken" in token ? token.apiToken : null;
// Don't try to support this method of authentication
if (!val) {
error(
crash(

Check warning on line 188 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L188

Added line #L188 was not covered by tests
"we don't allow for authKey/email credentials, use `wrangler login` or CLOUDFLARE_API_TOKEN env variable to authenticate"
);
}
Expand All @@ -197,14 +197,14 @@ export async function fillOpenAPIConfiguration(config: Config, json: boolean) {
OpenAPI.CREDENTIALS = "omit";
const [base, errApiURL] = await wrap(getAPIUrl(config));
if (errApiURL) {
error("getting the API url:" + errApiURL.message);
crash("getting the API url:" + errApiURL.message);
return;

Check warning on line 201 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L200-L201

Added lines #L200 - L201 were not covered by tests
}

OpenAPI.BASE = base;
OpenAPI.HEADERS = headers;
const [, err] = await wrap(loadAccountSpinner({ json }));
if (err) error("loading Cloudchamber account failed:" + err.message);
if (err) crash("loading Cloudchamber account failed:" + err.message);
}

export function interactWithUser(config: { json?: boolean }): boolean {
Expand Down Expand Up @@ -300,23 +300,23 @@ export function renderDeploymentMutationError(
err: Error
) {

Check warning on line 301 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L301

Added line #L301 was not covered by tests
if (!(err instanceof ApiError)) {
error(err.message);
crash(err.message);
return;

Check warning on line 304 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L303-L304

Added lines #L303 - L304 were not covered by tests
}

if (typeof err.body === "string") {
error("There has been an internal error, please try again!");
crash("There has been an internal error, please try again!");
return;

Check warning on line 309 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L308-L309

Added lines #L308 - L309 were not covered by tests
}

if (!("error" in err.body)) {
error(err.message);
crash(err.message);
return;

Check warning on line 314 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L313-L314

Added lines #L313 - L314 were not covered by tests
}

const errorMessage = err.body.error;

Check warning on line 317 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L317

Added line #L317 was not covered by tests
if (!(errorMessage in DeploymentMutationError)) {
error(err.message);
crash(err.message);
return;

Check warning on line 320 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L319-L320

Added lines #L319 - L320 were not covered by tests
}

Expand Down Expand Up @@ -359,7 +359,7 @@ export function renderDeploymentMutationError(
"You have to configure the domain of the image you're trying to set\n",

Check warning on line 359 in packages/wrangler/src/cloudchamber/common.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/common.ts#L358-L359

Added lines #L358 - L359 were not covered by tests
};

error(details["reason"] ?? errorEnumToErrorMessage[errorEnum]());
crash(details["reason"] ?? errorEnumToErrorMessage[errorEnum]());
}

export function sortEnvironmentVariables(
Expand Down
4 changes: 2 additions & 2 deletions packages/wrangler/src/cloudchamber/delete.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { startSection, error, endSection, cancel } from "@cloudflare/cli";
import { startSection, crash, endSection, cancel } from "@cloudflare/cli";
import { inputPrompt } from "@cloudflare/cli/interactive";
import { logDeployment, pickDeployment } from "./cli/deployments";
import { DeploymentsService } from "./client";
Expand Down Expand Up @@ -63,7 +63,7 @@ async function handleDeleteCommand(
DeploymentsService.deleteDeploymentV2(deployment.id)
);
if (err) {
error(
crash(

Check warning on line 66 in packages/wrangler/src/cloudchamber/delete.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/delete.ts#L66

Added line #L66 was not covered by tests
`There has been an internal error deleting your deployment.\n ${err.message}`
);
return;

Check warning on line 69 in packages/wrangler/src/cloudchamber/delete.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/delete.ts#L69

Added line #L69 was not covered by tests
Expand Down
12 changes: 6 additions & 6 deletions packages/wrangler/src/cloudchamber/images/images.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { startSection, error, endSection } from "@cloudflare/cli";
import { startSection, crash, endSection } from "@cloudflare/cli";
import { processArgument } from "@cloudflare/cli/args";
import {
ApiError,
Expand Down Expand Up @@ -114,7 +114,7 @@ export const registriesCommand = (yargs: CommonYargsArgvJSON) => {
_config
) => {
if (!imageArgs.pull && !imageArgs.push) {
error(
crash(

Check warning on line 117 in packages/wrangler/src/cloudchamber/images/images.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/images/images.ts#L117

Added line #L117 was not covered by tests
"You have to specify either --push or --pull in the command."
);

Expand Down Expand Up @@ -179,13 +179,13 @@ export async function handleConfigureImageRegistryCommand(
const { error: errString } = err.body as { error: string };

Check warning on line 179 in packages/wrangler/src/cloudchamber/images/images.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/images/images.ts#L179

Added line #L179 was not covered by tests
switch (errString) {
case ImageRegistryAlreadyExistsError.error.IMAGE_REGISTRY_ALREADY_EXISTS:
error("The domain already exists!");
crash("The domain already exists!");
break;
case ImageRegistryNotAllowedError.error.IMAGE_REGISTRY_NOT_ALLOWED:
error("This domain is not allowed!");
crash("This domain is not allowed!");
break;
default:
error(
crash(

Check warning on line 188 in packages/wrangler/src/cloudchamber/images/images.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/images/images.ts#L181-L188

Added lines #L181 - L188 were not covered by tests
"An unexpected error happened, please try again or send us the error for troubleshooting\n" +
errString
);
Expand All @@ -195,7 +195,7 @@ export async function handleConfigureImageRegistryCommand(
}

if (err) {
error("There has been an internal error:", `${JSON.stringify(err)}`);
crash("There has been an internal error:", `${JSON.stringify(err)}`);
return;

Check warning on line 199 in packages/wrangler/src/cloudchamber/images/images.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/cloudchamber/images/images.ts#L198-L199

Added lines #L198 - L199 were not covered by tests
}

Expand Down
Loading

0 comments on commit 0ed1b60

Please sign in to comment.