Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/product/command-principles.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ A command that operates on a subject resource takes that resource's identifier a

A Project, service, database or bucket that Prisma Composer deployed can also be named by its address: the name the app gave it, such as `shop.api`. The address is the row's `logicalId`, and its first `.`-separated part is the app, which is the Project's `logicalId`. On the command line the subject is `@`, then an optional environment and `:`, then the address: `@pr-42:shop.api`. The environment is the one the app was deployed to: the git name of one of the Project's Branches. Leaving it out, or writing `production`, means the Project's default Branch (the Branch with `isDefault` set), so `@shop.api` is production. This is the default Branch, not the Branch whose role is `production`, and not a Branch whose git name is `production`; a non-default Branch with that git name cannot be named by address. A Project's address is the app name alone, with no environment (`@shop`), because a Project spans every Branch. With an address, a destructive command's `--confirm` takes the address as typed (`postgres delete @pr-42:shop.db --confirm @pr-42:shop.db`), and its question names the row id, the environment and the Branch, saying plainly when that is production. `--project` and `--branch` cannot be combined with an address, because the address already names both.

A `service` command without `--branch` uses the Project's default Branch, the Branch with `isDefault` set, never a Branch guessed from its git name. A Project with no Branches yet gets the git name `main`, which `service create` creates as its first Branch. A Project that has Branches but none marked default stops with `SERVICE.DEFAULT_BRANCH_MISSING`, asking for `--branch`. A `service` command that deletes or changes what serves traffic (`service delete`, `service version rollback`, `service domain delete`) names the Branch in its confirmation question, and when that Branch is the default Branch it says production, as the address form does: `Delete Service "api" (svc_1) in production (branch main) and every version it owns?`. With `--branch`, the CLI looks the name up in the Project's Branches and takes the Branch's role and default mark from the listing, so `--branch main` says production when `main` is the default Branch; a name the Project does not list yet is used as typed, which lets `service create --branch <name>` create it.
A `service` command without `--branch` uses the Project's default Branch, the Branch with `isDefault` set, never a Branch guessed from its git name. A Project with no Branches yet gets the git name `main`, which `service create` creates as its first Branch. A Project that has Branches but none marked default stops with `SERVICE.DEFAULT_BRANCH_MISSING`, asking for `--branch`. A `service` command that deletes or changes what serves traffic (`service delete`, `service version rollback`, `service domain delete`) names the Branch in its confirmation question, and when that Branch is the default Branch it says production, as the address form does: `Delete Service "api" (svc_1) in production (branch main) and every version it owns?`. With `--branch`, the CLI looks the name up in the Project's Branches and takes the Branch's role and default mark from the listing, so `--branch main` says production when `main` is the default Branch; a name the Project does not list stops the command with `SERVICE.BRANCH_NOT_FOUND`, except in `service create`, which uses the name as typed and creates the Branch.

### `wait`

Expand Down
4 changes: 4 additions & 0 deletions docs/reference/error-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,10 @@ A `project` or `branch` group command was invoked with unusable arguments — fo

A `--branch` flag was passed with an empty or whitespace-only value to a service command; the check runs before any resolution because a blank value must never fall through to the default-branch behavior of omitting the flag. The fix is to pass a non-empty branch name, or omit `--branch` to target the default branch. Meta: none.

### SERVICE.BRANCH_NOT_FOUND

A `service` command was run with `--branch` naming a branch the project does not have, for example a mistyped name. The command stops before it lists or changes any service, so a mistyped branch is not reported as a missing service. `service create` never raises it, because it creates a branch it does not find. The fix is to pass a branch the project has, or omit `--branch` to use the default branch; the next actions offer `branch list` for the project. Meta: `projectId`, `branchName`.

### SERVICE.DEFAULT_BRANCH_MISSING

A `service` command was run without `--branch` on a project that has branches but none marked as its default, so there is no branch it can safely act on. It never guesses a branch by name. The fix is to pass `--branch` with the branch to use; the next actions also offer `branch list` for the project. Meta: `projectId`.
Expand Down
13 changes: 13 additions & 0 deletions packages/cli/e2e/service.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,19 @@ describeCommand("service list", () => {
// Still undeployed, so still no live URL in the listing either.
expect(found?.liveUrl).toBeNull();
});

it("with --branch naming a branch the project lacks, says the branch is missing", async () => {
const missing = scratchName("no-such-branch");
const run = await scratch.run(["service", "list", "--branch", missing], {
expectOk: false,
});

expect(run.envelope.error?.code).toBe("SERVICE.BRANCH_NOT_FOUND");
expect(run.envelope.error?.meta).toMatchObject({
projectId: scratch.project().id,
branchName: missing,
});
});
});

describeCommand("service show", () => {
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/commands/service/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export const serviceCreateCommand = defineCommand({

const target = await resolveServiceProjectContext(ctx, args.flags.project, {
commandName: "service create",
acceptsUnlistedBranch: true,
...(args.flags.branch !== undefined
? { branchName: args.flags.branch }
: {}),
Expand Down
23 changes: 23 additions & 0 deletions packages/cli/src/commands/service/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,29 @@ export function branchValueEmptyError(): CliStructuredError {
);
}

export function branchNotFoundError(
project: { id: string; name: string },
branchName: string,
): CliStructuredError {
return new CliStructuredError(
"SERVICE.BRANCH_NOT_FOUND",
`Project "${project.name}" has no branch named "${branchName}"`,
{
why: `Project "${project.name}" (${project.id}) has no branch named "${branchName}". The name may be mistyped, or the branch may have been deleted.`,
meta: { projectId: project.id, branchName },
nextActions: [
adviceAction(
"Pass --branch with the name of a branch the project has, or omit it to use the default branch.",
),
runCommandAction(
"List the project's branches",
`branch list --project ${project.id}`,
),
],
},
);
}

export function defaultBranchMissingError(project: {
id: string;
name: string;
Expand Down
37 changes: 30 additions & 7 deletions packages/cli/src/commands/service/target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type { AuthWorkspace } from "../../types/auth";
import type { BranchKind } from "../../types/branch";
import type { ProjectResolution, ProjectSummary } from "../../types/project";
import {
branchNotFoundError,
branchValueEmptyError,
type DomainCommand,
defaultBranchMissingError,
Expand Down Expand Up @@ -191,21 +192,28 @@ function namedBranch(name: string): ResolvedServiceBranch {
return { id: null, name, kind: toBranchKind(name), isDefault: false };
}

/** A Branch named with `--branch`, as the Project lists it. A name the
* Project does not have yet is kept as given, so `service create` can
* create it. */
/** A Branch named with `--branch`, as the Project lists it. Only
* `service create` may name a Branch the Project does not have yet,
* because creating the service creates the Branch. */
async function namedBranchOf(
ctx: ServiceContext,
project: ProjectSummary,
name: string,
acceptsUnlistedBranch: boolean,
): Promise<ResolvedServiceBranch> {
const branches = await listProjectBranches(ctx.api, {
projectId: project.id,
gitName: name,
signal: ctx.signal,
});
const listed = branches.find((branch) => branch.gitName === name);
return listed ? listedBranch(listed) : namedBranch(name);
if (listed) {
return listedBranch(listed);
}
if (acceptsUnlistedBranch) {
return namedBranch(name);
}
throw branchNotFoundError(project, name);
}

async function defaultBranchOf(
Expand All @@ -229,8 +237,18 @@ async function defaultBranchOf(
/** The Branch a command was pointed at: a `--branch` name to look up, or
* one an address already resolved. Neither means the default Branch. */
type BranchTarget =
| { readonly branchName?: string; readonly branch?: undefined }
| { readonly branch: ResolvedServiceBranch; readonly branchName?: undefined };
| {
readonly branchName?: string;
readonly branch?: undefined;
/** Use a `--branch` the Project does not list as typed, for
* `service create`, which creates it. */
readonly acceptsUnlistedBranch?: boolean;
}
| {
readonly branch: ResolvedServiceBranch;
readonly branchName?: undefined;
readonly acceptsUnlistedBranch?: undefined;
};

export async function resolveServiceProjectContext(
ctx: ServiceContext,
Expand Down Expand Up @@ -258,7 +276,12 @@ export async function resolveServiceProjectContext(
const branch =
options.branch ??
(options.branchName !== undefined
? await namedBranchOf(ctx, resolved.project, options.branchName)
? await namedBranchOf(
ctx,
resolved.project,
options.branchName,
options.acceptsUnlistedBranch === true,
)
: await defaultBranchOf(ctx, resolved.project));

return {
Expand Down
46 changes: 46 additions & 0 deletions packages/cli/tests/service-delete.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,52 @@ describe("prisma service delete", () => {
expect(deletes).toEqual([]);
});

it("with a mistyped --branch, says the branch is missing and deletes nothing", async () => {
const listings: unknown[] = [];
const deletes: unknown[] = [];
const harness = await makeServiceCli({
routes: releaseRoutes({
"GET /v1/apps": (init) => {
listings.push(init.params?.query?.branchGitName);
return { data: page([]) };
},
"DELETE /v1/apps/{appId}": (init) => {
deletes.push(init.params?.path?.appId);
return { data: { data: {} } };
},
}),
});

const result = await harness.cli.run(
[
"service",
"delete",
"--project",
"acme-app",
"hello-world",
"--branch",
"prodution",
"--confirm",
"hello-world",
"--json",
],
{ cwd: harness.cwd, env: harness.env },
);

expect(result.exitCode).toBe(2);
const frame = result.json.at(-1);
if (frame?.kind !== "result" || frame.envelope.ok) {
throw new Error("expected an errored envelope");
}
expect(frame.envelope.error).toMatchObject({
code: "SERVICE.BRANCH_NOT_FOUND",
summary: 'Project "acme-app" has no branch named "prodution"',
meta: { projectId: "proj_1", branchName: "prodution" },
});
expect(listings).toEqual([]);
expect(deletes).toEqual([]);
});

it("with --branch naming a preview branch, does not call it production", async () => {
const harness = await makeServiceCli({
routes: releaseRoutes(trunkDefaultBranchRoutes([])),
Expand Down
59 changes: 59 additions & 0 deletions packages/cli/tests/service-domain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,23 @@ const PUBLISH_BOTH_RECORDS = `Publish TXT _prisma-verification.shop.acme.com ->

const PUBLISH_CNAME = `Publish CNAME shop.acme.com -> switchboard.cdg.prisma.build at your DNS provider, then run prisma service domain retry shop.acme.com --service svc_1 --project proj_1 --branch main. ${APEX_NOTE}`;

/** Every branch these tests name exists, as a preview branch, except
* `main`, the default. */
function domainRoutes(overrides: Routes = {}): Routes {
return readFlowRoutes({
"GET /v1/projects/{projectId}/branches": (init) => {
const gitName = init.params?.query?.gitName ?? "main";
return {
data: page([
{
id: `br_${gitName}`,
gitName,
isDefault: gitName === "main",
role: gitName === "main" ? "production" : "preview",
},
]),
};
},
"GET /v1/services/{serviceId}/urls": () => ({
data: { data: [domainRecord()] },
}),
Expand All @@ -68,6 +83,50 @@ function fieldRows(presented: PresentedResult<unknown> | undefined) {

const TARGET_ARGS = ["--project", "acme-app", "--service", "hello-world"];

it.each([
"add",
"show",
"retry",
"wait",
"delete",
])("with a mistyped --branch, %s says the branch is missing", async (command) => {
const listings: unknown[] = [];
const harness = await makeServiceCli({
routes: domainRoutes({
"GET /v1/projects/{projectId}/branches": () => ({ data: page([]) }),
"GET /v1/apps": (init) => {
listings.push(init.params?.query?.branchGitName);
return { data: page([]) };
},
}),
});

const result = await harness.cli.run(
[
"service",
"domain",
command,
"shop.acme.com",
...TARGET_ARGS,
"--branch",
"prodution",
"--json",
...(command === "delete" ? ["--confirm", "shop.acme.com"] : []),
],
{ cwd: harness.cwd, env: harness.env },
);

expect(result.exitCode).toBe(2);
const frame = result.json.at(-1);
if (frame?.kind !== "result" || frame.envelope.ok)
throw new Error("expected an errored envelope");
expect(frame.envelope.error).toMatchObject({
code: "SERVICE.BRANCH_NOT_FOUND",
meta: { projectId: "proj_1", branchName: "prodution" },
});
expect(listings).toEqual([]);
});

it.each([
"add",
"show",
Expand Down
41 changes: 41 additions & 0 deletions packages/cli/tests/service-list.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,47 @@ describe("prisma service list", () => {
expect(result.presented?.data).toMatchObject({ branch: "staging" });
});

it("with --branch naming a branch the project lacks, fails with SERVICE.BRANCH_NOT_FOUND", async () => {
const harness = await makeServiceCli({ routes: readFlowRoutes() });

const result = await harness.cli.run(
[
"service",
"list",
"--project",
"acme-app",
"--branch",
"prodution",
"--json",
],
{ cwd: harness.cwd, env: harness.env },
);

expect(result.exitCode).toBe(2);
const frame = result.json.at(-1);
if (frame?.kind !== "result" || frame.envelope.ok) {
throw new Error("expected an errored envelope");
}
expect(frame.envelope.error).toMatchObject({
code: "SERVICE.BRANCH_NOT_FOUND",
summary: 'Project "acme-app" has no branch named "prodution"',
why: 'Project "acme-app" (proj_1) has no branch named "prodution". The name may be mistyped, or the branch may have been deleted.',
meta: { projectId: "proj_1", branchName: "prodution" },
});
expect(frame.envelope.error.nextActions).toEqual([
{
kind: "user-choice",
label:
"Pass --branch with the name of a branch the project has, or omit it to use the default branch.",
},
{
kind: "run-command",
label: "List the project's branches",
command: "prisma branch list --project proj_1",
},
]);
});

it("emits the completed json envelope with commandId service.list", async () => {
const harness = await makeServiceCli({ routes: listRoutes() });

Expand Down
12 changes: 12 additions & 0 deletions packages/cli/tests/service-testkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,18 @@ export function readFlowRoutes(overrides: Routes = {}): Routes {
"GET /v1/projects/{projectId}/branches": () => ({
data: page([
{ id: "br_1", gitName: "main", isDefault: true, role: "production" },
{
id: "br_staging",
gitName: "staging",
isDefault: false,
role: "preview",
},
{
id: "br_feature_foo",
gitName: "feature/foo",
isDefault: false,
role: "preview",
},
]),
}),
"GET /v1/apps": () => ({ data: page([SERVICE]) }),
Expand Down
Loading