Skip to content

Commit

Permalink
revert(cli): introduce default entrypoints (#4408)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkMcCulloh authored Oct 4, 2023
1 parent acf4bbe commit d9e096e
Show file tree
Hide file tree
Showing 9 changed files with 188 additions and 305 deletions.
3 changes: 1 addition & 2 deletions apps/wing/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
},
"scripts": {
"build": "tsc && pnpm copy-root-readme",
"eslint": "eslint --fix --ext .ts src",
"eslint": "eslint --ext .ts src",
"compile": "tsc",
"copy-root-readme": "cp ../../README.md ./README.md && pnpm copy-root-assets",
"copy-root-assets": "cp ../../logo/demo.gif ./logo/demo.gif",
Expand All @@ -41,7 +41,6 @@
"commander": "^10.0.1",
"compare-versions": "^5.0.3",
"debug": "^4.3.4",
"glob": "^10.3.10",
"nanoid": "^3.3.6",
"open": "^8.4.2",
"ora": "^5.4.1",
Expand Down
5 changes: 3 additions & 2 deletions apps/wing/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { collectCommandAnalytics } from "./analytics/collect";
import { optionallyDisplayDisclaimer } from "./analytics/disclaimer";
import { exportAnalytics } from "./analytics/export";
import { currentPackage } from "./util";

export const PACKAGE_VERSION = currentPackage.version;
let analyticsExportFile: Promise<string | undefined>;

Expand Down Expand Up @@ -132,7 +133,7 @@ async function main() {
program
.command("compile")
.description("Compiles a Wing program")
.argument("[entrypoint]", "program .w entrypoint")
.argument("<entrypoint>", "program .w entrypoint")
.addOption(
new Option("-t, --target <target>", "Target platform")
.choices(["tf-aws", "tf-azure", "tf-gcp", "sim", "awscdk"])
Expand All @@ -149,7 +150,7 @@ async function main() {
.description(
"Compiles a Wing program and runs all functions with the word 'test' or start with 'test:' in their resource identifiers"
)
.argument("[entrypoint...]", "all files to test (globs are supported)", ["*.test.w"])
.argument("<entrypoint...>", "all entrypoints to test")
.addOption(
new Option("-t, --target <target>", "Target platform")
.choices(["tf-aws", "tf-azure", "tf-gcp", "sim", "awscdk"])
Expand Down
35 changes: 1 addition & 34 deletions apps/wing/src/commands/compile.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { writeFileSync } from "fs";
import { readdir, stat, writeFile, mkdtemp } from "fs/promises";
import { tmpdir } from "os";
import { readdir, stat, writeFile } from "fs/promises";
import { join, resolve } from "path";
import { Target } from "@winglang/compiler";
import { describe, test, expect } from "vitest";
Expand Down Expand Up @@ -42,37 +40,6 @@ describe(
expect(files).toEqual([".wing", "connections.json", "simulator.json", "tree.json"]);
});

test("should be able to compile to default target sim", async () => {
const outDir = await compile(exampleFilePath, {
targetDir: `${await generateTmpDir()}/target`,
});

const stats = await stat(outDir);
expect(stats.isDirectory()).toBeTruthy();
const files = (await readdir(outDir)).sort();
expect(files.length).toBeGreaterThan(0);
expect(files).toEqual([".wing", "connections.json", "simulator.json", "tree.json"]);
});

test("should be able to compile the only entrypoint file in current directory", async () => {
const outDir = await mkdtemp(join(tmpdir(), "-wing-compile-test"));
const prevdir = process.cwd();

try {
process.chdir(outDir);
writeFileSync("main.w", "bring cloud;");
await compile();

const stats = await stat(outDir);
expect(stats.isDirectory()).toBeTruthy();
const files = (await readdir(outDir)).sort();
expect(files.length).toBeGreaterThan(0);
expect(files).toEqual(["main.w", "target"]);
} finally {
process.chdir(prevdir);
}
});

test("should error if a nonexistent file is compiled", async () => {
return expect(compile("non-existent-file.w", { target: Target.SIM })).rejects.toThrowError(
/Source file cannot be found/
Expand Down
27 changes: 7 additions & 20 deletions apps/wing/src/commands/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import * as wingCompiler from "@winglang/compiler";
import chalk from "chalk";
import { CHARS_ASCII, emitDiagnostic, File, Label } from "codespan-wasm";
import debug from "debug";
import { glob } from "glob";

// increase the stack trace limit to 50, useful for debugging Rust panics
// (not setting the limit too high in case of infinite recursion)
Expand All @@ -18,23 +17,19 @@ const log = debug("wing:compile");
* This is passed from Commander to the `compile` function.
*/
export interface CompileOptions {
readonly rootId?: string;
readonly target: wingCompiler.Target;
readonly plugins?: string[];
readonly rootId?: string;
/**
* The target to compile to
* @default wingCompiler.Target.SIM
* Whether to run the compiler in `wing test` mode. This may create multiple
* copies of the application resources in order to run tests in parallel.
*/
readonly target?: wingCompiler.Target;
readonly testing?: boolean;
/**
* The location to save the compilation output
* @default "./target"
*/
readonly targetDir?: string;
/**
* Whether to run the compiler in `wing test` mode. This may create multiple
* copies of the application resources in order to run tests in parallel.
*/
readonly testing?: boolean;
}

/**
Expand All @@ -43,22 +38,14 @@ export interface CompileOptions {
* @param options Compile options.
* @returns the output directory
*/
export async function compile(entrypoint?: string, options?: CompileOptions): Promise<string> {
if (!entrypoint) {
const wingFiles = await glob("{main,*.main}.w");
if (wingFiles.length !== 1) {
throw new Error("Please specify which file you want to compile");
}
entrypoint = wingFiles[0];
}

export async function compile(entrypoint: string, options: CompileOptions): Promise<string> {
const coloring = chalk.supportsColor ? chalk.supportsColor.hasBasic : false;
try {
return await wingCompiler.compile(entrypoint, {
...options,
log,
color: coloring,
target: options?.target || wingCompiler.Target.SIM,
targetDir: options.targetDir,
});
} catch (error) {
if (error instanceof wingCompiler.CompileError) {
Expand Down
74 changes: 23 additions & 51 deletions apps/wing/src/commands/run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,38 +19,17 @@ vi.mock("@wingconsole/app", () => {
};
});

test("wing it runs the only entrypoint file named main.w", async () => {
test("wing it runs the only .w file", async () => {
const workdir = await mkdtemp(join(tmpdir(), "-wing-it-test"));
const prevdir = process.cwd();
try {
process.chdir(workdir);

writeFileSync("main.w", "bring cloud;");

await run();
expect(createConsoleApp).toBeCalledWith({
wingfile: resolve("main.w"),
requestedPort: 3000,
hostUtils: expect.anything(),
requireAcceptTerms: false,
});
expect(open).toBeCalledWith("http://localhost:3000/");
} finally {
process.chdir(prevdir);
}
});

test("wing it runs the only entrypoint file ending with .main.w", async () => {
const workdir = await mkdtemp(join(tmpdir(), "-wing-it-test"));
const prevdir = process.cwd();
try {
process.chdir(workdir);

writeFileSync("foo.main.w", "bring cloud;");
writeFileSync("foo.w", "bring cloud;");

await run();
expect(createConsoleApp).toBeCalledWith({
wingfile: resolve("foo.main.w"),
wingfile: resolve("foo.w"),
requestedPort: 3000,
hostUtils: expect.anything(),
requireAcceptTerms: false,
Expand All @@ -61,44 +40,37 @@ test("wing it runs the only entrypoint file ending with .main.w", async () => {
}
});

test("wing it doesn't run the only entrypoint file ending with .test.w", async () => {
const workdir = await mkdtemp(join(tmpdir(), "-wing-it-test"));
const prevdir = process.cwd();
try {
process.chdir(workdir);

writeFileSync("foo.test.w", "bring cloud;");

await expect(run).rejects.toThrow("Please specify which file you want to run");
} finally {
process.chdir(prevdir);
}
});

test("wing it throws error for a directory with a non-entrypoint file", async () => {
test("wing it with no file throws error for a directory with more than 1 .w file", async () => {
const workdir = await mkdtemp(join(tmpdir(), "-wing-it-test"));
const prevdir = process.cwd();
try {
process.chdir(workdir);

writeFileSync("foo.w", "bring cloud;");
writeFileSync("bar.w", "bring cloud;");

await expect(run).rejects.toThrow("Please specify which file you want to run");
} finally {
process.chdir(prevdir);
}
});

test("wing it throws error for a directory with more than one entrypoint file", async () => {
test("wing it with a file runs", async () => {
const workdir = await mkdtemp(join(tmpdir(), "-wing-it-test"));
const prevdir = process.cwd();
try {
process.chdir(workdir);

writeFileSync("main.w", "bring cloud;");
writeFileSync("foo.main.w", "bring cloud;");
writeFileSync("foo.w", "bring cloud;");

await expect(run).rejects.toThrow("Please specify which file you want to run");
await run("foo.w");
expect(createConsoleApp).toBeCalledWith({
wingfile: resolve("foo.w"),
requestedPort: 3000,
hostUtils: expect.anything(),
requireAcceptTerms: false,
});
expect(open).toBeCalledWith("http://localhost:3000/");
} finally {
process.chdir(prevdir);
}
Expand All @@ -107,7 +79,7 @@ test("wing it throws error for a directory with more than one entrypoint file",
test("wing it with a nested file runs", async () => {
const workdir = await mkdtemp(join(tmpdir(), "-wing-it-test"));
const subdir = join(workdir, "subdir");
const filePath = join(subdir, "foo.main.w");
const filePath = join(subdir, "foo.w");
const prevdir = process.cwd();
try {
process.chdir(workdir);
Expand All @@ -134,9 +106,9 @@ test("wing it with an invalid file throws exception", async () => {
try {
process.chdir(workdir);

writeFileSync("foo.main.w", "bring cloud;");
writeFileSync("foo.w", "bring cloud;");

await expect(run("bar.main.w")).rejects.toThrow("bar.main.w doesn't exist");
await expect(run("bar.w")).rejects.toThrow("bar.w doesn't exist");
} finally {
process.chdir(prevdir);
}
Expand All @@ -148,11 +120,11 @@ test("wing it with a custom port runs", async () => {
try {
process.chdir(workdir);

writeFileSync("foo.main.w", "bring cloud;");
writeFileSync("foo.w", "bring cloud;");

await run("foo.main.w", { port: "5000" });
await run("foo.w", { port: "5000" });
expect(createConsoleApp).toBeCalledWith({
wingfile: resolve("foo.main.w"),
wingfile: resolve("foo.w"),
requestedPort: 5000,
hostUtils: expect.anything(),
requireAcceptTerms: false,
Expand All @@ -169,10 +141,10 @@ test("wing it throws when invalid port number is used", async () => {
try {
process.chdir(workdir);

writeFileSync("foo.main.w", "bring cloud;");
writeFileSync("foo.w", "bring cloud;");

await expect(async () => {
await run("foo.main.w", { port: "not a number" });
await run("foo.w", { port: "not a number" });
}).rejects.toThrowError('"not a number" is not a number');
} finally {
process.chdir(prevdir);
Expand Down
5 changes: 2 additions & 3 deletions apps/wing/src/commands/run.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { existsSync } from "fs";
import { readdirSync, existsSync } from "fs";
import { resolve } from "path";
import { createConsoleApp } from "@wingconsole/app";
import { debug } from "debug";
import { glob } from "glob";
import open from "open";
import { parseNumericString } from "../util";

Expand Down Expand Up @@ -36,7 +35,7 @@ export async function run(entrypoint?: string, options?: RunOptions) {
const openBrowser = options?.open ?? true;

if (!entrypoint) {
const wingFiles = await glob("{main,*.main}.w");
const wingFiles = readdirSync(".").filter((item) => item.endsWith(".w"));
if (wingFiles.length !== 1) {
throw new Error("Please specify which file you want to run");
}
Expand Down
9 changes: 1 addition & 8 deletions apps/wing/src/commands/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { Target } from "@winglang/compiler";
import { std, simulator } from "@winglang/sdk";
import chalk from "chalk";
import debug from "debug";
import { glob } from "glob";
import { nanoid } from "nanoid";
import { compile, CompileOptions } from "./compile";
import { generateTmpDir, withSpinner } from "../util";
Expand All @@ -30,12 +29,6 @@ export interface TestOptions extends CompileOptions {
}

export async function test(entrypoints: string[], options: TestOptions): Promise<number> {
const expandedEntrypoints = await glob(entrypoints);

if (expandedEntrypoints.length === 0) {
throw new Error(`No matching files found in current directory. (${entrypoints.join(", ")})`);
}

const startTime = Date.now();
const results: { testName: string; results: std.TestResult[] }[] = [];
const testFile = async (entrypoint: string) => {
Expand All @@ -51,7 +44,7 @@ export async function test(entrypoints: string[], options: TestOptions): Promise
});
}
};
await Promise.all(expandedEntrypoints.map(testFile));
await Promise.all(entrypoints.map(testFile));
printResults(results, Date.now() - startTime);

// if we have any failures, exit with 1
Expand Down
Loading

0 comments on commit d9e096e

Please sign in to comment.