@@ -8,6 +8,16 @@ type GitHubComment = {
88 } ;
99} ;
1010
11+ class GitHubRequestError extends Error {
12+ constructor (
13+ message : string ,
14+ readonly status : number ,
15+ ) {
16+ super ( message ) ;
17+ this . name = 'GitHubRequestError' ;
18+ }
19+ }
20+
1121function requiredEnv ( name : string ) : string {
1222 const value = Bun . env [ name ] ;
1323 if ( value == null || value . length === 0 ) {
@@ -29,8 +39,9 @@ async function githubRequest<T>(path: string, options: RequestInit = {}): Promis
2939 } ) ;
3040
3141 if ( ! response . ok ) {
32- throw new Error (
42+ throw new GitHubRequestError (
3343 `${ options . method ?? 'GET' } ${ path } failed: ${ response . status } ${ await response . text ( ) } ` ,
44+ response . status ,
3445 ) ;
3546 }
3647
@@ -46,6 +57,27 @@ const prNumber = requiredEnv('PR_NUMBER');
4657const marker = requiredEnv ( 'COMMENT_MARKER' ) ;
4758const body = await Bun . file ( requiredEnv ( 'COMMENT_FILE' ) ) . text ( ) ;
4859
60+ async function createComment ( ) : Promise < void > {
61+ await githubRequest ( `/repos/${ repository } /issues/${ prNumber } /comments` , {
62+ method : 'POST' ,
63+ body : JSON . stringify ( { body } ) ,
64+ } ) ;
65+ }
66+
67+ async function tryCreateComment ( ) : Promise < void > {
68+ try {
69+ await createComment ( ) ;
70+ } catch ( error ) {
71+ if ( error instanceof GitHubRequestError && error . status === 403 ) {
72+ console . warn (
73+ `Skipping PR comment because GitHub token cannot write comments: ${ error . message } ` ,
74+ ) ;
75+ return ;
76+ }
77+ throw error ;
78+ }
79+ }
80+
4981const comments = await githubRequest < GitHubComment [ ] > (
5082 `/repos/${ repository } /issues/${ prNumber } /comments?per_page=100` ,
5183) ;
@@ -54,13 +86,16 @@ const existing = comments.find(
5486) ;
5587
5688if ( existing == null ) {
57- await githubRequest ( `/repos/${ repository } /issues/${ prNumber } /comments` , {
58- method : 'POST' ,
59- body : JSON . stringify ( { body } ) ,
60- } ) ;
89+ await tryCreateComment ( ) ;
6190} else {
62- await githubRequest ( `/repos/${ repository } /issues/comments/${ existing . id } ` , {
63- method : 'PATCH' ,
64- body : JSON . stringify ( { body } ) ,
65- } ) ;
91+ try {
92+ await githubRequest ( `/repos/${ repository } /issues/comments/${ existing . id } ` , {
93+ method : 'PATCH' ,
94+ body : JSON . stringify ( { body } ) ,
95+ } ) ;
96+ } catch ( error ) {
97+ console . warn ( `Failed to update existing PR comment; creating a new comment instead.` ) ;
98+ console . warn ( error ) ;
99+ await tryCreateComment ( ) ;
100+ }
66101}
0 commit comments