Skip to content

Commit a29a41c

Browse files
authored
chore: remove getConfig helper function, centralising logic surrounding how to find the config file given various command line args (#7477)
1 parent 90fa58b commit a29a41c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+183
-193
lines changed

fixtures/import-npm/package-lock.json

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/wrangler/src/__tests__/configuration.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ describe("readConfig()", () => {
1919
main: "index.py",
2020
compatibility_flags: ["python_workers"],
2121
});
22-
const config = readConfig("wrangler.toml", {});
22+
const config = readConfig({ config: "wrangler.toml" });
2323
expect(config.rules).toMatchInlineSnapshot(`
2424
Array [
2525
Object {
@@ -36,7 +36,7 @@ describe("readConfig()", () => {
3636
main: "index.py",
3737
});
3838
try {
39-
readConfig("wrangler.toml", {});
39+
readConfig({ config: "wrangler.toml" });
4040
expect.fail();
4141
} catch (e) {
4242
expect(e).toMatchInlineSnapshot(

packages/wrangler/src/api/integrations/platform/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,8 @@ export async function getPlatformProxy<
103103
): Promise<PlatformProxy<Env, CfProperties>> {
104104
const env = options.environment;
105105

106-
const rawConfig = readConfig(options.configPath, {
106+
const rawConfig = readConfig({
107+
config: options.configPath,
107108
env,
108109
});
109110

@@ -263,7 +264,7 @@ export function unstable_getMiniflareWorkerOptions(
263264
): Unstable_MiniflareWorkerOptions {
264265
const config =
265266
typeof configOrConfigPath === "string"
266-
? readConfig(configOrConfigPath, { env })
267+
? readConfig({ config: configOrConfigPath, env })
267268
: configOrConfigPath;
268269

269270
const modulesRules: ModuleRule[] = config.rules

packages/wrangler/src/api/pages/deploy.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ export async function deploy({
160160
let config: Config | undefined;
161161

162162
try {
163-
config = readPagesConfig(undefined, { ...args, env });
163+
config = readPagesConfig({ ...args, env });
164164
} catch (err) {
165165
if (
166166
!(

packages/wrangler/src/api/startDevWorker/ConfigController.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,8 @@ export class ConfigController extends Controller<ConfigControllerEventMap> {
414414
const signal = this.#abortController.signal;
415415
this.latestInput = input;
416416
try {
417-
const fileConfig = readConfig(input.config, {
417+
const fileConfig = readConfig({
418+
config: input.config,
418419
env: input.env,
419420
"dispatch-namespace": undefined,
420421
"legacy-env": !input.legacy?.enableServiceEnvironments,

packages/wrangler/src/cloudchamber/common.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,19 +97,19 @@ export function handleFailure<
9797
? K
9898
: never,
9999
>(
100-
cb: (t: CommandArgumentsObject, config: Config) => Promise<void>
100+
cb: (args: CommandArgumentsObject, config: Config) => Promise<void>
101101
): (
102-
t: CommonYargsOptions &
102+
args: CommonYargsOptions &
103103
CommandArgumentsObject &
104104
CommonCloudchamberConfiguration
105105
) => Promise<void> {
106-
return async (t) => {
106+
return async (args) => {
107107
try {
108-
const config = readConfig(t.config, t);
109-
await fillOpenAPIConfiguration(config, t.json);
110-
await cb(t, config);
108+
const config = readConfig(args);
109+
await fillOpenAPIConfiguration(config, args.json);
110+
await cb(args, config);
111111
} catch (err) {
112-
if (!t.json) {
112+
if (!args.json) {
113113
throw err;
114114
}
115115

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import path from "path";
2+
import { findUpSync } from "find-up";
3+
4+
/**
5+
* Resolve the path to the configuration file, given the `config` and `script` optional command line arguments.
6+
* `config` takes precedence, then `script`, then we just use the cwd.
7+
*/
8+
export function resolveWranglerConfigPath({
9+
config,
10+
script,
11+
}: {
12+
config?: string;
13+
script?: string;
14+
}): string | undefined {
15+
if (config !== undefined) {
16+
return config;
17+
}
18+
19+
const leafPath = script !== undefined ? path.dirname(script) : process.cwd();
20+
21+
return findWranglerConfig(leafPath);
22+
}
23+
24+
/**
25+
* Find the wrangler config file by searching up the file-system
26+
* from the current working directory.
27+
*/
28+
export function findWranglerConfig(
29+
referencePath: string = process.cwd()
30+
): string | undefined {
31+
return (
32+
findUpSync(`wrangler.json`, { cwd: referencePath }) ??
33+
findUpSync(`wrangler.jsonc`, { cwd: referencePath }) ??
34+
findUpSync(`wrangler.toml`, { cwd: referencePath })
35+
);
36+
}

packages/wrangler/src/config/index.ts

Lines changed: 11 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ import fs from "node:fs";
22
import TOML from "@iarna/toml";
33
import chalk from "chalk";
44
import dotenv from "dotenv";
5-
import { findUpSync } from "find-up";
65
import { FatalError, UserError } from "../errors";
76
import { getFlag } from "../experimental-flags";
87
import { logger } from "../logger";
98
import { EXIT_CODE_INVALID_PAGES_CONFIG } from "../pages/errors";
109
import { parseJSONC, parseTOML, readFileSync } from "../parse";
10+
import { resolveWranglerConfigPath } from "./config-helpers";
1111
import { isPagesConfig, normalizeAndValidateConfig } from "./validation";
1212
import { validatePagesConfig } from "./validation-pages";
1313
import type { CfWorkerInit } from "../deployment-bundle/worker";
@@ -66,25 +66,23 @@ export function formatConfigSnippet(
6666
}
6767
}
6868

69-
type ReadConfigCommandArgs = NormalizeAndValidateConfigArgs;
69+
type ReadConfigCommandArgs = NormalizeAndValidateConfigArgs & {
70+
config?: string;
71+
script?: string;
72+
};
7073

7174
/**
7275
* Get the Wrangler configuration; read it from the give `configPath` if available.
7376
*/
7477
export function readConfig(
75-
configPath: string | undefined,
7678
args: ReadConfigCommandArgs,
7779
options?: { hideWarnings?: boolean }
7880
): Config;
7981
export function readConfig(
80-
configPath: string | undefined,
8182
args: ReadConfigCommandArgs,
8283
{ hideWarnings = false }: { hideWarnings?: boolean } = {}
8384
): Config {
84-
if (!configPath) {
85-
configPath = findWranglerConfig(process.cwd());
86-
}
87-
85+
const configPath = resolveWranglerConfigPath(args);
8886
const rawConfig = readRawConfig(configPath);
8987

9088
const { config, diagnostics } = normalizeAndValidateConfig(
@@ -104,13 +102,10 @@ export function readConfig(
104102
}
105103

106104
export function readPagesConfig(
107-
configPath: string | undefined,
108105
args: ReadConfigCommandArgs,
109106
{ hideWarnings = false }: { hideWarnings?: boolean } = {}
110107
): Omit<Config, "pages_build_output_dir"> & { pages_build_output_dir: string } {
111-
if (!configPath) {
112-
configPath = findWranglerConfig(process.cwd());
113-
}
108+
const configPath = resolveWranglerConfigPath(args);
114109

115110
let rawConfig: RawConfig;
116111
try {
@@ -173,20 +168,6 @@ export const readRawConfig = (configPath: string | undefined): RawConfig => {
173168
return {};
174169
};
175170

176-
/**
177-
* Find the wrangler config file by searching up the file-system
178-
* from the current working directory.
179-
*/
180-
export function findWranglerConfig(
181-
referencePath: string = process.cwd()
182-
): string | undefined {
183-
return (
184-
findUpSync(`wrangler.json`, { cwd: referencePath }) ??
185-
findUpSync(`wrangler.jsonc`, { cwd: referencePath }) ??
186-
findUpSync(`wrangler.toml`, { cwd: referencePath })
187-
);
188-
}
189-
190171
function addLocalSuffix(
191172
id: string | symbol | undefined,
192173
local: boolean = false
@@ -660,12 +641,12 @@ export function printBindings(
660641

661642
export function withConfig<T>(
662643
handler: (
663-
t: OnlyCamelCase<T & CommonYargsOptions> & { config: Config }
644+
args: OnlyCamelCase<T & CommonYargsOptions> & { config: Config }
664645
) => Promise<void>,
665-
options?: Parameters<typeof readConfig>[2]
646+
options?: Parameters<typeof readConfig>[1]
666647
) {
667-
return (t: OnlyCamelCase<T & CommonYargsOptions>) => {
668-
return handler({ ...t, config: readConfig(t.config, t, options) });
648+
return (args: OnlyCamelCase<T & CommonYargsOptions>) => {
649+
return handler({ ...args, config: readConfig(args, options) });
669650
};
670651
}
671652

packages/wrangler/src/core/register-yargs-command.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ function createHandler(def: CommandDefinition) {
8282
await def.handler(args, {
8383
config:
8484
def.behaviour?.provideConfig ?? true
85-
? readConfig(args.config, args, {
85+
? readConfig(args, {
8686
hideWarnings: !(def.behaviour?.printConfigWarnings ?? true),
8787
})
8888
: defaultWranglerConfig,

packages/wrangler/src/d1/execute.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export const Handler = async (args: HandlerOptions): Promise<void> => {
111111
}
112112
await printWranglerBanner();
113113

114-
const config = readConfig(args.config, args);
114+
const config = readConfig(args);
115115

116116
if (file && command) {
117117
throw createFatalError(

packages/wrangler/src/d1/export.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ type HandlerOptions = StrictYargsOptionsToInterface<typeof Options>;
7474
export const Handler = async (args: HandlerOptions): Promise<void> => {
7575
const { local, remote, name, output, schema, data, table } = args;
7676
await printWranglerBanner();
77-
const config = readConfig(args.config, args);
77+
const config = readConfig(args);
7878

7979
if (!local && !remote) {
8080
throw new UserError(`You must specify either --local or --remote`);

packages/wrangler/src/delete.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import assert from "assert";
2-
import path from "path";
32
import { fetchResult } from "./cfetch";
4-
import { configFileName, findWranglerConfig, readConfig } from "./config";
3+
import { configFileName, readConfig } from "./config";
54
import { confirm } from "./dialogs";
65
import { UserError } from "./errors";
76
import { deleteKVNamespace, listKVNamespaces } from "./kv/helpers";
@@ -94,10 +93,7 @@ type DeleteArgs = StrictYargsOptionsToInterface<typeof deleteOptions>;
9493
export async function deleteHandler(args: DeleteArgs) {
9594
await printWranglerBanner();
9695

97-
const configPath =
98-
args.config ||
99-
(args.script && findWranglerConfig(path.dirname(args.script)));
100-
const config = readConfig(configPath, args);
96+
const config = readConfig(args);
10197
if (config.pages_build_output_dir) {
10298
throw new UserError(
10399
"It looks like you've run a Workers-specific command in a Pages project.\n" +

packages/wrangler/src/deploy/index.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import assert from "node:assert";
22
import path from "node:path";
33
import { getAssetsOptions, validateAssetsArgsAndConfig } from "../assets";
4-
import { configFileName, findWranglerConfig, readConfig } from "../config";
4+
import { configFileName, readConfig } from "../config";
5+
import { resolveWranglerConfigPath } from "../config/config-helpers";
56
import { getEntry } from "../deployment-bundle/entry";
67
import { UserError } from "../errors";
78
import { run } from "../experimental-flags";
@@ -262,11 +263,9 @@ async function deployWorker(args: DeployArgs) {
262263
);
263264
}
264265

265-
const configPath =
266-
args.config ||
267-
(args.script && findWranglerConfig(path.dirname(args.script)));
266+
const configPath = resolveWranglerConfigPath(args);
268267
const projectRoot = configPath && path.dirname(configPath);
269-
const config = readConfig(configPath, args);
268+
const config = readConfig(args);
270269
if (config.pages_build_output_dir) {
271270
throw new UserError(
272271
"It looks like you've run a Workers-specific command in a Pages project.\n" +

packages/wrangler/src/deployments.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ export async function commonDeploymentCMDSetup(
323323
yargs: ArgumentsCamelCase<CommonYargsOptions>
324324
) {
325325
await printWranglerBanner();
326-
const config = readConfig(yargs.config, yargs);
326+
const config = readConfig(yargs);
327327
const accountId = await requireAuth(config);
328328
const scriptName = getScriptName(
329329
{ name: yargs.name as string, env: undefined },

packages/wrangler/src/dev.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,8 @@ import {
1010
convertCfWorkerInitBindingstoBindings,
1111
extractBindingsOfType,
1212
} from "./api/startDevWorker/utils";
13-
import {
14-
configFileName,
15-
findWranglerConfig,
16-
formatConfigSnippet,
17-
} from "./config";
13+
import { configFileName, formatConfigSnippet } from "./config";
14+
import { resolveWranglerConfigPath } from "./config/config-helpers";
1815
import { createCommand } from "./core/create-command";
1916
import { validateRoutes } from "./deploy/deploy";
2017
import { validateNodeCompatMode } from "./deployment-bundle/node-compat";
@@ -703,9 +700,7 @@ export async function startDev(args: StartDevOptions) {
703700
);
704701
}
705702

706-
const configPath =
707-
args.config ||
708-
(args.script && findWranglerConfig(path.dirname(args.script)));
703+
const configPath = resolveWranglerConfigPath(args);
709704

710705
const authHook: AsyncHook<CfAccount, [Pick<Config, "account_id">]> = async (
711706
config

packages/wrangler/src/dispatch-namespace.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ export function workerNamespaceCommands(
113113
"List all dispatch namespaces",
114114
(args) => args,
115115
async (args) => {
116-
const config = readConfig(args.config, args);
116+
const config = readConfig(args);
117117
const accountId = await requireAuth(config);
118118
await listWorkerNamespaces(accountId);
119119
metrics.sendMetricsEvent("list dispatch namespaces", {
@@ -132,7 +132,7 @@ export function workerNamespaceCommands(
132132
});
133133
},
134134
async (args) => {
135-
const config = readConfig(args.config, args);
135+
const config = readConfig(args);
136136
const accountId = await requireAuth(config);
137137
await getWorkerNamespaceInfo(accountId, args.name);
138138
metrics.sendMetricsEvent("view dispatch namespace", {
@@ -152,7 +152,7 @@ export function workerNamespaceCommands(
152152
},
153153
async (args) => {
154154
await printWranglerBanner();
155-
const config = readConfig(args.config, args);
155+
const config = readConfig(args);
156156
const accountId = await requireAuth(config);
157157
await createWorkerNamespace(accountId, args.name);
158158
metrics.sendMetricsEvent("create dispatch namespace", {
@@ -172,7 +172,7 @@ export function workerNamespaceCommands(
172172
},
173173
async (args) => {
174174
await printWranglerBanner();
175-
const config = readConfig(args.config, args);
175+
const config = readConfig(args);
176176
const accountId = await requireAuth(config);
177177
await deleteWorkerNamespace(accountId, args.name);
178178
metrics.sendMetricsEvent("delete dispatch namespace", {
@@ -198,7 +198,7 @@ export function workerNamespaceCommands(
198198
},
199199
async (args) => {
200200
await printWranglerBanner();
201-
const config = readConfig(args.config, args);
201+
const config = readConfig(args);
202202
const accountId = await requireAuth(config);
203203
await renameWorkerNamespace(accountId, args.oldName, args.newName);
204204
metrics.sendMetricsEvent("rename dispatch namespace", {

0 commit comments

Comments
 (0)