@@ -56,6 +56,21 @@ def comment_pr(repo, run_id):
5656 if os .path .isdir ("pr" ):
5757 shutil .rmtree ("pr" )
5858
59+ utils .download_artifact (repo , "comment" , "comment" , run_id )
60+
61+ try :
62+ with open ("comment/ID" ) as file :
63+ raw_comment_id = int (file .read ())
64+ except Exception as e :
65+ # If there is no existing comment, comment/ID will contain just a
66+ # newline (due to jq & gh behaviour). This will cause `int(file.read())`
67+ # to fail, so we catch that and set `raw_comment_id` to `None`.
68+ print ("Could not retrieve an existing comment ID. \n " , e )
69+ raw_comment_id = None
70+ finally :
71+ if os .path .isdir ("comment" ):
72+ shutil .rmtree ("comment" )
73+
5974 # Try storing diff for previous run:
6075 prev_run_id = 0
6176 prev_diff_exists = False
@@ -95,14 +110,37 @@ def comment_pr(repo, run_id):
95110
96111 comment = comment_first_line + \
97112 "A recent commit removed the previously reported differences."
98- post_comment (comment , repo , pr_number )
113+
114+ if raw_comment_id is None :
115+ post_initial_comment (comment , repo , pr_number )
116+ else :
117+ update_existing_comment (comment , repo , pr_number , raw_comment_id )
99118
100119
101- def post_comment (comment , repo , pr_number ):
120+ def post_initial_comment (comment , repo , pr_number ):
102121 print (f"Posting comment to PR #{ pr_number } " )
103122 utils .subprocess_run (["gh" , "pr" , "comment" , str (pr_number ),
104123 "--repo" , repo , "--body" , comment ])
105124
125+ def update_existing_comment (comment , repo , pr_number , raw_comment_id ):
126+ # Fetch existing comment, and validate:
127+ # - comment belongs to the PR with number `pr_number`
128+ # - comment starts with the expected prefix `comment_first_line`
129+ # - comment author is github-actions[bot]
130+ comment_author = "github-actions[bot]"
131+ filter = f"select(.issue_url | endswith(\" { repo } /issues/{ pr_number } \" )) " + \
132+ f"| select(.body | startswith(\" { comment_first_line } \" )) " + \
133+ f"| select(.user.login == \" { comment_author } \" ) " + \
134+ "| .id"
135+ comment_id = utils .subprocess_check_output (["gh" , "api" , f"repos/{ repo } /issues/comments/{ raw_comment_id } " ,
136+ "--jq" , filter ]).strip ()
137+
138+ if comment_id :
139+ print (f"Updating comment { comment_id } on PR #{ pr_number } " )
140+ utils .subprocess_run (["gh" , "api" , f"repos/{ repo } /issues/comments/{ comment_id } " ,
141+ "-X" , "PATCH" , "-f" , f"body={ comment } " ])
142+ else :
143+ print (f"Comment { raw_comment_id } did not pass validations: not editing." )
106144
107145def get_previous_run_id (repo , run_id , pr_number ):
108146 """
0 commit comments