Skip to content

Commit

Permalink
Add: Extend GitHub API for code scanning analyses
Browse files Browse the repository at this point in the history
Add GitHub API for getting and deleting code scanning analyses.
  • Loading branch information
bjoernricks committed Oct 19, 2023
1 parent efe1544 commit 9993a95
Show file tree
Hide file tree
Showing 4 changed files with 493 additions and 0 deletions.
146 changes: 146 additions & 0 deletions pontos/github/api/code_scanning.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from pontos.github.models.code_scanning import (
AlertSort,
AlertState,
Analysis,
CodeScanningAlert,
DismissedReason,
Instance,
Expand Down Expand Up @@ -309,3 +310,148 @@ async def instances(
async for response in self._client.get_all(api, params=params):
for alert in response.json():
yield Instance.from_dict(alert)

async def analyses(
self,
repo: str,
*,
tool_name: Optional[str] = None,
tool_guid: Optional[str] = "",
ref: Optional[str] = None,
sarif_id: Optional[str] = None,
direction: Union[str, SortOrder] = SortOrder.DESC,
) -> AsyncIterator[Analysis]:
"""
Lists the details of all code scanning analyses for a repository,
starting with the most recent.
https://docs.github.com/en/rest/code-scanning/code-scanning#list-code-scanning-analyses-for-a-repository
Args:
repo: GitHub repository (owner/name)
tool_name: The name of a code scanning tool. Only results by this
tool will be listed. You can specify the tool by using either
tool_name or tool_guid, but not both.
tool_guid: The GUID of a code scanning tool. Only results by this
tool will be listed. Note that some code scanning tools may not
include a GUID in their analysis data. You can specify the tool
by using either tool_guid or tool_name, but not both
ref: The Git reference for the analyses you want to list. The ref
for a branch can be formatted either as refs/heads/<branch name>
or simply <branch name>. To reference a pull request use
refs/pull/<number>/merge.
sarif_id: Filter analyses belonging to the same SARIF upload
Raises:
HTTPStatusError: A httpx.HTTPStatusError is raised if the request
failed.
Returns:
An async iterator yielding the code scanning alert analysis data
Example:
.. code-block:: python
from pontos.github.api import GitHubAsyncRESTApi
async with GitHubAsyncRESTApi(token) as api:
async for data in api.code_scanning.analyses(
"org/repo"
):
print(data)
"""

api = f"/repos/{repo}/code-scanning/analyses"
params: dict[str, Union[str, None]] = {"per_page": "100"}

if tool_name:
params["tool_name"] = tool_name
if tool_guid or tool_guid is None:
params["tool_guid"] = tool_guid
if ref:
params["ref"] = ref
if sarif_id:
params["sarif_id"] = sarif_id
if direction:
params["direction"] = enum_or_value(direction)

async for response in self._client.get_all(api, params=params):
response.raise_for_status()

for alert in response.json():
yield Analysis.from_dict(alert)

async def analysis(
self,
repo: str,
analysis_id: Union[int, str],
) -> Analysis:
"""
Gets a specified code scanning analysis for a repository
https://docs.github.com/en/rest/code-scanning/code-scanning#get-a-code-scanning-analysis-for-a-repository
Args:
repo: GitHub repository (owner/name)
analysis_id: The ID of the analysis
Raises:
HTTPStatusError: A httpx.HTTPStatusError is raised if the request
failed.
Returns:
Code scanning alert analysis data
Example:
.. code-block:: python
from pontos.github.api import GitHubAsyncRESTApi
async with GitHubAsyncRESTApi(token) as api:
analysis = await api.code_scanning.analysis(
"org/repo", 123
)
print(analysis)
"""

api = f"/repos/{repo}/code-scanning/analyses/{analysis_id}"
response = await self._client.get(api)
response.raise_for_status()
return Analysis.from_dict(response.json())

async def delete_analysis(
self,
repo: str,
analysis_id: Union[int, str],
) -> dict[str, str]:
"""
Delete a specified code scanning analysis from a repository
https://docs.github.com/en/rest/code-scanning/code-scanning#delete-a-code-scanning-analysis-from-a-repository
Args:
repo: GitHub repository (owner/name)
analysis_id: The ID of the analysis
Raises:
HTTPStatusError: A httpx.HTTPStatusError is raised if the request
failed.
Returns:
See the GitHub documentation for the response object
Example:
.. code-block:: python
from pontos.github.api import GitHubAsyncRESTApi
async with GitHubAsyncRESTApi(token) as api:
await api.code_scanning.delete(
"org/repo", 123
)
"""

api = f"/repos/{repo}/code-scanning/analyses/{analysis_id}"
response = await self._client.delete(api)
response.raise_for_status()
return response.json()
48 changes: 48 additions & 0 deletions pontos/github/models/code_scanning.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,51 @@ class CodeScanningAlert(GitHubModel):
dismissed_at: Optional[datetime] = None
dismissed_reason: Optional[DismissedReason] = None
dismissed_comment: Optional[str] = None


@dataclass
class Analysis(GitHubModel):
"""
Details for a code scanning analyses
Attributes:
ref: The full Git reference, formatted as `refs/heads/<branch name>`,
`refs/pull/<number>/merge`, or `refs/pull/<number>/head`
commit_sha: The SHA of the commit to which the analysis you are
uploading relates
analysis_key: Identifies the configuration under which the analysis was
executed. For example, in GitHub Actions this includes the workflow
filename and job name
environment: Identifies the variable values associated with the
environment in which this analysis was performed
category: Identifies the configuration under which the analysis was
executed. Used to distinguish between multiple analyses for the same
tool and commit, but performed on different languages or different
parts of the code
error: Error generated when processing the analysis
created_at: The time that the analysis was created
results_count: The total number of results in the analysis
rules_count: The total number of rules used in the analysis
id: Unique identifier for this analysis
url: The REST API URL of the analysis resource
sarif_id: An identifier for the upload
tool: The tool used to generate the code scanning analysis
deletable:
warning: Warning generated when processing the analysis
"""

ref: str
commit_sha: str
analysis_key: str
environment: str
category: str
error: str
created_at: datetime
results_count: int
rules_count: int
id: int
url: str
sarif_id: str
tool: Tool
deletable: bool
warning: str
Loading

0 comments on commit 9993a95

Please sign in to comment.