11import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage" ;
22import { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils" ;
33import * as Context from "effect/Context" ;
4+ import * as DateTime from "effect/DateTime" ;
45import * as Effect from "effect/Effect" ;
56import * as Layer from "effect/Layer" ;
7+ import * as Option from "effect/Option" ;
68import * as Result from "effect/Result" ;
79import * as Schema from "effect/Schema" ;
810import { resolvePullRequestAuthorFilter , VcsProcessExitError } from "@t3tools/contracts" ;
@@ -33,6 +35,7 @@ import * as GitLabCli from "./GitLabCli.ts";
3335import {
3436 AWARD_EMOJI_GRAPHQL_QUERY ,
3537 decodeAwardEmojiJson ,
38+ decodeBranchJson ,
3639 decodeCommitDiffRefsJson ,
3740 decodeCommitsJson ,
3841 decodeDiffRefsJson ,
@@ -53,6 +56,7 @@ import {
5356 decodeProjectUsersJson ,
5457 decodeRepositoryBlobsJson ,
5558 decodeReviewDecisionsJson ,
59+ decodeSourceBranchJson ,
5660 decodeTriggerJobChecksJson ,
5761 decodeViewerJson ,
5862 gitLabAwardName ,
@@ -62,6 +66,7 @@ import {
6266 MERGE_REQUEST_STATS_GRAPHQL_QUERY ,
6367 REPOSITORY_BLOBS_GRAPHQL_QUERY ,
6468 REVIEW_DECISIONS_GRAPHQL_QUERY ,
69+ SOURCE_BRANCH_GRAPHQL_QUERY ,
6570 type GitLabDiffRefs ,
6671 type GitLabMergeRequestDetail ,
6772 type GitLabMergeRequestListItem ,
@@ -193,6 +198,41 @@ export class GitLabDiffFileContentsUnavailableError extends Schema.TaggedError<G
193198 }
194199}
195200
201+ export class GitLabBranchDeletionRefusedError extends Schema . TaggedError < GitLabBranchDeletionRefusedError > ( ) (
202+ "GitLabBranchDeletionRefusedError" ,
203+ {
204+ command : Schema . Literal ( "glab" ) ,
205+ cwd : Schema . String ,
206+ number : Schema . Int ,
207+ reason : Schema . Literals ( [
208+ "open" ,
209+ "not-allowed" ,
210+ "source-unavailable" ,
211+ "default-branch" ,
212+ "head-changed" ,
213+ ] ) ,
214+ } ,
215+ ) {
216+ get detail ( ) : string {
217+ switch ( this . reason ) {
218+ case "open" :
219+ return `Close or merge merge request !${ this . number } before deleting its source branch.` ;
220+ case "not-allowed" :
221+ return "GitLab does not let you delete this source branch. It may be protected, or you may not be able to push to it." ;
222+ case "source-unavailable" :
223+ return `GitLab did not report a source project for merge request !${ this . number } .` ;
224+ case "default-branch" :
225+ return "The source branch is its project's default branch and cannot be deleted here." ;
226+ case "head-changed" :
227+ return "The source branch has new commits and was not deleted." ;
228+ }
229+ }
230+
231+ override get message ( ) : string {
232+ return `GitLab CLI failed in deleteSourceBranch: ${ this . detail } ` ;
233+ }
234+ }
235+
196236export class GitLabUnknownLabelError extends Schema . TaggedError < GitLabUnknownLabelError > ( ) (
197237 "GitLabUnknownLabelError" ,
198238 {
@@ -212,6 +252,7 @@ export class GitLabUnknownLabelError extends Schema.TaggedError<GitLabUnknownLab
212252
213253export type GitLabPullRequestCliError =
214254 | GitLabCli . GitLabCliError
255+ | GitLabBranchDeletionRefusedError
215256 | GitLabMergeRequestReadError
216257 | GitLabUnknownLabelError
217258 | GitLabDiffCursorError
@@ -657,6 +698,7 @@ export const make = Effect.gen(function* () {
657698 readonly path : string ;
658699 readonly method ?: string ;
659700 readonly stdin ?: string ;
701+ readonly headers ?: ReadonlyArray < string > ;
660702 readonly maxOutputBytes ?: number ;
661703 readonly timeoutMs ?: number ;
662704 } ) =>
@@ -671,6 +713,7 @@ export const make = Effect.gen(function* () {
671713 ...( input . stdin === undefined
672714 ? [ ]
673715 : [ "--input" , "-" , "--header" , "Content-Type: application/json" ] ) ,
716+ ...( input . headers ?? [ ] ) . flatMap ( ( header ) => [ "--header" , header ] ) ,
674717 ] ,
675718 ...( input . stdin === undefined ? { } : { stdin : input . stdin } ) ,
676719 ...( input . maxOutputBytes === undefined ? { } : { maxOutputBytes : input . maxOutputBytes } ) ,
@@ -1281,6 +1324,88 @@ export const make = Effect.gen(function* () {
12811324 ) ,
12821325 ) ;
12831326
1327+ const sourceBranch = ( input : {
1328+ readonly cwd : string ;
1329+ readonly host ?: string | undefined ;
1330+ readonly repository : string ;
1331+ readonly number : number ;
1332+ } ) =>
1333+ graphqlRead ( {
1334+ cwd : input . cwd ,
1335+ host : input . host ,
1336+ operation : "getSourceBranch" ,
1337+ query : SOURCE_BRANCH_GRAPHQL_QUERY ,
1338+ variables : { fullPath : input . repository , iid : String ( input . number ) } ,
1339+ decode : decodeSourceBranchJson ,
1340+ } ) ;
1341+
1342+ const deleteSourceBranch = Effect . fn ( "GitLabPullRequestCli.deleteSourceBranch" ) (
1343+ function * ( input : {
1344+ readonly cwd : string ;
1345+ readonly host ?: string | undefined ;
1346+ readonly repository : string ;
1347+ readonly number : number ;
1348+ } ) {
1349+ const refuse = ( reason : GitLabBranchDeletionRefusedError [ "reason" ] ) =>
1350+ new GitLabBranchDeletionRefusedError ( {
1351+ command : "glab" ,
1352+ cwd : input . cwd ,
1353+ number : input . number ,
1354+ reason,
1355+ } ) ;
1356+ const source = yield * sourceBranch ( input ) ;
1357+ if ( source === null ) {
1358+ return yield * new GitLabMergeRequestReadError ( {
1359+ command : "glab" ,
1360+ cwd : input . cwd ,
1361+ operation : "getSourceBranch" ,
1362+ cause : new Error ( "GitLab reported no merge request." ) ,
1363+ } ) ;
1364+ }
1365+ if ( source . open ) return yield * refuse ( "open" ) ;
1366+ if ( ! source . canDelete ) return yield * refuse ( "not-allowed" ) ;
1367+ if ( source . sourceProject === null || source . headSha === null ) {
1368+ return yield * refuse ( "source-unavailable" ) ;
1369+ }
1370+ const path = `projects/${ projectPath ( source . sourceProject ) } /repository/branches/${ encodeURIComponent ( source . branch ) } ` ;
1371+ const branch = yield * api ( { cwd : input . cwd , host : input . host , path } ) . pipe (
1372+ Effect . flatMap ( ( result ) => {
1373+ const decoded = decodeBranchJson ( result . stdout . trim ( ) ) ;
1374+ return Result . isSuccess ( decoded )
1375+ ? Effect . succeed ( decoded . success )
1376+ : Effect . fail (
1377+ new GitLabMergeRequestReadError ( {
1378+ command : "glab" ,
1379+ cwd : input . cwd ,
1380+ operation : "getSourceBranch" ,
1381+ cause : decoded . failure ,
1382+ } ) ,
1383+ ) ;
1384+ } ) ,
1385+ ) ;
1386+ if ( branch . isDefault ) return yield * refuse ( "default-branch" ) ;
1387+ if ( branch . headSha !== source . headSha ) return yield * refuse ( "head-changed" ) ;
1388+ // GitLab's branch delete takes no expected SHA. It answers 412 when the head's authored
1389+ // date is newer than If-Unmodified-Since, which catches a commit pushed after this read but
1390+ // not a force-push of an older-dated commit (a rebase keeps author dates).
1391+ const authoredAt =
1392+ branch . headAuthoredDate === null ? Option . none ( ) : DateTime . make ( branch . headAuthoredDate ) ;
1393+ yield * api ( {
1394+ cwd : input . cwd ,
1395+ host : input . host ,
1396+ path,
1397+ method : "DELETE" ,
1398+ ...( Option . isNone ( authoredAt )
1399+ ? { }
1400+ : {
1401+ headers : [
1402+ `If-Unmodified-Since: ${ DateTime . toDateUtc ( authoredAt . value ) . toUTCString ( ) } ` ,
1403+ ] ,
1404+ } ) ,
1405+ } ) ;
1406+ } ,
1407+ ) ;
1408+
12841409 const mergeRequestStats = ( input : {
12851410 readonly cwd : string ;
12861411 readonly host ?: string | undefined ;
@@ -1472,7 +1597,26 @@ export const make = Effect.gen(function* () {
14721597 [ mergeRequestDetail ( input ) , labelPermission ( input ) ] ,
14731598 { concurrency : 2 } ,
14741599 ) ;
1475- const detail = { ...read , viewerCanEditLabels } ;
1600+ // Only a closed or merged merge request offers its branch for deletion, so an open one,
1601+ // the page most often read, skips the extra query.
1602+ const detail =
1603+ read . state === "open"
1604+ ? { ...read , viewerCanEditLabels }
1605+ : {
1606+ ...read ,
1607+ viewerCanEditLabels,
1608+ viewerCanDeleteBranch : yield * sourceBranch ( input ) . pipe (
1609+ Effect . map ( ( source ) => source ?. canDelete === true ) ,
1610+ // The answer gates one optional action; an unusable CLI or account still surfaces.
1611+ Effect . catchIf (
1612+ ( cause ) =>
1613+ cause . _tag !== "GitLabCliUnavailableError" &&
1614+ cause . _tag !== "GitLabCliAuthenticationError" &&
1615+ cause . _tag !== "GitLabCliRateLimitError" ,
1616+ ( ) => Effect . succeed ( false ) ,
1617+ ) ,
1618+ ) ,
1619+ } ;
14761620 if ( input . downstreamChecks === false || detail . headPipeline === undefined ) return detail ;
14771621 const downstream = yield * triggerJobChecks ( {
14781622 cwd : input . cwd ,
@@ -1820,6 +1964,7 @@ export const make = Effect.gen(function* () {
18201964 // `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
18211965 // no flag for is asked of GitLab directly through the same `api` passthrough the rest of
18221966 // this module writes with.
1967+ if ( input . action === "delete-branch" ) return yield * deleteSourceBranch ( input ) ;
18231968 if ( input . action === "disable-auto-merge" ) {
18241969 const result = yield * api ( {
18251970 cwd : input . cwd ,
0 commit comments