Skip to content
Open
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
10 changes: 10 additions & 0 deletions plugins/sentry-cli/skills/sentry-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,16 @@ 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`
- `-n, --dry-run - Validate inputs and show what would be deleted without deleting it`
- `--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
250 changes: 250 additions & 0 deletions src/commands/project/delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
/**
* 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 (unless --yes is passed)
* 4. Call `deleteProject` API
* 5. Display result
*
* Safety measures:
* - No auto-detect mode: requires explicit target to prevent accidental deletion
* - Confirmation prompt with strict `confirmed !== true` 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 { ApiError, CliError, ContextError } from "../../lib/errors.js";
import {
formatProjectDeleted,
type ProjectDeleteResult,
} from "../../lib/formatters/human.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.
*
* Throws in non-interactive mode without --yes. Returns true if confirmed,
* false if the user cancels.
*
* @param orgSlug - Organization slug for display
* @param project - Project with slug and name for display
* @returns true if confirmed, false if cancelled
*/
async function confirmDeletion(
orgSlug: string,
project: { slug: string; name: string }
): Promise<boolean> {
if (!isatty(0)) {
throw new CliError(
`Refusing to delete '${orgSlug}/${project.slug}' in non-interactive mode. Use --yes to confirm.`
);
}

const confirmed = await log.prompt(
`Delete project '${project.name}' (${orgSlug}/${project.slug})? This cannot be undone.`,
{ type: "confirm", initial: false }
);

// consola prompt returns Symbol(clack:cancel) on Ctrl+C — a truthy value.
// Strictly check for `true` to avoid deleting on cancel.
return confirmed === true;
}

/**
* 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 re-authenticating (likely token scope)
* - unknown/fetch failure → generic message covering both cases
*/
async function buildPermissionError(
orgSlug: string,
projectSlug: string
): Promise<ApiError> {
const label = `'${orgSlug}/${projectSlug}'`;
const rolesWithAccess = "Manager, Owner, or Team Admin";

let orgRole: string | undefined;
try {
const org = await getOrganization(orgSlug);
orgRole = (org as Record<string, unknown>).orgRole as string | undefined;
} catch {
// Best-effort — fall through to generic message
}

if (orgRole && ["member", "billing"].includes(orgRole)) {
return new ApiError(
`Permission denied: You don't have permission to delete ${label}.\n\n` +
`Your organization role is '${orgRole}'. ` +
`Project deletion requires ${rolesWithAccess} role.\n` +
" Ask 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: You don't have permission to delete ${label}.\n\n` +
`Your org role ('${orgRole}') should allow this. ` +
"Your auth token may be missing the 'project:admin' scope.\n" +
" Re-authenticate: sentry auth login",
403
);
}

return new ApiError(
`Permission denied: You don't have permission to delete ${label}.\n\n` +
`This requires ${rolesWithAccess} role, or a token with the 'project:admin' scope.\n` +
` Check your role: sentry org view ${orgSlug}\n` +
" Re-authenticate: sentry auth login",
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 "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 --dry-run",
},
output: {
json: true,
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,
},
"dry-run": {
kind: "boolean",
brief:
"Validate inputs and show what would be deleted without deleting it",
default: false,
},
},
aliases: { y: "yes", n: "dry-run" },
},
async func(this: SentryContext, flags: DeleteFlags, target: string) {
const { stdout, 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"]) {
return { data: buildResult(orgSlug, project, true) };
}

// Confirmation gate
if (!flags.yes) {
const confirmed = await confirmDeletion(orgSlug, project);
if (!confirmed) {
stdout.write("Cancelled.\n");
return;
}
}

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

return { data: 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 @@ -59,6 +59,7 @@ export {
} from "./api/organizations.js";
export {
createProject,
deleteProject,
findProjectByDsnKey,
findProjectsByPattern,
findProjectsBySlug,
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
38 changes: 38 additions & 0 deletions src/lib/formatters/human.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1928,6 +1928,44 @@ export function formatProjectCreated(result: ProjectCreatedResult): string {
return renderMarkdown(lines.join("\n"));
}

// Project Deletion Formatting

/** Result of a project deletion (or dry-run). */
export type ProjectDeleteResult = {
/** Organization slug */
orgSlug: string;
/** Project slug */
projectSlug: string;
/** Human-readable project name */
projectName: string;
/** Sentry web URL for the project */
url: string;
/** When true, nothing was actually deleted — output uses tentative wording */
dryRun?: boolean;
};

/**
* Format a project deletion result as rendered markdown.
*
* @param result - Deletion context
* @returns Rendered terminal string
*/
export function formatProjectDeleted(result: ProjectDeleteResult): string {
const nameEsc = escapeMarkdownInline(result.projectName);
const qualifiedSlug = `${result.orgSlug}/${result.projectSlug}`;

if (result.dryRun) {
return renderMarkdown(
`Would delete project '${nameEsc}' (${safeCodeSpan(qualifiedSlug)}).\n\n` +
`URL: ${result.url}`
);
}

return renderMarkdown(
`Deleted project '${nameEsc}' (${safeCodeSpan(qualifiedSlug)}).`
);
}

// CLI Fix Formatting

/** Structured fix result (imported from the command module) */
Expand Down
1 change: 1 addition & 0 deletions src/lib/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ function getClientId(): string {
const SCOPES = [
"project:read",
"project:write",
"project:admin",
Copy link
Member

Choose a reason for hiding this comment

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

what would happen if someone doesn't have this permission? would it face trouble signing in?

"org:read",
"event:read",
"event:write",
Expand Down
Loading
Loading