forked from bazelbuild/bazel-central-registry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbcr_validation.py
612 lines (545 loc) · 27 KB
/
bcr_validation.py
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
#!/usr/bin/env python3
#
# Copyright 2022 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=invalid-name
# pylint: disable=line-too-long
# pylint: disable=missing-function-docstring
"""A script to perform BCR validations for Bazel modules
Validations performed are:
- Verify versions in metadata.json matches existing versions
- Verify the source archive URL match the source repositories
- Verify the source archive URL is stable
- Verify if the presubmit.yml file matches the previous version
- If not, we should require BCR maintainer review.
- Verify the checked in MODULE.bazel file matches the one in the extracted and patched source tree.
"""
import argparse
import ast
import json
import subprocess
from pathlib import Path
import shutil
import sys
import tempfile
import os
import yaml
from enum import Enum
from difflib import unified_diff
from urllib.parse import urlparse
from registry import RegistryClient
from registry import Version
from registry import download
from registry import download_file
from registry import integrity
from registry import read
from verify_stable_archives import UrlStability
from verify_stable_archives import verify_stable_archive
class BcrValidationResult(Enum):
GOOD = 1
NEED_BCR_MAINTAINER_REVIEW = 2
FAILED = 3
RED = "\x1b[31m"
GREEN = "\x1b[32m"
YELLOW = "\x1b[33m"
RESET = "\x1b[0m"
COLOR = {
BcrValidationResult.GOOD: GREEN,
BcrValidationResult.NEED_BCR_MAINTAINER_REVIEW: YELLOW,
BcrValidationResult.FAILED: RED,
}
def print_collapsed_group(name):
print("\n\n--- {0}\n\n".format(name))
def print_expanded_group(name):
print("\n\n+++ {0}\n\n".format(name))
def parse_module_versions(registry, check_all, inputs):
"""Parse module versions to be validated from input."""
if check_all:
return registry.get_all_module_versions()
if not inputs:
return []
result = []
for s in inputs:
if "@" in s:
name, version = s.split("@")
result.append((name, version))
else:
result.extend(registry.get_module_versions(s))
return result
def apply_patch(work_dir, patch_strip, patch_file):
# Requires patch to be installed
subprocess.run(
["patch", "-p%d" % patch_strip, "-f", "-l", "-i", patch_file],
shell=False,
check=True,
env=os.environ,
cwd=work_dir,
)
def run_git(*args):
# Requires git to be installed
subprocess.run(
["git", *args],
shell=False,
check=True,
env=os.environ,
)
def fix_line_endings(lines):
return [line.rstrip() + "\n" for line in lines]
class BcrValidationException(Exception):
"""
Raised whenever we should stop the validation immediately.
"""
class BcrValidator:
def __init__(self, registry, should_fix):
self.validation_results = []
self.registry = registry
# Whether the validator should try to fix the detected error.
self.should_fix = should_fix
def report(self, type, message):
color = COLOR[type]
print(f"{color}{type}{RESET}: {message}\n")
self.validation_results.append((type, message))
def verify_module_existence(self, module_name, version):
"""Verify the directory exists and the version is recorded in metadata.json."""
if not self.registry.contains(module_name, version):
self.report(BcrValidationResult.FAILED, f"{module_name}@{version} doesn't exist.")
raise BcrValidationException("The module to be validated doesn't exist!")
versions = self.registry.get_metadata(module_name)["versions"]
if version not in versions:
self.report(
BcrValidationResult.FAILED, f"Version {version} is not recorded in {module_name}'s metadata.json file."
)
else:
self.report(BcrValidationResult.GOOD, "The module exists and is recorded in metadata.json.")
def verify_source_archive_url_match_github_repo(self, module_name, version):
"""Verify the source archive URL matches the github repo. For now, we only support github repositories check."""
if self.registry.get_source(module_name, version).get("type", None) == "git_repository":
source_url = self.registry.get_source(module_name, version)["remote"]
# Preprocess the git URL to make the comparison easier.
if source_url.startswith("git@"):
source_url = source_url.removeprefix("git@")
source_netloc, source_parts = source_url.split(":")
source_url = "https://" + source_netloc + "/" + source_parts
if source_url.endswith(".git"):
source_url = source_url.removesuffix(".git")
# The asterisk here is to prevent the final slash from getting
# dropped by os.path.abspath().
source_url = source_url + "/*"
else:
source_url = self.registry.get_source(module_name, version)["url"]
source_repositories = self.registry.get_metadata(module_name).get("repository", [])
matched = not source_repositories
for source_repository in source_repositories:
if matched:
break
repo_type, repo_path = source_repository.split(":")
if repo_type == "github":
parts = urlparse(source_url)
matched = (
parts.scheme == "https"
and parts.netloc == "github.com"
and os.path.abspath(parts.path).startswith(f"/{repo_path}/")
)
elif repo_type == "https":
repo = urlparse(source_repository)
parts = urlparse(source_url)
matched = (
parts.scheme == repo.scheme
and parts.netloc == repo.netloc
and os.path.abspath(parts.path).startswith(f"{repo.path}/")
)
if not matched:
self.report(
BcrValidationResult.FAILED,
f"The source URL of {module_name}@{version} ({source_url}) doesn't match any of the module's source repositories {source_repositories}.",
)
else:
self.report(BcrValidationResult.GOOD, "The source URL matches one of the source repositories.")
def verify_source_archive_url_stability(self, module_name, version):
"""Verify source archive URL is stable"""
if self.registry.get_source(module_name, version).get("type", None) == "git_repository":
return
source_url = self.registry.get_source(module_name, version)["url"]
if verify_stable_archive(source_url) == UrlStability.UNSTABLE:
self.report(
BcrValidationResult.FAILED,
f"{module_name}@{version} is using an unstable source url: `{source_url}`.\n"
+ "If at all possible, you should use a release archive URL in the format of "
+ "`https://github.com/<ORGANIZATION>/<REPO>/releases/download/<version>/<name>.tar.gz` "
+ "to ensure the archive checksum stability.\n"
+ "See https://blog.bazel.build/2023/02/15/github-archive-checksum.html for more context.\n"
+ "If no release archives are available, please add a comment to your BCR PR with the text\n"
+ " @bazel-io skip_check unstable_url\n"
+ "and this check will be skipped.",
)
else:
self.report(BcrValidationResult.GOOD, "The source URL doesn't look unstable.")
def verify_source_archive_url_integrity(self, module_name, version):
"""Verify the integrity value of the URL is correct."""
if self.registry.get_source(module_name, version).get("type", None) == "git_repository":
return
source_url = self.registry.get_source(module_name, version)["url"]
expected_integrity = self.registry.get_source(module_name, version)["integrity"]
algorithm, _ = expected_integrity.split("-", 1)
real_integrity = integrity(download(source_url), algorithm)
if real_integrity != expected_integrity:
self.report(
BcrValidationResult.FAILED,
f"{module_name}@{version}'s source archive `{source_url}` has expected integrity value "
f"`{expected_integrity}`, but the real integrity value is `{real_integrity}`!",
)
else:
self.report(BcrValidationResult.GOOD, "The source archive's integrity value matches.")
def verify_git_repo_source_stability(self, module_name, version):
"""Verify git repositories are specified in a stable way."""
if self.registry.get_source(module_name, version).get("type", None) != "git_repository":
return
# There's a handful of failure modes here, don't fail fast.
error_encountered = False
if self.registry.get_source(module_name, version).get("branch", None):
self.report(
BcrValidationResult.FAILED,
f"{module_name}@{version}'s source is a git_repository that is trying to track "
"a branch. Please use a specific commit instead, as branches are not stable sources.",
)
error_encountered = True
if self.registry.get_source(module_name, version).get("tag", None):
self.report(
BcrValidationResult.FAILED,
f"{module_name}@{version}'s source is a git_repository that is trying to track "
"a tag. Please use a specific commit instead, as tags are not stable sources.",
)
error_encountered = True
commit = self.registry.get_source(module_name, version)["commit"]
try:
commit_hash_bytes = bytes.fromhex(commit)
if len(commit_hash_bytes) != 20:
self.report(
BcrValidationResult.FAILED,
f"{module_name}@{version}'s git_repository commit hash is an unexpected length.",
)
except ValueError:
self.report(
BcrValidationResult.FAILED,
f"{module_name}@{version}'s source is a git_repository with an invalid commit hash format.",
)
error_encountered = True
if not error_encountered:
self.report(BcrValidationResult.GOOD, "The git_repository appears stable.")
def verify_presubmit_yml_change(self, module_name, version):
"""Verify if the presubmit.yml is the same as the previous version."""
versions = self.registry.get_metadata(module_name)["versions"]
versions.sort(key=Version)
index = versions.index(version)
if index == 0:
self.report(
BcrValidationResult.NEED_BCR_MAINTAINER_REVIEW,
f"Module version {module_name}@{version} is new, the presubmit.yml file "
"should be reviewed by a BCR maintainer.",
)
elif index > 0:
pre_version = versions[index - 1]
previous_presubmit_yml = self.registry.get_presubmit_yml_path(module_name, pre_version)
previous_presubmit_content = open(previous_presubmit_yml, "r").readlines()
current_presubmit_yml = self.registry.get_presubmit_yml_path(module_name, version)
current_presubmit_content = open(current_presubmit_yml, "r").readlines()
diff = list(
unified_diff(
previous_presubmit_content,
current_presubmit_content,
fromfile=str(previous_presubmit_yml),
tofile=str(current_presubmit_yml),
)
)
if diff:
self.report(
BcrValidationResult.NEED_BCR_MAINTAINER_REVIEW,
f"The presubmit.yml file of {module_name}@{version} doesn't match its previous version "
f"{module_name}@{pre_version}, the following presubmit.yml file change "
"should be reviewed by a BCR maintainer.\n " + " ".join(diff),
)
else:
self.report(BcrValidationResult.GOOD, "The presubmit.yml file matches the previous version.")
def add_module_dot_bazel_patch(self, diff, module_name, version):
"""Adding a patch file for MODULE.bazel according to the diff result."""
source = self.registry.get_source(module_name, version)
patch_file = self.registry.get_patch_file_path(module_name, version, "module_dot_bazel.patch")
patch_file.parent.mkdir(parents=True, exist_ok=True)
open(patch_file, "w").writelines(diff)
source["patch_strip"] = int(source.get("patch_strip", 0))
patches = source.get("patches", {})
patches["module_dot_bazel.patch"] = integrity(read(patch_file))
source["patches"] = patches
source_json_content = json.dumps(source, indent=4) + "\n"
self.registry.get_source_json_path(module_name, version).write_text(source_json_content)
def _download_source_archive(self, source, output_dir):
source_url = source["url"]
tmp_dir = Path(tempfile.mkdtemp())
archive_file = tmp_dir.joinpath(source_url.split("/")[-1].split("?")[0])
download_file(source_url, archive_file)
shutil.unpack_archive(str(archive_file), output_dir)
def _download_git_repo(self, source, output_dir):
run_git("clone", "--depth=1", source["remote"], output_dir)
run_git("-C", output_dir, "fetch", "--depth=1", "origin", source["commit"])
run_git("-C", output_dir, "checkout", source["commit"])
def verify_module_dot_bazel(self, module_name, version):
source = self.registry.get_source(module_name, version)
tmp_dir = Path(tempfile.mkdtemp())
output_dir = tmp_dir.joinpath("source_root")
source_type = source.get("type", "archive")
if source_type == "archive":
self._download_source_archive(source, output_dir)
elif source_type == "git_repository":
self._download_git_repo(source, output_dir)
else:
raise BcrValidationException("Unsupported repository type")
module_file = self.registry.get_module_dot_bazel_path(module_name, version)
if module_file.is_symlink():
self.report(BcrValidationResult.FAILED, f"{module_file} must not be a symlink.")
# Apply patch files if there are any, also verify their integrity values
source_root = output_dir.joinpath(source["strip_prefix"] if "strip_prefix" in source else "")
if "patches" in source:
for patch_name, expected_integrity in source["patches"].items():
patch_file = self.registry.get_patch_file_path(module_name, version, patch_name)
actual_integrity = integrity(read(patch_file))
if actual_integrity != expected_integrity:
self.report(
BcrValidationResult.FAILED,
f"The patch file `{patch_file}` has expected integrity value `{expected_integrity}`, "
f"but the real integrity value is `{actual_integrity}`.",
)
apply_patch(source_root, source["patch_strip"], str(patch_file.resolve()))
if "overlay" in source:
overlay_dir = self.registry.get_overlay_dir(module_name, version)
module_file = overlay_dir / "MODULE.bazel"
if module_file.exists() and (not module_file.is_symlink() or os.readlink(module_file) != "../MODULE.bazel"):
self.report(BcrValidationResult.FAILED, f"{module_file} should be a symlink to `../MODULE.bazel`.")
for overlay_file, expected_integrity in source["overlay"].items():
overlay_src = overlay_dir / overlay_file
overlay_dst = source_root / overlay_file
try:
overlay_dst.resolve().relative_to(source_root.resolve())
except ValueError as e:
self.report(
BcrValidationResult.FAILED,
f"The overlay file path `{overlay_file}` must point inside the source archive.\n {e}",
)
continue
try:
actual_integrity = integrity(read(overlay_src))
except FileNotFoundError:
self.report(BcrValidationResult.FAILED, f"The overlay file `{overlay_file}` does not exist")
continue
if actual_integrity != expected_integrity:
self.report(
BcrValidationResult.FAILED,
f"The overlay file `{overlay_file}` has expected integrity value `{expected_integrity}`, "
f"but the real integrity value is `{actual_integrity}`.",
)
continue
overlay_dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(overlay_src, overlay_dst)
source_module_dot_bazel = source_root.joinpath("MODULE.bazel")
if source_module_dot_bazel.exists():
source_module_dot_bazel_content = open(source_module_dot_bazel, "r").readlines()
else:
source_module_dot_bazel_content = []
bcr_module_dot_bazel_content = open(
self.registry.get_module_dot_bazel_path(module_name, version), "r"
).readlines()
source_module_dot_bazel_content = fix_line_endings(source_module_dot_bazel_content)
bcr_module_dot_bazel_content = fix_line_endings(bcr_module_dot_bazel_content)
file_name = "a/" * int(source.get("patch_strip", 0)) + "MODULE.bazel"
diff = list(
unified_diff(
source_module_dot_bazel_content, bcr_module_dot_bazel_content, fromfile=file_name, tofile=file_name
)
)
if diff:
self.report(
BcrValidationResult.FAILED,
"Checked in MODULE.bazel file doesn't match the one in the extracted and patched sources.\n"
+ f"Please fix the MODULE.bazel file or you can add the following patch to {module_name}@{version}:\n"
+ " "
+ " ".join(diff),
)
if self.should_fix:
self.add_module_dot_bazel_patch(diff, module_name, version)
else:
self.report(BcrValidationResult.GOOD, "Checked in MODULE.bazel matches the sources.")
tree = ast.parse("".join(bcr_module_dot_bazel_content), filename=source_root)
for node in tree.body:
if (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Call)
and isinstance(node.value.func, ast.Name)
and node.value.func.id == "module"
):
keywords = {k.arg: k.value.value for k in node.value.keywords if isinstance(k.value, ast.Constant)}
if keywords.get("version", version) != version:
self.report(
BcrValidationResult.FAILED,
"Checked in MODULE.bazel version does not match the version of the module directory added.",
)
shutil.rmtree(tmp_dir)
def check_if_bazel_version_is_set(self, tasks):
for task_name, task_config in tasks.items():
if "bazel" not in task_config:
self.report(
BcrValidationResult.FAILED,
"Missing bazel version for task '%s' in the presubmit.yml file." % task_name,
)
def validate_presubmit_yml(self, module_name, version):
presubmit_yml = self.registry.get_presubmit_yml_path(module_name, version)
presubmit = yaml.safe_load(open(presubmit_yml, "r"))
report_num_old = len(self.validation_results)
tasks = presubmit.get("tasks", {})
self.check_if_bazel_version_is_set(tasks)
test_module_tasks = {}
if "bcr_test_module" in presubmit:
test_module_tasks = presubmit["bcr_test_module"].get("tasks", {})
self.check_if_bazel_version_is_set(test_module_tasks)
if not tasks and not test_module_tasks:
self.report(BcrValidationResult.FAILED, "At least one task should be specified in the presubmit.yml file.")
report_num_new = len(self.validation_results)
if report_num_new == report_num_old:
self.report(BcrValidationResult.GOOD, "The presubmit.yml file is valid.")
def verify_module_name_conflict(self):
"""Verify no module name conflict when ignoring case sensitivity."""
module_names = self.registry.get_all_modules()
conflict_found = False
module_group = {}
for name in module_names:
module_group.setdefault(name.lower(), []).append(name)
for name, modules in module_group.items():
if len(modules) > 1:
conflict_found = True
self.report(BcrValidationResult.FAILED, f"Module name conflict found: {', '.join(modules)}")
if not conflict_found:
self.report(BcrValidationResult.GOOD, "No module name conflict found.")
def validate_module(self, module_name, version, skipped_validations):
print_expanded_group(f"Validating {module_name}@{version}")
self.verify_module_name_conflict()
self.verify_module_existence(module_name, version)
self.verify_git_repo_source_stability(module_name, version)
if "source_repo" not in skipped_validations:
self.verify_source_archive_url_match_github_repo(module_name, version)
if "url_stability" not in skipped_validations:
self.verify_source_archive_url_stability(module_name, version)
self.verify_source_archive_url_integrity(module_name, version)
if "presubmit_yml" not in skipped_validations:
self.verify_presubmit_yml_change(module_name, version)
self.validate_presubmit_yml(module_name, version)
self.verify_module_dot_bazel(module_name, version)
def validate_all_metadata(self):
print_expanded_group("Validating all metadata.json files")
has_error = False
for module_name in self.registry.get_all_modules():
try:
metadata = self.registry.get_metadata(module_name)
except json.JSONDecodeError as e:
self.report(BcrValidationResult.FAILED, f"Failed to load {module_name}'s metadata.json file: " + str(e))
has_error = True
continue
sorted_versions = sorted(metadata["versions"], key=Version)
if sorted_versions != metadata["versions"]:
self.report(
BcrValidationResult.FAILED,
f"{module_name}'s metadata.json file is not sorted by version.\n "
f"Sorted versions: {sorted_versions}.\n "
f"Original versions: {metadata['versions']}",
)
has_error = True
for version in metadata["versions"]:
if not self.registry.contains(module_name, version):
self.report(
BcrValidationResult.FAILED,
f"{module_name}@{version} doesn't exist, "
f"but it's recorded in {module_name}'s metadata.json file.",
)
has_error = True
if not has_error:
self.report(BcrValidationResult.GOOD, "All metadata.json files are valid.")
def getValidationReturnCode(self):
# Calculate the overall return code
# 0: All good
# 1: BCR validation failed
# 42: BCR validation passes, but some changes need BCR maintainer review before trigging follow up BCR presubmit jobs.
result_codes = [code for code, _ in self.validation_results]
if BcrValidationResult.FAILED in result_codes:
return 1
if BcrValidationResult.NEED_BCR_MAINTAINER_REVIEW in result_codes:
# Use a special return code to avoid conflict with other error code
return 42
return 0
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument(
"--registry",
type=str,
default=".",
help="Specify the root path of the registry (default: the current working directory).",
)
parser.add_argument(
"--check",
type=str,
action="append",
help="Specify a Bazel module version you want to perform the BCR check on."
+ " (e.g. [email protected]). If no version is specified, all versions of that module are checked."
+ " This flag can be repeated to accept multiple module versions.",
)
parser.add_argument(
"--check_all", action="store_true", help="Check all Bazel modules in the registry, ignore other --check flags."
)
parser.add_argument(
"--check_all_metadata", action="store_true", help="Check all Bazel module metadata in the registry."
)
parser.add_argument(
"--fix", action="store_true", help="Should the script try to fix the detected validation errors."
)
parser.add_argument(
"--skip_validation",
type=str,
default=[],
action="append",
help='Bypass the given step for validating modules. Supported values are: "url_stability", '
+ 'to bypass the URL stability check; "presubmit_yml", to bypass the presubmit.yml check; '
+ '"source_repo", to bypass the source repo verification; '
+ "This flag can be repeated to skip multiple validations.",
)
args = parser.parse_args(argv)
if not args.check_all and not args.check and not args.check_all_metadata:
parser.print_help()
return -1
registry = RegistryClient(args.registry)
# Parse what module versions we should validate
module_versions = parse_module_versions(registry, args.check_all, args.check)
if module_versions:
print_expanded_group("Module versions to be validated:")
for name, version in module_versions:
print(f"{name}@{version}")
# Validate given module version.
validator = BcrValidator(registry, args.fix)
for name, version in module_versions:
validator.validate_module(name, version, args.skip_validation)
if args.check_all_metadata:
validator.validate_all_metadata()
return validator.getValidationReturnCode()
if __name__ == "__main__":
# Under 'bazel run' we want to run within the source folder instead of the execroot.
if os.getenv("BUILD_WORKSPACE_DIRECTORY"):
os.chdir(os.getenv("BUILD_WORKSPACE_DIRECTORY"))
sys.exit(main())