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
70 changes: 20 additions & 50 deletions AGENTS.md

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions plugins/sentry-cli/skills/sentry-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,17 @@ Create a new project
- `--json - Output as JSON`
- `--fields <value> - Comma-separated fields to include in JSON output (dot.notation supported)`

#### `sentry project delete <org/project>`

Delete a project

**Flags:**
- `-y, --yes - Skip confirmation prompt`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also accept -f/--force flag

- `-f, --force - Force deletion without confirmation`
- `-n, --dry-run - Validate and show what would be deleted without deleting`
- `--json - Output as JSON`
- `--fields <value> - Comma-separated fields to include in JSON output (dot.notation supported)`

#### `sentry project list <org/project>`

List projects
Expand Down
276 changes: 276 additions & 0 deletions src/commands/project/delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
/**
* sentry project delete
*
* Permanently delete a Sentry project.
*
* ## Flow
*
* 1. Parse target arg → extract org/project (e.g., "acme/my-app" or "my-app")
* 2. Verify the project exists via `getProject` (also displays its name)
* 3. Prompt for confirmation by typing `org/project` (unless --yes is passed)
* 4. Call `deleteProject` API
* 5. Display result
*
* Safety measures:
* - No auto-detect mode: requires explicit target to prevent accidental deletion
* - Type-out confirmation: user must type the full `org/project` slug
* - Strict cancellation check (Symbol(clack:cancel) gotcha)
* - Refuses to run in non-interactive mode without --yes flag
*/

import { isatty } from "node:tty";
import type { SentryContext } from "../../context.js";
import {
deleteProject,
getOrganization,
getProject,
} from "../../lib/api-client.js";
import { parseOrgProjectArg } from "../../lib/arg-parsing.js";
import { buildCommand } from "../../lib/command.js";
import { getCachedOrgRole } from "../../lib/db/regions.js";
import { ApiError, CliError, ContextError } from "../../lib/errors.js";
import {
formatProjectDeleted,
type ProjectDeleteResult,
} from "../../lib/formatters/human.js";
import { CommandOutput } from "../../lib/formatters/output.js";
import { logger } from "../../lib/logger.js";
import { resolveOrgProjectTarget } from "../../lib/resolve-target.js";
import { buildProjectUrl } from "../../lib/sentry-urls.js";

const log = logger.withTag("project.delete");

/** Command name used in error messages and resolution hints */
const COMMAND_NAME = "project delete";

/**
* Prompt for confirmation before deleting a project.
*
* Uses a type-out confirmation where the user must type the full
* `org/project` slug — similar to GitHub's deletion confirmation.
*
* Throws in non-interactive mode without --yes. Returns true if
* the typed input matches, false otherwise.
*
* @param orgSlug - Organization slug for display and matching
* @param project - Project with slug and name for display and matching
* @returns true if confirmed, false if cancelled or mismatched
*/
async function confirmDeletion(
orgSlug: string,
project: { slug: string; name: string }
): Promise<boolean> {
const expected = `${orgSlug}/${project.slug}`;

if (!isatty(0)) {
throw new CliError(
`Refusing to delete '${expected}' in non-interactive mode. ` +
"Use --yes or --force to confirm."
);
}

const response = await log.prompt(
`Type '${expected}' to permanently delete project '${project.name}':`,
{ type: "text", placeholder: expected }
);

// consola prompt returns Symbol(clack:cancel) on Ctrl+C — a truthy value.
// Check type to avoid treating cancel as a valid response.
if (typeof response !== "string") {
return false;
}

return response.trim() === expected;
}

/**
* Build an actionable 403 error by checking the user's org role.
*
* - member/billing → tell them they need a higher role
* - manager/owner/admin → suggest checking token scope
* - unknown/fetch failure → generic message covering both cases
*
* Never suggests `sentry auth login` — re-authenticating via OAuth won't
* change permissions. The issue is either an insufficient org role or
* a custom auth token missing the `project:admin` scope.
*/
async function buildPermissionError(
orgSlug: string,
projectSlug: string
): Promise<ApiError> {
const label = `'${orgSlug}/${projectSlug}'`;
const rolesWithAccess = "Manager, Owner, or Admin";

// Try the org cache first (populated by listOrganizations), then fall back
// to a fresh API call. The cache avoids an extra HTTP round-trip when the
// org listing has already been fetched during this session.
let orgRole = await getCachedOrgRole(orgSlug);
if (!orgRole) {
try {
const org = await getOrganization(orgSlug);
orgRole = (org as Record<string, unknown>).orgRole as string | undefined;
} catch {
// Fall through to generic message
}
}

if (orgRole && ["member", "billing"].includes(orgRole)) {
return new ApiError(
`Permission denied: cannot delete ${label}.\n\n` +
`Your organization role is '${orgRole}'. ` +
`Project deletion requires a ${rolesWithAccess} role.\n` +
" Contact an org admin to change your role or delete the project for you.",
403
);
}

if (orgRole && ["manager", "owner", "admin"].includes(orgRole)) {
return new ApiError(
`Permission denied: cannot delete ${label}.\n\n` +
`Your org role ('${orgRole}') should have permission. ` +
"If using a custom auth token, ensure it includes the 'project:admin' scope.",
403
);
}

return new ApiError(
`Permission denied: cannot delete ${label}.\n\n` +
`This requires a ${rolesWithAccess} role, or a token with the 'project:admin' scope.\n` +
` Check your role: sentry org view ${orgSlug}`,
403
);
}

/** Build a result object for both dry-run and actual deletion */
function buildResult(
orgSlug: string,
project: { slug: string; name: string },
dryRun?: boolean
): ProjectDeleteResult {
return {
orgSlug,
projectSlug: project.slug,
projectName: project.name,
url: buildProjectUrl(orgSlug, project.slug),
dryRun,
};
}

type DeleteFlags = {
readonly yes: boolean;
readonly force: boolean;
readonly "dry-run": boolean;
readonly json: boolean;
readonly fields?: string[];
};

export const deleteCommand = buildCommand({
docs: {
brief: "Delete a project",
fullDescription:
"Permanently delete a Sentry project. This action cannot be undone.\n\n" +
"Requires explicit target — auto-detection is disabled for safety.\n\n" +
"Examples:\n" +
" sentry project delete acme-corp/my-app\n" +
" sentry project delete my-app\n" +
" sentry project delete acme-corp/my-app --yes\n" +
" sentry project delete acme-corp/my-app --force\n" +
" sentry project delete acme-corp/my-app --dry-run",
},
output: {
human: formatProjectDeleted,
jsonTransform: (result: ProjectDeleteResult) => {
if (result.dryRun) {
return {
dryRun: true,
org: result.orgSlug,
project: result.projectSlug,
name: result.projectName,
url: result.url,
};
}
return {
deleted: true,
org: result.orgSlug,
project: result.projectSlug,
};
},
},
parameters: {
positional: {
kind: "tuple",
parameters: [
{
placeholder: "org/project",
brief: "<org>/<project> or <project> (search across orgs)",
parse: String,
},
],
},
flags: {
yes: {
kind: "boolean",
brief: "Skip confirmation prompt",
default: false,
},
force: {
kind: "boolean",
brief: "Force deletion without confirmation",
default: false,
},
"dry-run": {
kind: "boolean",
brief: "Validate and show what would be deleted without deleting",
default: false,
},
},
aliases: { y: "yes", f: "force", n: "dry-run" },
},
async *func(this: SentryContext, flags: DeleteFlags, target: string) {
const { cwd } = this;

// Block auto-detect for safety — destructive commands require explicit targets
const parsed = parseOrgProjectArg(target);
if (parsed.type === "auto-detect") {
throw new ContextError(
"Project target",
`sentry ${COMMAND_NAME} <org>/<project>`,
[
"Auto-detection is disabled for delete — specify the target explicitly",
]
);
}

const { org: orgSlug, project: projectSlug } =
await resolveOrgProjectTarget(parsed, cwd, COMMAND_NAME);

// Verify project exists before prompting — also used to display the project name
const project = await getProject(orgSlug, projectSlug);

// Dry-run mode: show what would be deleted without deleting it
if (flags["dry-run"]) {
yield new CommandOutput(buildResult(orgSlug, project, true));
return;
}

// Confirmation gate
if (!(flags.yes || flags.force)) {
const confirmed = await confirmDeletion(orgSlug, project);
if (!confirmed) {
log.info("Cancelled.");
return;
}
}

try {
await deleteProject(orgSlug, project.slug);
} catch (error) {
if (error instanceof ApiError && error.status === 403) {
throw await buildPermissionError(orgSlug, project.slug);
}
throw error;
}

yield new CommandOutput(buildResult(orgSlug, project));
},
});
2 changes: 2 additions & 0 deletions src/commands/project/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { buildRouteMap } from "@stricli/core";
import { createCommand } from "./create.js";
import { deleteCommand } from "./delete.js";
import { listCommand } from "./list.js";
import { viewCommand } from "./view.js";

export const projectRoute = buildRouteMap({
routes: {
create: createCommand,
delete: deleteCommand,
list: listCommand,
view: viewCommand,
},
Expand Down
1 change: 1 addition & 0 deletions src/lib/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export {
} from "./api/organizations.js";
export {
createProject,
deleteProject,
findProjectByDsnKey,
findProjectsByPattern,
findProjectsBySlug,
Expand Down
3 changes: 3 additions & 0 deletions src/lib/api/organizations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export async function listOrganizations(): Promise<SentryOrganization[]> {
id: org.id,
slug: org.slug,
name: org.name,
...(org.orgRole ? { orgRole: org.orgRole } : {}),
}));
}

Expand Down Expand Up @@ -119,6 +120,7 @@ export async function listOrganizationsUncached(): Promise<
regionUrl: baseUrl,
orgId: org.id,
orgName: org.name,
orgRole: (org as Record<string, unknown>).orgRole as string | undefined,
}))
);
return orgs;
Expand Down Expand Up @@ -146,6 +148,7 @@ export async function listOrganizationsUncached(): Promise<
regionUrl: r.regionUrl,
orgId: r.org.id,
orgName: r.org.name,
orgRole: (r.org as Record<string, unknown>).orgRole as string | undefined,
}));
await setOrgRegions(regionEntries);

Expand Down
25 changes: 25 additions & 0 deletions src/lib/api/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import {
createANewProject,
deleteAProject,
listAnOrganization_sProjects,
listAProject_sClientKeys,
retrieveAProject,
Expand Down Expand Up @@ -152,6 +153,30 @@ export async function createProject(
return data as unknown as SentryProject;
}

/**
* Delete a project from an organization.
*
* Sends a DELETE request to the Sentry API. Returns 204 No Content on success.
*
* @param orgSlug - The organization slug
* @param projectSlug - The project slug to delete
* @throws {ApiError} 403 if the user lacks permission, 404 if the project doesn't exist
*/
export async function deleteProject(
orgSlug: string,
projectSlug: string
): Promise<void> {
const config = await getOrgSdkConfig(orgSlug);
const result = await deleteAProject({
...config,
path: {
organization_id_or_slug: orgSlug,
project_id_or_slug: projectSlug,
},
});
unwrapResult(result, "Failed to delete project");
}

/** Result of searching for projects by slug across all organizations. */
export type ProjectSearchResult = {
/** Matching projects with their org context */
Expand Down
Loading
Loading