|
| 1 | +import os |
| 2 | +import json |
| 3 | +import requests |
| 4 | +import argparse |
| 5 | + |
| 6 | +SNYK_TOKEN = os.getenv("SNYK_TOKEN") |
| 7 | + |
| 8 | + |
| 9 | +class APIClient: |
| 10 | + def __init__( |
| 11 | + self, snyk_token, owner, name, snyk_org, integration_id, branch |
| 12 | + ) -> None: |
| 13 | + self.snyk_token = snyk_token |
| 14 | + self.owner = owner |
| 15 | + self.name = name |
| 16 | + self.snyk_org = snyk_org |
| 17 | + self.integration_id = integration_id |
| 18 | + self.branch = branch |
| 19 | + self.base_url = "https://api.snyk.io/v1" |
| 20 | + |
| 21 | + def import_repo(self) -> object: |
| 22 | + request_url = f"{self.base_url}/org/{self.snyk_org}/integrations/{self.integration_id}/import" |
| 23 | + headers = self._format_headers() |
| 24 | + body = self._format_body() |
| 25 | + response = requests.post( |
| 26 | + request_url, |
| 27 | + headers=headers, |
| 28 | + data=body, |
| 29 | + ) |
| 30 | + return response |
| 31 | + |
| 32 | + def _format_body(self) -> object: |
| 33 | + body = json.dumps( |
| 34 | + {"target": {"owner": self.owner, "name": self.name, "branch": self.branch}} |
| 35 | + ) |
| 36 | + return body |
| 37 | + |
| 38 | + def _format_headers(self) -> object: |
| 39 | + headers = { |
| 40 | + "Content-Type": "application/json", |
| 41 | + "Authorization": f"token {self.snyk_token}", |
| 42 | + } |
| 43 | + return headers |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == "__main__": |
| 47 | + parser = argparse.ArgumentParser(description="Import a repository to Snyk.") |
| 48 | + parser.add_argument("--owner", required=True, help="Repository owner") |
| 49 | + parser.add_argument("--name", required=True, help="Repository name") |
| 50 | + parser.add_argument("--snyk-org", required=True, help="Snyk organization ID") |
| 51 | + parser.add_argument("--integration-id", required=True, help="Snyk integration ID") |
| 52 | + parser.add_argument("--branch", required=True, help="Repository branch") |
| 53 | + |
| 54 | + args = parser.parse_args() |
| 55 | + |
| 56 | + client = APIClient( |
| 57 | + SNYK_TOKEN, |
| 58 | + args.owner, |
| 59 | + args.name, |
| 60 | + args.snyk_org, |
| 61 | + args.integration_id, |
| 62 | + args.branch, |
| 63 | + ) |
| 64 | + response = client.import_repo() |
| 65 | + print("status_code", response.status_code, response.text) |
0 commit comments