Skip to content

Commit

Permalink
chore: remove getConfig helper function, centralising logic surroundi…
Browse files Browse the repository at this point in the history
…ng how to find the config file given various command line args (#7477)
  • Loading branch information
andyjessop authored Dec 9, 2024
1 parent 90fa58b commit a29a41c
Show file tree
Hide file tree
Showing 67 changed files with 183 additions and 193 deletions.
6 changes: 3 additions & 3 deletions fixtures/import-npm/package-lock.json

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

4 changes: 2 additions & 2 deletions packages/wrangler/src/__tests__/configuration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 19,7 @@ describe("readConfig()", () => {
main: "index.py",
compatibility_flags: ["python_workers"],
});
const config = readConfig("wrangler.toml", {});
const config = readConfig({ config: "wrangler.toml" });
expect(config.rules).toMatchInlineSnapshot(`
Array [
Object {
Expand All @@ -36,7 36,7 @@ describe("readConfig()", () => {
main: "index.py",
});
try {
readConfig("wrangler.toml", {});
readConfig({ config: "wrangler.toml" });
expect.fail();
} catch (e) {
expect(e).toMatchInlineSnapshot(
Expand Down
5 changes: 3 additions & 2 deletions packages/wrangler/src/api/integrations/platform/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 103,8 @@ export async function getPlatformProxy<
): Promise<PlatformProxy<Env, CfProperties>> {
const env = options.environment;

const rawConfig = readConfig(options.configPath, {
const rawConfig = readConfig({
config: options.configPath,
env,
});

Expand Down Expand Up @@ -263,7 264,7 @@ export function unstable_getMiniflareWorkerOptions(
): Unstable_MiniflareWorkerOptions {
const config =
typeof configOrConfigPath === "string"
? readConfig(configOrConfigPath, { env })
? readConfig({ config: configOrConfigPath, env })
: configOrConfigPath;

const modulesRules: ModuleRule[] = config.rules
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/api/pages/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 160,7 @@ export async function deploy({
let config: Config | undefined;

try {
config = readPagesConfig(undefined, { ...args, env });
config = readPagesConfig({ ...args, env });
} catch (err) {
if (
!(
Expand Down
3 changes: 2 additions & 1 deletion packages/wrangler/src/api/startDevWorker/ConfigController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 414,8 @@ export class ConfigController extends Controller<ConfigControllerEventMap> {
const signal = this.#abortController.signal;
this.latestInput = input;
try {
const fileConfig = readConfig(input.config, {
const fileConfig = readConfig({
config: input.config,
env: input.env,
"dispatch-namespace": undefined,
"legacy-env": !input.legacy?.enableServiceEnvironments,
Expand Down
14 changes: 7 additions & 7 deletions packages/wrangler/src/cloudchamber/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,19 97,19 @@ export function handleFailure<
? K
: never,
>(
cb: (t: CommandArgumentsObject, config: Config) => Promise<void>
cb: (args: CommandArgumentsObject, config: Config) => Promise<void>
): (
t: CommonYargsOptions &
args: CommonYargsOptions &
CommandArgumentsObject &
CommonCloudchamberConfiguration
) => Promise<void> {
return async (t) => {
return async (args) => {
try {
const config = readConfig(t.config, t);
await fillOpenAPIConfiguration(config, t.json);
await cb(t, config);
const config = readConfig(args);
await fillOpenAPIConfiguration(config, args.json);
await cb(args, config);
} catch (err) {
if (!t.json) {
if (!args.json) {
throw err;
}

Expand Down
36 changes: 36 additions & 0 deletions packages/wrangler/src/config/config-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 1,36 @@
import path from "path";
import { findUpSync } from "find-up";

/**
* Resolve the path to the configuration file, given the `config` and `script` optional command line arguments.
* `config` takes precedence, then `script`, then we just use the cwd.
*/
export function resolveWranglerConfigPath({
config,
script,
}: {
config?: string;
script?: string;
}): string | undefined {
if (config !== undefined) {
return config;
}

const leafPath = script !== undefined ? path.dirname(script) : process.cwd();

return findWranglerConfig(leafPath);
}

/**
* Find the wrangler config file by searching up the file-system
* from the current working directory.
*/
export function findWranglerConfig(
referencePath: string = process.cwd()
): string | undefined {
return (
findUpSync(`wrangler.json`, { cwd: referencePath }) ??
findUpSync(`wrangler.jsonc`, { cwd: referencePath }) ??
findUpSync(`wrangler.toml`, { cwd: referencePath })
);
}
41 changes: 11 additions & 30 deletions packages/wrangler/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 2,12 @@ import fs from "node:fs";
import TOML from "@iarna/toml";
import chalk from "chalk";
import dotenv from "dotenv";
import { findUpSync } from "find-up";
import { FatalError, UserError } from "../errors";
import { getFlag } from "../experimental-flags";
import { logger } from "../logger";
import { EXIT_CODE_INVALID_PAGES_CONFIG } from "../pages/errors";
import { parseJSONC, parseTOML, readFileSync } from "../parse";
import { resolveWranglerConfigPath } from "./config-helpers";
import { isPagesConfig, normalizeAndValidateConfig } from "./validation";
import { validatePagesConfig } from "./validation-pages";
import type { CfWorkerInit } from "../deployment-bundle/worker";
Expand Down Expand Up @@ -66,25 66,23 @@ export function formatConfigSnippet(
}
}

type ReadConfigCommandArgs = NormalizeAndValidateConfigArgs;
type ReadConfigCommandArgs = NormalizeAndValidateConfigArgs & {
config?: string;
script?: string;
};

/**
* Get the Wrangler configuration; read it from the give `configPath` if available.
*/
export function readConfig(
configPath: string | undefined,
args: ReadConfigCommandArgs,
options?: { hideWarnings?: boolean }
): Config;
export function readConfig(
configPath: string | undefined,
args: ReadConfigCommandArgs,
{ hideWarnings = false }: { hideWarnings?: boolean } = {}
): Config {
if (!configPath) {
configPath = findWranglerConfig(process.cwd());
}

const configPath = resolveWranglerConfigPath(args);
const rawConfig = readRawConfig(configPath);

const { config, diagnostics } = normalizeAndValidateConfig(
Expand All @@ -104,13 102,10 @@ export function readConfig(
}

export function readPagesConfig(
configPath: string | undefined,
args: ReadConfigCommandArgs,
{ hideWarnings = false }: { hideWarnings?: boolean } = {}
): Omit<Config, "pages_build_output_dir"> & { pages_build_output_dir: string } {
if (!configPath) {
configPath = findWranglerConfig(process.cwd());
}
const configPath = resolveWranglerConfigPath(args);

let rawConfig: RawConfig;
try {
Expand Down Expand Up @@ -173,20 168,6 @@ export const readRawConfig = (configPath: string | undefined): RawConfig => {
return {};
};

/**
* Find the wrangler config file by searching up the file-system
* from the current working directory.
*/
export function findWranglerConfig(
referencePath: string = process.cwd()
): string | undefined {
return (
findUpSync(`wrangler.json`, { cwd: referencePath }) ??
findUpSync(`wrangler.jsonc`, { cwd: referencePath }) ??
findUpSync(`wrangler.toml`, { cwd: referencePath })
);
}

function addLocalSuffix(
id: string | symbol | undefined,
local: boolean = false
Expand Down Expand Up @@ -660,12 641,12 @@ export function printBindings(

export function withConfig<T>(
handler: (
t: OnlyCamelCase<T & CommonYargsOptions> & { config: Config }
args: OnlyCamelCase<T & CommonYargsOptions> & { config: Config }
) => Promise<void>,
options?: Parameters<typeof readConfig>[2]
options?: Parameters<typeof readConfig>[1]
) {
return (t: OnlyCamelCase<T & CommonYargsOptions>) => {
return handler({ ...t, config: readConfig(t.config, t, options) });
return (args: OnlyCamelCase<T & CommonYargsOptions>) => {
return handler({ ...args, config: readConfig(args, options) });
};
}

Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/core/register-yargs-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 82,7 @@ function createHandler(def: CommandDefinition) {
await def.handler(args, {
config:
def.behaviour?.provideConfig ?? true
? readConfig(args.config, args, {
? readConfig(args, {
hideWarnings: !(def.behaviour?.printConfigWarnings ?? true),
})
: defaultWranglerConfig,
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/d1/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 111,7 @@ export const Handler = async (args: HandlerOptions): Promise<void> => {
}
await printWranglerBanner();

const config = readConfig(args.config, args);
const config = readConfig(args);

if (file && command) {
throw createFatalError(
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/d1/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 74,7 @@ type HandlerOptions = StrictYargsOptionsToInterface<typeof Options>;
export const Handler = async (args: HandlerOptions): Promise<void> => {
const { local, remote, name, output, schema, data, table } = args;
await printWranglerBanner();
const config = readConfig(args.config, args);
const config = readConfig(args);

if (!local && !remote) {
throw new UserError(`You must specify either --local or --remote`);
Expand Down
8 changes: 2 additions & 6 deletions packages/wrangler/src/delete.ts
Original file line number Diff line number Diff line change
@@ -1,7 1,6 @@
import assert from "assert";
import path from "path";
import { fetchResult } from "./cfetch";
import { configFileName, findWranglerConfig, readConfig } from "./config";
import { configFileName, readConfig } from "./config";
import { confirm } from "./dialogs";
import { UserError } from "./errors";
import { deleteKVNamespace, listKVNamespaces } from "./kv/helpers";
Expand Down Expand Up @@ -94,10 93,7 @@ type DeleteArgs = StrictYargsOptionsToInterface<typeof deleteOptions>;
export async function deleteHandler(args: DeleteArgs) {
await printWranglerBanner();

const configPath =
args.config ||
(args.script && findWranglerConfig(path.dirname(args.script)));
const config = readConfig(configPath, args);
const config = readConfig(args);
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\n"
Expand Down
9 changes: 4 additions & 5 deletions packages/wrangler/src/deploy/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 1,8 @@
import assert from "node:assert";
import path from "node:path";
import { getAssetsOptions, validateAssetsArgsAndConfig } from "../assets";
import { configFileName, findWranglerConfig, readConfig } from "../config";
import { configFileName, readConfig } from "../config";
import { resolveWranglerConfigPath } from "../config/config-helpers";
import { getEntry } from "../deployment-bundle/entry";
import { UserError } from "../errors";
import { run } from "../experimental-flags";
Expand Down Expand Up @@ -262,11 263,9 @@ async function deployWorker(args: DeployArgs) {
);
}

const configPath =
args.config ||
(args.script && findWranglerConfig(path.dirname(args.script)));
const configPath = resolveWranglerConfigPath(args);
const projectRoot = configPath && path.dirname(configPath);
const config = readConfig(configPath, args);
const config = readConfig(args);
if (config.pages_build_output_dir) {
throw new UserError(
"It looks like you've run a Workers-specific command in a Pages project.\n"
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/deployments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 323,7 @@ export async function commonDeploymentCMDSetup(
yargs: ArgumentsCamelCase<CommonYargsOptions>
) {
await printWranglerBanner();
const config = readConfig(yargs.config, yargs);
const config = readConfig(yargs);
const accountId = await requireAuth(config);
const scriptName = getScriptName(
{ name: yargs.name as string, env: undefined },
Expand Down
11 changes: 3 additions & 8 deletions packages/wrangler/src/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 10,8 @@ import {
convertCfWorkerInitBindingstoBindings,
extractBindingsOfType,
} from "./api/startDevWorker/utils";
import {
configFileName,
findWranglerConfig,
formatConfigSnippet,
} from "./config";
import { configFileName, formatConfigSnippet } from "./config";
import { resolveWranglerConfigPath } from "./config/config-helpers";
import { createCommand } from "./core/create-command";
import { validateRoutes } from "./deploy/deploy";
import { validateNodeCompatMode } from "./deployment-bundle/node-compat";
Expand Down Expand Up @@ -703,9 700,7 @@ export async function startDev(args: StartDevOptions) {
);
}

const configPath =
args.config ||
(args.script && findWranglerConfig(path.dirname(args.script)));
const configPath = resolveWranglerConfigPath(args);

const authHook: AsyncHook<CfAccount, [Pick<Config, "account_id">]> = async (
config
Expand Down
10 changes: 5 additions & 5 deletions packages/wrangler/src/dispatch-namespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 113,7 @@ export function workerNamespaceCommands(
"List all dispatch namespaces",
(args) => args,
async (args) => {
const config = readConfig(args.config, args);
const config = readConfig(args);
const accountId = await requireAuth(config);
await listWorkerNamespaces(accountId);
metrics.sendMetricsEvent("list dispatch namespaces", {
Expand All @@ -132,7 132,7 @@ export function workerNamespaceCommands(
});
},
async (args) => {
const config = readConfig(args.config, args);
const config = readConfig(args);
const accountId = await requireAuth(config);
await getWorkerNamespaceInfo(accountId, args.name);
metrics.sendMetricsEvent("view dispatch namespace", {
Expand All @@ -152,7 152,7 @@ export function workerNamespaceCommands(
},
async (args) => {
await printWranglerBanner();
const config = readConfig(args.config, args);
const config = readConfig(args);
const accountId = await requireAuth(config);
await createWorkerNamespace(accountId, args.name);
metrics.sendMetricsEvent("create dispatch namespace", {
Expand All @@ -172,7 172,7 @@ export function workerNamespaceCommands(
},
async (args) => {
await printWranglerBanner();
const config = readConfig(args.config, args);
const config = readConfig(args);
const accountId = await requireAuth(config);
await deleteWorkerNamespace(accountId, args.name);
metrics.sendMetricsEvent("delete dispatch namespace", {
Expand All @@ -198,7 198,7 @@ export function workerNamespaceCommands(
},
async (args) => {
await printWranglerBanner();
const config = readConfig(args.config, args);
const config = readConfig(args);
const accountId = await requireAuth(config);
await renameWorkerNamespace(accountId, args.oldName, args.newName);
metrics.sendMetricsEvent("rename dispatch namespace", {
Expand Down
Loading

0 comments on commit a29a41c

Please sign in to comment.