@@ -81,7 +81,7 @@ defmodule MixDependencySubmission.CLI do
8181 help: "GitHub Actions Workflow Name"
8282 ) ,
8383 sha:
84- optimus_options_with_env_default ( "GITHUB_SHA" ,
84+ sha_option (
8585 value_name: "SHA" ,
8686 long: "--sha" ,
8787 help: "Current Git SHA"
@@ -140,4 +140,41 @@ defmodule MixDependencySubmission.CLI do
140140 :error -> [ required: true ]
141141 end ++ details
142142 end
143+
144+ @ spec sha_option ( Keyword . t ( ) ) :: Keyword . t ( )
145+ defp sha_option ( base_opts ) do
146+ # If the GitHub event is a pull request, we need to use the head SHA of the PR
147+ # instead of the commit SHA of the workflow run.
148+ # This is because the workflow run is triggered by the base commit of the PR,
149+ # and we want to report the dependencies of the head commit.
150+ # See: https://github.com/github/dependency-submission-toolkit/blob/72f5e31325b5e1bcc91f1b12eb7abe68e75b2105/src/snapshot.ts#L36-L61
151+ case load_pr_head_sha ( ) do
152+ { :ok , sha } ->
153+ Keyword . put ( base_opts , :default , sha )
154+
155+ :error ->
156+ # If we can't load the PR head SHA, we fall back to the default behavior
157+ # of using the GITHUB_SHA environment variable.
158+ optimus_options_with_env_default ( "GITHUB_SHA" , base_opts )
159+ end
160+ end
161+
162+ # Note that pull_request_target is omitted here.
163+ # That event runs in the context of the base commit of the PR,
164+ # so the snapshot should not be associated with the head commit.
165+
166+ @ pr_events ~w[ pull_request pull_request_comment pull_request_review pull_request_review_comment]
167+
168+ @ spec load_pr_head_sha :: { :ok , << _ :: 320 >> } | :error
169+ defp load_pr_head_sha do
170+ with { :ok , event } when event in @ pr_events <- System . fetch_env ( "GITHUB_EVENT_NAME" ) ,
171+ { :ok , event_path } <- System . fetch_env ( "GITHUB_EVENT_PATH" ) do
172+ event_details_json = File . read! ( event_path )
173+
174+ % { "pull_request" => % { "head" => % { "sha" => << _binary :: 320 >> = sha } } } =
175+ JSON . decode! ( event_details_json )
176+
177+ { :ok , sha }
178+ end
179+ end
143180end
0 commit comments