-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path__init__.py
More file actions
166 lines (132 loc) · 5.51 KB
/
__init__.py
File metadata and controls
166 lines (132 loc) · 5.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import json
import logging
from typing import Optional, Union
from dataclasses import dataclass, asdict
log = logging.getLogger("socketdev")
@dataclass
class RepositoryInfo:
id: str
created_at: str # Could be datetime if we want to parse it
updated_at: str # Could be datetime if we want to parse it
head_full_scan_id: str
name: str
description: str
homepage: str
visibility: str
archived: bool
default_branch: str
slug: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "RepositoryInfo":
return cls(
id=data["id"],
created_at=data.get("created_at", ""),
updated_at=data.get("updated_at", ""),
head_full_scan_id=data.get("head_full_scan_id", ""),
name=data["name"],
description=data.get("description", ""),
homepage=data.get("homepage", ""),
visibility=data.get("visibility", "private"),
archived=data.get("archived", False),
default_branch=data.get("default_branch", "main"),
slug=data["slug"]
)
@dataclass
class GetRepoResponse:
success: bool
status: int
data: Optional[RepositoryInfo] = None
message: Optional[str] = None
def __getitem__(self, key):
return getattr(self, key)
def to_dict(self):
return asdict(self)
@classmethod
def from_dict(cls, data: dict) -> "GetRepoResponse":
data_field = data.get("data")
return cls(
success=data["success"],
status=data["status"],
message=data.get("message"),
data=RepositoryInfo.from_dict(data_field) if data_field is not None else None,
)
class Repos:
def __init__(self, api):
self.api = api
def get(self, org_slug: str, **kwargs) -> dict[str, list[dict] | int]:
query_params = kwargs
path = "orgs/" + org_slug + "/repos"
if query_params: # Only add query string if we have parameters
path += "?"
for param in query_params:
value = query_params[param]
path += f"{param}={value}&"
path = path.rstrip("&")
response = self.api.do_request(path=path)
if response.status_code == 200:
raw_result = response.json()
per_page = int(query_params.get("per_page", 30))
# TEMPORARY: Handle pagination edge case where API returns nextPage=1 even when no more results exist
if raw_result["nextPage"] != 0 and len(raw_result["results"]) < per_page:
raw_result["nextPage"] = 0
return raw_result
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error getting repositories: {response.status_code}, message: {error_message}")
return {}
def repo(self, org_slug: str, repo_name: str, use_types: bool = False) -> Union[dict, GetRepoResponse]:
path = f"orgs/{org_slug}/repos/{repo_name}"
response = self.api.do_request(path=path)
if response.status_code == 200:
result = response.json()
if use_types:
return GetRepoResponse.from_dict({"success": True, "status": 200, "data": result})
return result
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Failed to get repository: {response.status_code}, message: {error_message}")
if use_types:
return GetRepoResponse.from_dict(
{"success": False, "status": response.status_code, "message": error_message}
)
return {}
def delete(self, org_slug: str, name: str) -> dict:
path = f"orgs/{org_slug}/repos/{name}"
response = self.api.do_request(path=path, method="DELETE")
if response.status_code == 200:
return response.json()
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error deleting repository: {response.status_code}, message: {error_message}")
return {}
def post(self, org_slug: str, **kwargs) -> dict:
params = {}
if kwargs:
for key, val in kwargs.items():
params[key] = val
if len(params) == 0:
return {}
path = "orgs/" + org_slug + "/repos"
payload = json.dumps(params)
response = self.api.do_request(path=path, method="POST", payload=payload)
if response.status_code == 201:
return response.json()
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error creating repository: {response.status_code}, message: {error_message}")
return {}
def update(self, org_slug: str, repo_name: str, **kwargs) -> dict:
params = {}
if kwargs:
for key, val in kwargs.keys():
params[key] = val
if len(params) == 0:
return {}
path = f"orgs/{org_slug}/repos/{repo_name}"
payload = json.dumps(params)
response = self.api.do_request(path=path, method="POST", payload=payload)
if response.status_code == 200:
return response.json()
error_message = response.json().get("error", {}).get("message", "Unknown error")
log.error(f"Error updating repository: {response.status_code}, message: {error_message}")
return {}