-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathenv.py
More file actions
416 lines (363 loc) · 14 KB
/
env.py
File metadata and controls
416 lines (363 loc) · 14 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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
"""
Sets up the environment variables for the action.
"""
import os
import re
from dataclasses import dataclass
from os.path import dirname, join
from dotenv import load_dotenv
MAX_TITLE_LENGTH = 70
MAX_BODY_LENGTH = 65536
MAX_COMMIT_MESSAGE_LENGTH = 65536
SUPPORTED_PACKAGE_ECOSYSTEMS = [
"bazel",
"bun",
"bundler",
"cargo",
"composer",
"conda",
"devcontainers",
"docker",
"docker-compose",
"dotnet-sdk",
"elm",
"gitsubmodule",
"github-actions",
"gomod",
"gradle",
"helm",
"julia",
"maven",
"mix",
"npm",
"nuget",
"pip",
"pre-commit",
"pub",
"rust-toolchain",
"swift",
"terraform",
"uv",
"vcpkg",
]
@dataclass(frozen=True)
class EvergreenConfig: # pylint: disable=too-many-instance-attributes
"""Configuration for the Evergreen action, parsed from environment variables."""
organization: str | None
repository_list: list[str]
search_query: str
gh_app_id: int | None
gh_app_installation_id: int | None
gh_app_private_key_bytes: bytes
gh_app_enterprise_only: bool
token: str
ghe: str
ghe_api_url: str
exempt_repositories_list: list[str]
follow_up_type: str
title: str
body: str
created_after_date: str
dry_run: bool
commit_message: str
project_id: str | None
group_dependencies: bool
filter_visibility: list[str]
batch_size: int | None
enable_security_updates: bool
exempt_ecosystems: list[str]
update_existing: bool
repo_specific_exemptions: dict[str, list[str]]
schedule: str
schedule_day: str
team_name: str | None
labels: list[str]
dependabot_config_file: str | None
def get_api_endpoint(ghe: str, ghe_api_url: str) -> str:
"""Return the GitHub API endpoint URL.
Args:
ghe: The GitHub Enterprise URL (e.g., https://github.example.com)
ghe_api_url: Optional override for the full API endpoint URL
Returns:
The API endpoint URL to use for REST/GraphQL calls.
"""
if ghe_api_url:
return ghe_api_url.rstrip("/")
if ghe:
return f"{ghe.rstrip('/')}/api/v3"
return "https://api.github.com"
def get_bool_env_var(env_var_name: str, default: bool = False) -> bool:
"""Get a boolean environment variable.
Args:
env_var_name: The name of the environment variable to retrieve.
default: The default value to return if the environment variable is not set.
Returns:
The value of the environment variable as a boolean.
"""
ev = os.environ.get(env_var_name, "")
if ev == "" and default:
return default
return ev.strip().lower() == "true"
def get_int_env_var(env_var_name: str) -> int | None:
"""Get an integer environment variable.
Args:
env_var_name: The name of the environment variable to retrieve.
Returns:
The value of the environment variable as an integer or None.
"""
env_var = os.environ.get(env_var_name)
if env_var is None or not env_var.strip():
return None
try:
return int(env_var)
except ValueError:
return None
def parse_repo_specific_exemptions(repo_specific_exemptions_str: str) -> dict:
"""Parse the REPO_SPECIFIC_EXEMPTIONS environment variable into a dictionary.
Args:
repo_specific_exemptions_str: The REPO_SPECIFIC_EXEMPTIONS environment variable as a string.
Returns:
A dictionary where keys are repository names and values are lists of exempt ecosystems.
"""
exemptions_dict = {}
if repo_specific_exemptions_str:
# if repo_specific_exemptions_str doesn't have a ; and : character, it's not valid
separators = [";", ":"]
if not all(sep in repo_specific_exemptions_str for sep in separators):
raise ValueError(
"REPO_SPECIFIC_EXEMPTIONS environment variable not formatted correctly"
)
exemptions_list = repo_specific_exemptions_str.split(";")
for exemption in exemptions_list:
if (
exemption == ""
): # Account for final ; in the repo_specific_exemptions_str
continue
repo, ecosystems = exemption.split(":")
cleaned_ecosystems = []
for ecosystem in ecosystems.split(","):
ecosystem = ecosystem.strip().lower()
if ecosystem not in SUPPORTED_PACKAGE_ECOSYSTEMS:
raise ValueError(
"REPO_SPECIFIC_EXEMPTIONS environment variable not formatted correctly. Unrecognized package-ecosystem."
)
cleaned_ecosystems.append(ecosystem)
exemptions_dict[repo.strip()] = cleaned_ecosystems
return exemptions_dict
def get_env_vars(
test: bool = False,
) -> EvergreenConfig:
"""
Get the environment variables for use in the action.
Args:
test: If True, skip loading from .env file.
Returns:
EvergreenConfig: A frozen dataclass containing all configuration values.
"""
if not test: # pragma: no cover
# Load from .env file if it exists and not testing
dotenv_path = join(dirname(__file__), ".env")
load_dotenv(dotenv_path)
organization = os.getenv("ORGANIZATION")
repositories_str = os.getenv("REPOSITORY")
search_query = os.getenv("REPOSITORY_SEARCH_QUERY", "").strip()
team_name = os.getenv("TEAM_NAME")
# Either organization, repository, or search_query must be set
if not organization and not repositories_str and not search_query:
raise ValueError(
"ORGANIZATION, REPOSITORY, and REPOSITORY_SEARCH_QUERY environment variables were not set. Please set one"
)
# Team name and repository are mutually exclusive
if repositories_str and team_name:
raise ValueError(
"TEAM_NAME environment variable cannot be used with REPOSITORY"
)
# Separate repositories_str into a list based on the comma separator
repositories_list = []
if repositories_str:
repositories_list = [
repository.strip() for repository in repositories_str.split(",")
]
gh_app_id = get_int_env_var("GH_APP_ID")
gh_app_private_key_bytes = os.environ.get("GH_APP_PRIVATE_KEY", "").encode("utf8")
gh_app_installation_id = get_int_env_var("GH_APP_INSTALLATION_ID")
gh_app_enterprise_only = get_bool_env_var("GITHUB_APP_ENTERPRISE_ONLY")
if gh_app_id and (not gh_app_private_key_bytes or not gh_app_installation_id):
raise ValueError(
"GH_APP_ID set and GH_APP_INSTALLATION_ID or GH_APP_PRIVATE_KEY variable not set"
)
token = os.getenv("GH_TOKEN", "")
if (
not gh_app_id
and not gh_app_private_key_bytes
and not gh_app_installation_id
and not token
):
raise ValueError("GH_TOKEN environment variable not set")
ghe = os.getenv("GH_ENTERPRISE_URL", default="").strip()
ghe_api_url = os.getenv("GH_ENTERPRISE_API_URL", default="").strip().rstrip("/")
if ghe_api_url and not ghe:
raise ValueError(
"GH_ENTERPRISE_API_URL requires GH_ENTERPRISE_URL to also be set"
)
exempt_repos = os.getenv("EXEMPT_REPOS")
exempt_repositories_list = []
if exempt_repos:
exempt_repositories_list = [
repository.strip() for repository in exempt_repos.split(",")
]
follow_up_type = os.getenv("TYPE")
# make sure that follow_up_type is either "issue" or "pull"
if follow_up_type:
if follow_up_type not in ("issue", "pull"):
raise ValueError("TYPE environment variable not 'issue' or 'pull'")
else:
follow_up_type = "pull"
title = os.getenv("TITLE")
# make sure that title is a string with less than MAX_TITLE_LENGTH characters
if title:
if len(title) > MAX_TITLE_LENGTH:
raise ValueError("TITLE environment variable is too long")
else:
title = "Enable Dependabot"
body = os.getenv("BODY")
if body and len(body) > MAX_BODY_LENGTH:
raise ValueError("BODY environment variable is too long")
if not body:
default_bodies = {
"pull": "Dependabot could be enabled for this repository. \
Please enable it by merging this pull request so that we can keep our dependencies up to date and secure.",
"issue": (
"Please update the repository to include a Dependabot configuration file.\n"
"This will ensure our dependencies remain updated and secure.\n"
"Follow the guidelines in [creating Dependabot configuration files]"
"(https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file) "
"to set it up properly.\n\n"
"Here's an example of the code:"
),
}
body = body = default_bodies[follow_up_type]
commit_message = os.getenv("COMMIT_MESSAGE")
if commit_message:
if len(commit_message) > MAX_COMMIT_MESSAGE_LENGTH:
raise ValueError("COMMIT_MESSAGE environment variable is too long")
else:
commit_message = "Create/Update dependabot.yaml"
created_after_date = os.getenv("CREATED_AFTER_DATE", "")
is_match = re.match(r"\d{4}-\d{2}-\d{2}", created_after_date)
if created_after_date and not is_match:
raise ValueError(
f"CREATED_AFTER_DATE '{created_after_date}' environment variable not in YYYY-MM-DD"
)
group_dependencies_bool = get_bool_env_var("GROUP_DEPENDENCIES")
enable_security_updates_bool = get_bool_env_var(
"ENABLE_SECURITY_UPDATES", default=True
)
dry_run_bool = get_bool_env_var("DRY_RUN")
batch_size_str = os.getenv("BATCH_SIZE")
batch_size = int(batch_size_str) if batch_size_str else None
if batch_size and batch_size <= 0:
raise ValueError("BATCH_SIZE environment variable is 0 or lower")
filter_visibility = os.getenv("FILTER_VISIBILITY")
filter_visibility_list = []
if filter_visibility:
filter_visibility_set = set()
for visibility in filter_visibility.split(","):
if visibility.strip().lower() not in ["public", "private", "internal"]:
raise ValueError(
"FILTER_VISIBILITY environment variable not 'public', 'private', or 'internal'"
)
filter_visibility_set.add(visibility.strip().lower())
filter_visibility_list = sorted(list(filter_visibility_set))
else:
filter_visibility_list = sorted(["public", "private", "internal"]) # all
exempt_ecosystems = os.getenv("EXEMPT_ECOSYSTEMS")
exempt_ecosystems_list = []
if exempt_ecosystems:
for ecosystem in exempt_ecosystems.split(","):
ecosystem = ecosystem.lower().strip()
if not ecosystem:
continue
if ecosystem not in SUPPORTED_PACKAGE_ECOSYSTEMS:
raise ValueError(
f"EXEMPT_ECOSYSTEMS environment variable contains an unrecognized package-ecosystem: '{ecosystem}'."
)
exempt_ecosystems_list.append(ecosystem)
project_id = os.getenv("PROJECT_ID")
if project_id and not project_id.isnumeric():
raise ValueError("PROJECT_ID environment variable is not numeric")
update_existing = get_bool_env_var("UPDATE_EXISTING")
repo_specific_exemptions_str = os.getenv("REPO_SPECIFIC_EXEMPTIONS", "")
repo_specific_exemptions = parse_repo_specific_exemptions(
repo_specific_exemptions_str
)
schedule = os.getenv("SCHEDULE", "").strip().lower()
if schedule and schedule not in ["daily", "weekly", "monthly"]:
raise ValueError(
"SCHEDULE environment variable not 'daily', 'weekly', or 'monthly'"
)
if not schedule:
schedule = "weekly"
schedule_day = os.getenv("SCHEDULE_DAY", "").strip().lower()
if schedule != "weekly" and schedule_day:
raise ValueError(
"SCHEDULE_DAY environment variable not needed when SCHEDULE is not 'weekly'"
)
if (
schedule == "weekly"
and schedule_day
and schedule_day
not in [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
):
raise ValueError(
"SCHEDULE_DAY environment variable not 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', or 'sunday'"
)
labels_str = os.getenv("LABELS")
labels_list = []
if labels_str:
labels_list = [label.lower().strip() for label in labels_str.split(",")]
dependabot_config_file = os.getenv("DEPENDABOT_CONFIG_FILE")
if dependabot_config_file and not os.path.exists(dependabot_config_file):
raise ValueError(
f"No dependabot extra configuration found. Please create one in {dependabot_config_file}"
)
return EvergreenConfig(
organization=organization,
repository_list=repositories_list,
search_query=search_query,
gh_app_id=gh_app_id,
gh_app_installation_id=gh_app_installation_id,
gh_app_private_key_bytes=gh_app_private_key_bytes,
gh_app_enterprise_only=gh_app_enterprise_only,
token=token,
ghe=ghe,
ghe_api_url=ghe_api_url,
exempt_repositories_list=exempt_repositories_list,
follow_up_type=follow_up_type,
title=title,
body=body,
created_after_date=created_after_date,
dry_run=dry_run_bool,
commit_message=commit_message,
project_id=project_id,
group_dependencies=group_dependencies_bool,
filter_visibility=filter_visibility_list,
batch_size=batch_size,
enable_security_updates=enable_security_updates_bool,
exempt_ecosystems=exempt_ecosystems_list,
update_existing=update_existing,
repo_specific_exemptions=repo_specific_exemptions,
schedule=schedule,
schedule_day=schedule_day,
team_name=team_name,
labels=labels_list,
dependabot_config_file=dependabot_config_file,
)