jinxapi_github/v1_1_4/request/
code_scanning_upload_sarif.rs

1//! Upload an analysis as SARIF data
2//! 
3//! Uploads SARIF data containing the results of a code scanning analysis to make the results available in a repository. You must use an access token with the `security_events` scope to use this endpoint for private repositories. You can also use tokens with the `public_repo` scope for public repositories only. GitHub Apps must have the `security_events` write permission to use this endpoint.
4//! 
5//! There are two places where you can upload code scanning results.
6//!  - If you upload to a pull request, for example `--ref refs/pull/42/merge` or `--ref refs/pull/42/head`, then the results appear as alerts in a pull request check. For more information, see "[Triaging code scanning alerts in pull requests](/code-security/secure-coding/triaging-code-scanning-alerts-in-pull-requests)."
7//!  - If you upload to a branch, for example `--ref refs/heads/my-branch`, then the results appear in the **Security** tab for your repository. For more information, see "[Managing code scanning alerts for your repository](/code-security/secure-coding/managing-code-scanning-alerts-for-your-repository#viewing-the-alerts-for-a-repository)."
8//! 
9//! You must compress the SARIF-formatted analysis data that you want to upload, using `gzip`, and then encode it as a Base64 format string. For example:
10//! 
11//! ```text
12//! gzip -c analysis-data.sarif | base64 -w0
13//! ```
14//! 
15//! SARIF upload supports a maximum of 5000 results per analysis run. Any results over this limit are ignored and any SARIF uploads with more than 25,000 results are rejected. Typically, but not necessarily, a SARIF file contains a single run of a single tool. If a code scanning tool generates too many results, you should update the analysis configuration to run only the most important rules or queries.
16//! 
17//! The `202 Accepted`, response includes an `id` value.
18//! You can use this ID to check the status of the upload by using this for the `/sarifs/{sarif_id}` endpoint.
19//! For more information, see "[Get information about a SARIF upload](/rest/reference/code-scanning#get-information-about-a-sarif-upload)."
20//! 
21//! [API method documentation](https://docs.github.com/rest/reference/code-scanning#upload-a-sarif-file)
22
23pub struct Content<Body>
24{
25    body: Body,
26    content_type_value: Option<::std::borrow::Cow<'static, [u8]>>,
27}
28
29impl<Body> Content<Body> {
30    pub fn new(body: Body) -> Self {
31        Self { body, content_type_value: None }
32    }
33
34    #[must_use]
35    pub fn with_content_type(mut self, content_type: impl Into<::std::borrow::Cow<'static, [u8]>>) -> Self {
36        self.content_type_value = Some(content_type.into());
37        self
38    }
39
40    fn content_type(&self) -> Option<&[u8]> {
41        self.content_type_value.as_deref()
42    }
43
44    fn into_body(self) -> Body {
45        self.body
46    }
47}
48
49fn url_string(
50    base_url: &str,
51    p_owner: &str,
52    p_repo: &str,
53) -> Result<String, crate::v1_1_4::ApiError> {
54    let trimmed = if base_url.is_empty() {
55        "https://api.github.com"
56    } else {
57        base_url.trim_end_matches('/')
58    };
59    let mut url = String::with_capacity(trimmed.len() + 47);
60    url.push_str(trimmed);
61    url.push_str("/repos/");
62    ::querylizer::Simple::extend(&mut url, &p_owner, false, &::querylizer::encode_path)?;
63    url.push('/');
64    ::querylizer::Simple::extend(&mut url, &p_repo, false, &::querylizer::encode_path)?;
65    url.push_str("/code-scanning/sarifs");
66    Ok(url)
67}
68
69#[cfg(feature = "hyper")]
70pub fn http_builder(
71    base_url: &str,
72    p_owner: &str,
73    p_repo: &str,
74    h_user_agent: &str,
75    h_accept: ::std::option::Option<&str>,
76) -> Result<::http::request::Builder, crate::v1_1_4::ApiError> {
77    let url = url_string(
78        base_url,
79        p_owner,
80        p_repo,
81    )?;
82    let mut builder = ::http::request::Request::post(url);
83    builder = builder.header(
84        "User-Agent",
85        &::querylizer::Simple::to_string(&h_user_agent, false, &::querylizer::passthrough)?
86    );
87    if let Some(value) = &h_accept {
88        builder = builder.header(
89            "Accept",
90            &::querylizer::Simple::to_string(value, false, &::querylizer::passthrough)?
91        );
92    }
93    Ok(builder)
94}
95
96#[cfg(feature = "hyper")]
97pub fn hyper_request(
98    mut builder: ::http::request::Builder,
99    content: Content<::hyper::Body>,
100) -> Result<::http::request::Request<::hyper::Body>, crate::v1_1_4::ApiError>
101{
102    if let Some(content_type) = content.content_type() {
103        builder = builder.header(::http::header::CONTENT_TYPE, content_type);
104    }
105    Ok(builder.body(content.into_body())?)
106}
107
108#[cfg(feature = "hyper")]
109impl From<::hyper::Body> for Content<::hyper::Body> {
110    fn from(body: ::hyper::Body) -> Self {
111        Self::new(body)
112    }
113}
114
115#[cfg(feature = "reqwest")]
116pub fn reqwest_builder(
117    base_url: &str,
118    p_owner: &str,
119    p_repo: &str,
120    h_user_agent: &str,
121    h_accept: ::std::option::Option<&str>,
122) -> Result<::reqwest::Request, crate::v1_1_4::ApiError> {
123    let url = url_string(
124        base_url,
125        p_owner,
126        p_repo,
127    )?;
128    let reqwest_url = ::reqwest::Url::parse(&url)?;
129    let mut request = ::reqwest::Request::new(::reqwest::Method::POST, reqwest_url);
130    let headers = request.headers_mut();
131    headers.append(
132        "User-Agent",
133        ::querylizer::Simple::to_string(&h_user_agent, false, &::querylizer::passthrough)?.try_into()?
134    );
135    if let Some(value) = &h_accept {
136        headers.append(
137            "Accept",
138            ::querylizer::Simple::to_string(value, false, &::querylizer::passthrough)?.try_into()?
139        );
140    }
141    Ok(request)
142}
143
144#[cfg(feature = "reqwest")]
145pub fn reqwest_request(
146    mut builder: ::reqwest::Request,
147    content: Content<::reqwest::Body>,
148) -> Result<::reqwest::Request, crate::v1_1_4::ApiError> {
149    if let Some(content_type) = content.content_type() {
150        builder.headers_mut().append(
151            ::reqwest::header::HeaderName::from_static("content-type"),
152            ::reqwest::header::HeaderValue::try_from(content_type)?,
153        );
154    }
155    *builder.body_mut() = Some(content.into_body());
156    Ok(builder)
157}
158
159#[cfg(feature = "reqwest")]
160impl From<::reqwest::Body> for Content<::reqwest::Body> {
161    fn from(body: ::reqwest::Body) -> Self {
162        Self::new(body)
163    }
164}
165
166#[cfg(feature = "reqwest-blocking")]
167pub fn reqwest_blocking_builder(
168    base_url: &str,
169    p_owner: &str,
170    p_repo: &str,
171    h_user_agent: &str,
172    h_accept: ::std::option::Option<&str>,
173) -> Result<::reqwest::blocking::Request, crate::v1_1_4::ApiError> {
174    let url = url_string(
175        base_url,
176        p_owner,
177        p_repo,
178    )?;
179    let reqwest_url = ::reqwest::Url::parse(&url)?;
180    let mut request = ::reqwest::blocking::Request::new(::reqwest::Method::POST, reqwest_url);
181    let headers = request.headers_mut();
182    headers.append(
183        "User-Agent",
184        ::querylizer::Simple::to_string(&h_user_agent, false, &::querylizer::passthrough)?.try_into()?
185    );
186    if let Some(value) = &h_accept {
187        headers.append(
188            "Accept",
189            ::querylizer::Simple::to_string(value, false, &::querylizer::passthrough)?.try_into()?
190        );
191    }
192    Ok(request)
193}
194
195#[cfg(feature = "reqwest-blocking")]
196pub fn reqwest_blocking_request(
197    mut builder: ::reqwest::blocking::Request,
198    content: Content<::reqwest::blocking::Body>,
199) -> Result<::reqwest::blocking::Request, crate::v1_1_4::ApiError> {
200    if let Some(content_type) = content.content_type() {
201        builder.headers_mut().append(
202            ::reqwest::header::HeaderName::from_static("content-type"),
203            ::reqwest::header::HeaderValue::try_from(content_type)?,
204        );
205    }
206    *builder.body_mut() = Some(content.into_body());
207    Ok(builder)
208}
209
210#[cfg(feature = "reqwest-blocking")]
211impl From<::reqwest::blocking::Body> for Content<::reqwest::blocking::Body> {
212    fn from(body: ::reqwest::blocking::Body) -> Self {
213        Self::new(body)
214    }
215}
216
217/// Types for body parameter in [`super::code_scanning_upload_sarif`]
218pub mod body {
219    #[allow(non_snake_case)]
220    #[derive(Clone, Eq, PartialEq, Debug, Default, ::serde::Serialize, ::serde::Deserialize)]
221    pub struct Json<'a> {
222        /// The SHA of the commit to which the analysis you are uploading relates.
223        pub commit_sha: ::std::borrow::Cow<'a, str>,
224
225        /// The full Git reference, formatted as `refs/heads/<branch name>`,
226        /// `refs/pull/<number>/merge`, or `refs/pull/<number>/head`.
227        pub r#ref: ::std::borrow::Cow<'a, str>,
228
229        /// A Base64 string representing the SARIF file to upload. You must first compress your SARIF file using [`gzip`](http://www.gnu.org/software/gzip/manual/gzip.html) and then translate the contents of the file into a Base64 encoding string. For more information, see "[SARIF support for code scanning](https://docs.github.com/code-security/secure-coding/sarif-support-for-code-scanning)."
230        pub sarif: ::std::borrow::Cow<'a, str>,
231
232        /// The base directory used in the analysis, as it appears in the SARIF file.
233        /// This property is used to convert file paths from absolute to relative, so that alerts can be mapped to their correct location in the repository.
234        /// 
235        /// # Example
236        /// 
237        /// ```json
238        /// "file:///github/workspace/"
239        /// ```
240        #[serde(skip_serializing_if = "Option::is_none", default)]
241        pub checkout_uri: ::std::option::Option<::std::borrow::Cow<'a, str>>,
242
243        /// The time that the analysis run began. This is a timestamp in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format: `YYYY-MM-DDTHH:MM:SSZ`.
244        #[serde(skip_serializing_if = "Option::is_none", default)]
245        pub started_at: ::std::option::Option<::std::borrow::Cow<'a, str>>,
246
247        /// The name of the tool used to generate the code scanning analysis. If this parameter is not used, the tool name defaults to "API". If the uploaded SARIF contains a tool GUID, this will be available for filtering using the `tool_guid` parameter of operations such as `GET /repos/{owner}/{repo}/code-scanning/alerts`.
248        #[serde(skip_serializing_if = "Option::is_none", default)]
249        pub tool_name: ::std::option::Option<::std::borrow::Cow<'a, str>>,
250
251        #[serde(flatten)]
252        pub additionalProperties: ::std::collections::HashMap<::std::borrow::Cow<'a, str>, ::serde_json::value::Value>
253    }
254
255    #[cfg(feature = "hyper")]
256    impl<'a> TryFrom<&Json<'a>> for super::Content<::hyper::Body> {
257        type Error = crate::v1_1_4::ApiError;
258
259        fn try_from(value: &Json<'a>) -> Result<Self, Self::Error> {
260            Ok(
261                Self::new(::serde_json::to_vec(value)?.into())
262                .with_content_type(&b"application/json"[..])
263            )
264        }
265    }
266
267    #[cfg(feature = "reqwest")]
268    impl<'a> TryFrom<&Json<'a>> for super::Content<::reqwest::Body> {
269        type Error = crate::v1_1_4::ApiError;
270
271        fn try_from(value: &Json<'a>) -> Result<Self, Self::Error> {
272            Ok(
273                Self::new(::serde_json::to_vec(value)?.into())
274                .with_content_type(&b"application/json"[..])
275            )
276        }
277    }
278
279    #[cfg(feature = "reqwest-blocking")]
280    impl<'a> TryFrom<&Json<'a>> for super::Content<::reqwest::blocking::Body> {
281        type Error = crate::v1_1_4::ApiError;
282
283        fn try_from(value: &Json<'a>) -> Result<Self, Self::Error> {
284            Ok(
285                Self::new(::serde_json::to_vec(value)?.into())
286                .with_content_type(&b"application/json"[..])
287            )
288        }
289    }
290}