Skip to content

Commit

Permalink
fix(cli)!: .env file not loaded when compiling outside sourceDir (#6348)
Browse files Browse the repository at this point in the history
Closes: #6346

## Breaking Change
- Removed the ability to specify command specific `.env` files

## Summary
Basically just moves the loading of environment files to the subcommands. Previously this loading was happening for all commands, which really doesnt make sense since some commands like `lsp`, `docs`, `init` dont need to load those env files. 

Also I several subcommands call the compile subcommand (secrets, test, etc..) so having subcommand specific `.env` files is additional overhead that Im not sure what the usecase it solves is. If needed, its probably just easier to just use a `--env-file` flag

## Checklist

- [x] Title matches [Winglang's style guide](https://www.winglang.io/contributing/start-here/pull_requests#how-are-pull-request-titles-formatted)
- [x] Description explains motivation and solution
- [x] Tests added (always)
- [ ] Docs updated (only required for features)
- [ ] Added `pr/e2e-full` label if this feature requires end-to-end testing

*By submitting this pull request, I confirm that my contribution is made under the terms of the [Wing Cloud Contribution License](https://github.com/winglang/wing/blob/main/CONTRIBUTION_LICENSE.md)*.
  • Loading branch information
hasanaburayyan authored Apr 26, 2024
1 parent 8375778 commit 0ef615f
Show file tree
Hide file tree
Showing 6 changed files with 10 additions and 28 deletions.
5 changes: 0 additions & 5 deletions apps/wing/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { satisfies } from "compare-versions";
import { optionallyDisplayDisclaimer } from "./analytics/disclaimer";
import { exportAnalytics } from "./analytics/export";
import { SNAPSHOTS_HELP } from "./commands/test/snapshots-help";
import { loadEnvVariables } from "./env";
import { currentPackage, projectTemplateNames } from "./util";

export const PACKAGE_VERSION = currentPackage.version;
Expand All @@ -22,10 +21,6 @@ const DEFAULT_PLATFORM = ["sim"];
let analyticsExportFile: Promise<string | undefined> | undefined;

function runSubCommand(subCommand: string, path: string = subCommand) {
loadEnvVariables({
mode: subCommand,
});

return async (...args: any[]) => {
try {
// paths other than the root path aren't working unless specified in the path arg
Expand Down
5 changes: 3 additions & 2 deletions apps/wing/src/commands/compile.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { promises as fsPromise } from "fs";
import { relative, resolve } from "path";
import { dirname, relative, resolve } from "path";

import * as wingCompiler from "@winglang/compiler";
import { prettyPrintError } from "@winglang/sdk/lib/util/enhanced-error";
import chalk from "chalk";
import { CHARS_ASCII, emitDiagnostic, File, Label } from "codespan-wasm";
import debug from "debug";
import { glob } from "glob";
import { loadEnvVariables } from "../env";

// increase the stack trace limit to 50, useful for debugging Rust panics
// (not setting the limit too high in case of infinite recursion)
Expand Down Expand Up @@ -78,7 +79,7 @@ export async function compile(entrypoint?: string, options?: CompileOptions): Pr
}
entrypoint = wingFiles[0];
}

loadEnvVariables({ cwd: resolve(dirname(entrypoint)) });
const coloring = chalk.supportsColor ? chalk.supportsColor.hasBasic : false;
try {
return await wingCompiler.compile(entrypoint, {
Expand Down
2 changes: 2 additions & 0 deletions apps/wing/src/commands/pack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { BuiltinPlatform } from "@winglang/compiler";
import packlist from "npm-packlist";
import * as tar from "tar";
import { compile } from "./compile";
import { loadEnvVariables } from "../env";

// TODO: add --dry-run option?
// TODO: let the user specify library's supported targets in package.json, and compile to each before packaging
Expand Down Expand Up @@ -79,6 +80,7 @@ export async function pack(options: PackageOptions = {}): Promise<string> {
const outfile = options.outFile ? resolve(options.outFile) : undefined;
const outdir = outfile ? path.dirname(outfile) : userDir;

loadEnvVariables({ cwd: userDir });
// check package.json exists
const originalPkgJsonPath = path.join(userDir, "package.json");
if (!(await exists(originalPkgJsonPath))) {
Expand Down
5 changes: 4 additions & 1 deletion apps/wing/src/commands/run.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { existsSync } from "fs";
import { resolve } from "path";
import { dirname, resolve } from "path";
import { createConsoleApp } from "@wingconsole/app";
import { BuiltinPlatform } from "@winglang/compiler";
import { debug } from "debug";
import { glob } from "glob";
import once from "lodash.once";
import { loadEnvVariables } from "../env";
import { parseNumericString } from "../util";
import { beforeShutdown } from "../util.before-shutdown.js";

Expand Down Expand Up @@ -63,6 +64,8 @@ export async function run(entrypoint?: string, options?: RunOptions) {
throw new Error(entrypoint + " doesn't exist");
}

loadEnvVariables({ cwd: resolve(dirname(entrypoint)) });

if (options?.platform && options?.platform[0] !== BuiltinPlatform.SIM) {
throw new Error(
`The first platform in the list must be the sim platform (try "-t sim -t ${options.platform.join(
Expand Down
10 changes: 1 addition & 9 deletions apps/wing/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,14 @@ export interface EnvLoadOptions {
* @default process.cwd()
*/
cwd?: string;

/**
* The mode to load additional environment variables from.
* e.g. "wing compile" has mode "compile", which will load ".env.compile" and ".env.compile.local".
*/
mode?: string;
}

/**
* Loads environment variables from `.env` and `.env.local` files.
*/
export function loadEnvVariables(options?: EnvLoadOptions): Record<string, string> | undefined {
const envDir = options?.cwd ?? process.cwd();
const envFiles = DEFAULT_ENV_FILES.concat(
options?.mode ? [`.env.${options.mode}`, `.env.${options.mode}.local`] : []
).map((file) => join(envDir, file));
const envFiles = DEFAULT_ENV_FILES.map((file) => join(envDir, file));

// Parse `envFiles` and combine their variables into a single object
const parsed = Object.fromEntries(
Expand Down
11 changes: 0 additions & 11 deletions libs/wingsdk/src/target-sim/secret.inflight.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import * as fs from "fs";
import * as path from "path";
import { SecretAttributes, SecretSchema } from "./schema-resources";
import { ISecretClient, SECRET_FQN } from "../cloud";
import {
Expand All @@ -11,18 +9,9 @@ import { Json, TraceType } from "../std";

export class Secret implements ISecretClient, ISimulatorResourceInstance {
private _context: ISimulatorContext | undefined;
private readonly secretsFile: string;
private readonly name: string;

constructor(props: SecretSchema) {
this.secretsFile = path.join(process.cwd(), ".env");

if (!fs.existsSync(this.secretsFile)) {
throw new Error(
`No secrets file found at ${this.secretsFile} while looking for secret ${props.name}`
);
}

this.name = props.name;
}

Expand Down

0 comments on commit 0ef615f

Please sign in to comment.