Debian Codegraph @

crt/aws-c-s3/scripts/update_s3_endpoint_resolver_artifacts.py

raw symbols SCIP
1 # This script pulls latest 'partitions.json' and 's3-endpoint-rule-set.json' from Git.
2 # You will need a secret in secrets manager which has the 'ruleset-url' and 'ruleset-token'.
3 # It uses the latest files to generate 'source/s3_endpoint_resolver/aws_s3_endpoint_rule_set.c' and
4 # 'source/s3_endpoint_resolver/aws_s3_endpoint_resolver_partition.c'
5
6 import argparse
7 import json
8 import requests
9
10
11 def escape_char(c):
12 escape_dict = {
13 '\\': '\\\\',
14 '\'': '\\\'',
15 '\0': '\\0',
16 '\a': '\\a',
17 '\b': '\\b',
18 '\f': '\\f',
19 '\n': '\\n',
20 '\r': '\\r',
21 '\t': '\\t',
22 '\v': '\\v'
23 }
24
25 return escape_dict.get(c, c)
26
27
28 def get_header():
29 return """\
30 /**
31 * Copyright Amazon.com, Inc. or its affiliates.
32 * All Rights Reserved. SPDX-License-Identifier: Apache-2.0.
33 */
34 #include "aws/s3/private/s3_endpoint_resolver.h"
35 #include <aws/s3/s3_endpoint_resolver.h>
36
37 /**
38 * This file is generated using scripts/update_s3_endpoint_resolver_artifacts.py.
39 * Do not modify directly. */
40 /* clang-format off */
41
42 """
43
44
45 def generate_c_file_from_json(json_content, c_file_name, c_struct_name):
46 num_chars_per_line = 20
47
48 try:
49 # Compact the json
50 compact_json_str = json.dumps(json_content, separators=(',', ':'))
51 compact_c = []
52 for i in range(0, len(compact_json_str), num_chars_per_line):
53 compact_c.append(
54 ', '.join("'{}'".format(escape_char(char)) for char in compact_json_str[i:i + num_chars_per_line]))
55
56 # Write json to a C file
57 with open(c_file_name, 'w') as f:
58 f.write(get_header())
59 f.write(f"static const char s_generated_array[] = {{\n\t")
60 f.write(",\n\t".join(compact_c))
61 f.write("};\n\n")
62
63 f.write(f"const struct aws_byte_cursor {c_struct_name} = {{\n\t")
64 f.write(f".len = {len(compact_json_str)},\n\t")
65 f.write(f".ptr = (uint8_t *) s_generated_array\n}};\n")
66
67 print(f"{c_file_name} has been created successfully.")
68
69 except Exception as e:
70 print(f"An error occurred: {e}")
71
72
73 def extract_rule_set(s3_model):
74 """
75 Extract the smithy.rules#endpointRuleSet from the s3_model JSON.
76
77 The ruleset is nested at: shapes -> com.amazonaws.s3#AmazonS3 -> traits -> smithy.rules#endpointRuleSet
78
79 Args:
80 s3_model: The full s3-2006-03-01.json model as a dictionary
81
82 Returns:
83 The endpoint ruleset dictionary
84
85 Raises:
86 KeyError: If the expected path doesn't exist in the model
87 """
88 try:
89 # Navigate through the nested structure to find the endpoint ruleset
90 shapes = s3_model.get('shapes', {})
91 amazon_s3_shape = shapes.get('com.amazonaws.s3#AmazonS3', {})
92 traits = amazon_s3_shape.get('traits', {})
93 rule_set = traits.get('smithy.rules#endpointRuleSet', None)
94
95 if rule_set is None:
96 raise KeyError(
97 "smithy.rules#endpointRuleSet not found in s3_model")
98
99 return rule_set
100
101 except KeyError as e:
102 raise KeyError(
103 f"Failed to extract endpoint ruleset from s3_model: {e}")
104
105
106 def download_from_git(url, token=None):
107 headers = {'Accept': 'application/vnd.github+json'}
108 if token is not None:
109 headers['Authorization'] = f"Bearer {token}"
110 http_response = requests.get(url, headers=headers)
111 if http_response.status_code != 200:
112 raise Exception(f"HTTP Status code is {http_response.status_code}")
113
114 return json.loads(http_response.content.decode())
115
116
117 if __name__ == '__main__':
118 argument_parser = argparse.ArgumentParser(
119 description="Endpoint Ruleset Updater")
120 argument_parser.add_argument("--ruleset", metavar="<Path to ruleset>",
121 required=False, help="Path to endpoint ruleset json file")
122 argument_parser.add_argument("--partitions", metavar="<Path to partitions>",
123 required=False, help="Path to partitions json file")
124 parsed_args = argument_parser.parse_args()
125
126 if (parsed_args.ruleset):
127 with open(parsed_args.ruleset) as f:
128 rule_set = json.load(f)
129 else:
130 s3_model = download_from_git(
131 'https://raw.githubusercontent.com/aws/api-models-aws/refs/heads/main/models/s3/service/2006-03-01/s3-2006-03-01.json')
132 rule_set = extract_rule_set(s3_model)
133
134 if (parsed_args.partitions):
135 with open(parsed_args.partitions) as f:
136 partition = json.load(f)
137 else:
138 partition = download_from_git(
139 'https://raw.githubusercontent.com/aws/aws-sdk-cpp/main/tools/code-generation/partitions/partitions.json')
140
141 generate_c_file_from_json(
142 rule_set,
143 'source/s3_endpoint_resolver/aws_s3_endpoint_rule_set.c',
144 'aws_s3_endpoint_rule_set')
145
146 generate_c_file_from_json(
147 partition,
148 'source/s3_endpoint_resolver/aws_s3_endpoint_resolver_partition.c',
149 'aws_s3_endpoint_resolver_partitions')