Skip to content

Commit c0a398c

Browse files
authored
Clean up (#178)
1 parent 99db71f commit c0a398c

15 files changed

+360
-361
lines changed

cm_library_c_binding/build.py

+20-20
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ def gather_sources_from_directory(directory: str) -> list[Source]:
2626
"""
2727
sources = []
2828
for filename in os.listdir(directory):
29-
if filename.endswith('.h'):
30-
include_line = f'#include <{filename}>'
29+
if filename.endswith(".h"):
30+
include_line = f"#include <{filename}>"
3131
sources.append(Source(filename, include_line))
3232
return sorted(sources)
3333

@@ -43,7 +43,7 @@ def mk_ffi(
4343
directory: str,
4444
sources: list[Source],
4545
static_lib: bool = False, # noqa: FBT001, FBT002
46-
name: str = '_libsecp256k1',
46+
name: str = "_libsecp256k1",
4747
) -> FFI:
4848
"""
4949
Create an FFI object.
@@ -56,45 +56,45 @@ def mk_ffi(
5656
_ffi = FFI()
5757
code = [define_static_lib] if static_lib else []
5858

59-
logging.info(' Static %s...', static_lib)
59+
logging.info(" Static %s...", static_lib)
6060
for source in sources:
61-
with open(os.path.join(directory, source.h), encoding='utf-8') as h:
62-
logging.info(' Including %s...', source.h)
61+
with open(os.path.join(directory, source.h), encoding="utf-8") as h:
62+
logging.info(" Including %s...", source.h)
6363
c_header = h.read()
6464
_ffi.cdef(c_header)
6565

6666
code.append(source.include)
6767

68-
code.append('#define PY_USE_BUNDLED')
69-
_ffi.set_source(name, '\n'.join(code))
68+
code.append("#define PY_USE_BUNDLED")
69+
_ffi.set_source(name, "\n".join(code))
7070

7171
return _ffi
7272

7373

74-
if __name__ == '__main__':
75-
logging.info('Starting CFFI build process...')
76-
parser = argparse.ArgumentParser(description='Generate C code using CFFI.')
77-
parser.add_argument('headers_dir', help='Path to the header files.', type=str)
78-
parser.add_argument('c_file', help='Generated C code filename.', type=str)
79-
parser.add_argument('static_lib', help='Generate static lib in Windows.', default='0N', type=str)
74+
if __name__ == "__main__":
75+
logging.info("Starting CFFI build process...")
76+
parser = argparse.ArgumentParser(description="Generate C code using CFFI.")
77+
parser.add_argument("headers_dir", help="Path to the header files.", type=str)
78+
parser.add_argument("c_file", help="Generated C code filename.", type=str)
79+
parser.add_argument("static_lib", help="Generate static lib in Windows.", default="0N", type=str)
8080
args = parser.parse_args()
8181

8282
modules = gather_sources_from_directory(args.headers_dir)
83-
ffi = mk_ffi(args.headers_dir, modules, args.static_lib == 'ON')
83+
ffi = mk_ffi(args.headers_dir, modules, args.static_lib == "ON")
8484
ffi.emit_c_code(args.c_file)
8585

86-
vendor_cffi = os.environ.get('COINCURVE_VENDOR_CFFI', '1') == '1'
86+
vendor_cffi = os.environ.get("COINCURVE_VENDOR_CFFI", "1") == "1"
8787
if vendor_cffi:
88-
with open(args.c_file, encoding='utf-8') as f:
88+
with open(args.c_file, encoding="utf-8") as f:
8989
source = f.read()
9090

9191
expected_text = 'PyImport_ImportModule("_cffi_backend")'
9292
if expected_text not in source:
93-
msg = f'{expected_text} not found in {args.c_file}'
93+
msg = f"{expected_text} not found in {args.c_file}"
9494
raise ValueError(msg)
9595

9696
new_source = source.replace(expected_text, 'PyImport_ImportModule("coincurve._cffi_backend")')
97-
with open(args.c_file, 'w', encoding='utf-8') as f:
97+
with open(args.c_file, "w", encoding="utf-8") as f:
9898
f.write(new_source)
9999

100-
logging.info(' Generated C code: %s', args.c_file)
100+
logging.info(" Generated C code: %s", args.c_file)

cm_library_cffi_headers/compose_cffi_headers.py

+55-55
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,21 @@
88

99

1010
def remove_c_comments_emptylines(text):
11-
text = re.sub(r'/\*.*?\*/', '', text, flags=re.DOTALL) # Remove multi-line comments
12-
text = re.sub(r'//.*', '', text) # Remove single-line comments
13-
return re.sub(r'\n\s*\n+', '\n', text) # Remove empty lines
11+
text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL) # Remove multi-line comments
12+
text = re.sub(r"//.*", "", text) # Remove single-line comments
13+
return re.sub(r"\n\s*\n+", "\n", text) # Remove empty lines
1414

1515

1616
def remove_c_includes(lines):
17-
return [line for line in lines if not re.match(r'^\s*#include\s', line)]
17+
return [line for line in lines if not re.match(r"^\s*#include\s", line)]
1818

1919

2020
def remove_special_defines(lines, defines):
21-
return [line for line in lines if not any(f'#define {define}' in line for define in defines)]
21+
return [line for line in lines if not any(f"#define {define}" in line for define in defines)]
2222

2323

2424
def apply_cffi_defines_syntax(lines):
25-
return [re.sub(r'#\s*define\s+(\w+).*', r'#define \1 ...', line) for line in lines]
25+
return [re.sub(r"#\s*define\s+(\w+).*", r"#define \1 ...", line) for line in lines]
2626

2727

2828
def remove_c_ifdef(lines):
@@ -34,15 +34,15 @@ def remove_c_ifdef(lines):
3434
for line in lines:
3535
stripped_line = line.rstrip()
3636

37-
if re.match(r'^#\s*(if|el|endif)', stripped_line):
38-
stripped_line = stripped_line.replace(' ', '')
39-
ifdef_count += stripped_line.count('#if') - stripped_line.count('#endif')
37+
if re.match(r"^#\s*(if|el|endif)", stripped_line):
38+
stripped_line = stripped_line.replace(" ", "")
39+
ifdef_count += stripped_line.count("#if") - stripped_line.count("#endif")
4040
continue
4141

4242
if ifdef_count == 0:
4343
processed_lines.append(stripped_line)
4444
elif ifdef_count < 0 and line != lines[-1]:
45-
msg = 'Unbalanced #if/#endif preprocessor directives.'
45+
msg = "Unbalanced #if/#endif preprocessor directives."
4646
raise ValueError(msg)
4747

4848
return processed_lines
@@ -56,16 +56,16 @@ def concatenate_c_defines(lines):
5656
for line in lines:
5757
stripped_line = line.rstrip()
5858

59-
if (re.match(r'#\s*define', stripped_line) or in_define) and stripped_line.endswith('\\'):
59+
if (re.match(r"#\s*define", stripped_line) or in_define) and stripped_line.endswith("\\"):
6060
in_define = True
6161
buffer.append(
62-
re.sub(r'#\s*define', '#define', stripped_line).rstrip('\\').strip()
62+
re.sub(r"#\s*define", "#define", stripped_line).rstrip("\\").strip()
6363
) # Normalize #define and remove trailing backslash
6464
continue # Skip the rest of the loop to avoid resetting the buffer
6565

6666
if in_define:
6767
buffer.append(stripped_line)
68-
processed_lines.append(' '.join(buffer))
68+
processed_lines.append(" ".join(buffer))
6969
buffer = [] # Reset the buffer for the next definition
7070
in_define = False
7171
continue # Skip the rest of the loop to avoid adding the line again
@@ -85,25 +85,25 @@ def remove_deprecated_functions(lines, deprecation):
8585
for line in lines:
8686
stripped_line = line.rstrip()
8787

88-
if re.match(r'#\s*define', stripped_line) or in_define:
89-
in_define = bool(stripped_line.endswith('\\'))
88+
if re.match(r"#\s*define", stripped_line) or in_define:
89+
in_define = bool(stripped_line.endswith("\\"))
9090
processed_lines.append(stripped_line)
9191
continue
9292

93-
if stripped_line.startswith('struct') or re.match(r'typedef\s+struct', stripped_line) or in_struct:
93+
if stripped_line.startswith("struct") or re.match(r"typedef\s+struct", stripped_line) or in_struct:
9494
in_struct = True
9595
processed_lines.append(stripped_line)
96-
brace_count += stripped_line.count('{') - stripped_line.count('}')
96+
brace_count += stripped_line.count("{") - stripped_line.count("}")
9797
if brace_count == 0: # End of struct block
9898
in_struct = False
9999
continue
100100

101101
buffer.append(stripped_line)
102102

103103
# Check for the end of a function declaration
104-
if stripped_line.endswith(';') and not in_struct:
104+
if stripped_line.endswith(";") and not in_struct:
105105
# Extend if not DEPRECATED
106-
if not any(d in ' '.join(buffer) for d in deprecation):
106+
if not any(d in " ".join(buffer) for d in deprecation):
107107
processed_lines.extend(buffer)
108108
buffer = [] # Reset the buffer for the next definition
109109

@@ -119,14 +119,14 @@ def remove_function_attributes(lines, attributes):
119119
for attribute, replacement in attributes.items():
120120
# Attributes can be functions with (...), so using regular expression
121121
# Remove the definition
122-
if re.search(rf'#\s*define\s+{attribute}(\(.*\))?\b', stripped_line):
122+
if re.search(rf"#\s*define\s+{attribute}(\(.*\))?\b", stripped_line):
123123
stripped_line = None
124124
break
125125

126-
if re.search(rf'\b{attribute}(\(.*\))?\b', stripped_line):
127-
stripped_line = re.sub(rf'\b{attribute}(\(.*\))?', f'{replacement}', stripped_line)
128-
stripped_line = stripped_line.replace(' ;', ';')
129-
stripped_line = stripped_line.replace(' ', ' ')
126+
if re.search(rf"\b{attribute}(\(.*\))?\b", stripped_line):
127+
stripped_line = re.sub(rf"\b{attribute}(\(.*\))?", f"{replacement}", stripped_line)
128+
stripped_line = stripped_line.replace(" ;", ";")
129+
stripped_line = stripped_line.replace(" ", " ")
130130

131131
if stripped_line:
132132
processed_lines.append(stripped_line)
@@ -141,7 +141,7 @@ def remove_header_guard(lines, keywords):
141141
stripped_line = line.rstrip()
142142

143143
for keyword in keywords:
144-
if re.search(rf'#\s*define\s+{keyword}.*_H\b', stripped_line):
144+
if re.search(rf"#\s*define\s+{keyword}.*_H\b", stripped_line):
145145
continue
146146
processed_lines.append(stripped_line)
147147

@@ -157,12 +157,12 @@ def concatenate_c_struct(lines):
157157
for line in lines:
158158
stripped_line = line.strip()
159159

160-
if stripped_line.startswith('struct') or re.match(r'typedef\s+struct', stripped_line) or in_struct:
160+
if stripped_line.startswith("struct") or re.match(r"typedef\s+struct", stripped_line) or in_struct:
161161
in_struct = True
162-
brace_count += stripped_line.count('{') - stripped_line.count('}')
162+
brace_count += stripped_line.count("{") - stripped_line.count("}")
163163
buffer.append(stripped_line)
164164
if brace_count == 0: # End of struct block
165-
processed_lines.append(' '.join(buffer).strip())
165+
processed_lines.append(" ".join(buffer).strip())
166166
buffer = [] # Reset the buffer for the next definition
167167
in_struct = False
168168
continue # Skip the rest of the loop to avoid adding the line again
@@ -173,72 +173,72 @@ def concatenate_c_struct(lines):
173173

174174

175175
def make_header_cffi_compliant(src_header_dir, src_header, cffi_dir):
176-
with open(os.path.join(src_header_dir, src_header), encoding='utf-8') as f:
176+
with open(os.path.join(src_header_dir, src_header), encoding="utf-8") as f:
177177
text = remove_c_comments_emptylines(f.read())
178-
lines = text.split('\n')
178+
lines = text.split("\n")
179179

180180
lines = remove_c_includes(lines)
181181
lines = remove_c_ifdef(lines)
182182
lines = concatenate_c_defines(lines)
183-
lines = remove_deprecated_functions(lines, ['DEPRECATED'])
184-
lines = remove_header_guard(lines, ['SECP256K1'])
183+
lines = remove_deprecated_functions(lines, ["DEPRECATED"])
184+
lines = remove_header_guard(lines, ["SECP256K1"])
185185
lines = remove_function_attributes(
186186
lines,
187187
{
188-
'SECP256K1_API': 'extern',
189-
'SECP256K1_WARN_UNUSED_RESULT': '',
190-
'SECP256K1_DEPRECATED': '',
191-
'SECP256K1_ARG_NONNULL': '',
188+
"SECP256K1_API": "extern",
189+
"SECP256K1_WARN_UNUSED_RESULT": "",
190+
"SECP256K1_DEPRECATED": "",
191+
"SECP256K1_ARG_NONNULL": "",
192192
},
193193
)
194194
lines = remove_special_defines(
195195
lines,
196196
[
197197
# Deprecated flags
198-
'SECP256K1_CONTEXT_VERIFY',
199-
'SECP256K1_CONTEXT_SIGN',
200-
'SECP256K1_FLAGS_BIT_CONTEXT_VERIFY',
201-
'SECP256K1_FLAGS_BIT_CONTEXT_SIGN',
198+
"SECP256K1_CONTEXT_VERIFY",
199+
"SECP256K1_CONTEXT_SIGN",
200+
"SECP256K1_FLAGS_BIT_CONTEXT_VERIFY",
201+
"SECP256K1_FLAGS_BIT_CONTEXT_SIGN",
202202
# Testing flags
203-
'SECP256K1_CONTEXT_DECLASSIFY',
204-
'SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY',
203+
"SECP256K1_CONTEXT_DECLASSIFY",
204+
"SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY",
205205
# Not for direct use - That may not mean to remove them!
206206
# 'SECP256K1_FLAGS_TYPE_MASK',
207207
# 'SECP256K1_FLAGS_TYPE_CONTEXT',
208208
# 'SECP256K1_FLAGS_TYPE_COMPRESSION',
209209
# 'SECP256K1_FLAGS_BIT_COMPRESSION',
210210
# Not supported
211-
'SECP256K1_SCHNORRSIG_EXTRAPARAMS_MAGIC',
212-
'SECP256K1_SCHNORRSIG_EXTRAPARAMS',
211+
"SECP256K1_SCHNORRSIG_EXTRAPARAMS_MAGIC",
212+
"SECP256K1_SCHNORRSIG_EXTRAPARAMS",
213213
],
214214
)
215215
lines = apply_cffi_defines_syntax(lines)
216216

217-
logging.info(' Writting: %s in %s', src_header, cffi_dir)
217+
logging.info(" Writting: %s in %s", src_header, cffi_dir)
218218
output_filename = os.path.join(cffi_dir, src_header)
219-
with open(output_filename, 'w', encoding='utf-8') as f_out:
220-
f_out.write('\n'.join(lines))
219+
with open(output_filename, "w", encoding="utf-8") as f_out:
220+
f_out.write("\n".join(lines))
221221

222222

223-
if __name__ == '__main__':
224-
parser = argparse.ArgumentParser(description='Process a header file.')
225-
parser.add_argument('src_header_dir', type=str, help='The path to the header file to be processed.')
226-
parser.add_argument('cffi_header', type=str, help='The path where the compliant header will be written.')
227-
parser.add_argument('cffi_dir', type=str, help='The path where the compliant header will be written.', default='.')
223+
if __name__ == "__main__":
224+
parser = argparse.ArgumentParser(description="Process a header file.")
225+
parser.add_argument("src_header_dir", type=str, help="The path to the header file to be processed.")
226+
parser.add_argument("cffi_header", type=str, help="The path where the compliant header will be written.")
227+
parser.add_argument("cffi_dir", type=str, help="The path where the compliant header will be written.", default=".")
228228

229229
args = parser.parse_args()
230230

231231
# Verify args are valid
232232
if not os.path.isdir(args.src_header_dir):
233-
logging.error('Error: Directory: %s not found.', args.src_header_dir)
233+
logging.error("Error: Directory: %s not found.", args.src_header_dir)
234234
sys.exit(1)
235235

236236
if not os.path.isdir(args.cffi_dir):
237-
logging.error('Error: Directory: %s not found.', args.cffi_dir)
237+
logging.error("Error: Directory: %s not found.", args.cffi_dir)
238238
sys.exit(1)
239239

240240
if not os.path.isfile(os.path.join(args.src_header_dir, args.cffi_header)):
241-
logging.error('Error: %s not found in %s.', args.cffi_header, args.src_header_dir)
241+
logging.error("Error: %s not found in %s.", args.cffi_header, args.src_header_dir)
242242
sys.exit(1)
243243

244244
make_header_cffi_compliant(args.src_header_dir, args.cffi_header, args.cffi_dir)

hatch_build.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,21 @@ class CustomBuildHook(BuildHookInterface):
1616
the `cffi` package is not required as a runtime dependency.
1717
"""
1818

19-
LICENSE_NAME = 'LICENSE-cffi'
19+
LICENSE_NAME = "LICENSE-cffi"
2020

2121
@cached_property
2222
def local_cffi_license(self) -> str:
2323
return os.path.join(self.root, self.LICENSE_NAME)
2424

2525
def initialize(self, version: str, build_data: dict[str, Any]) -> None: # noqa: ARG002
2626
cffi_shared_lib = _cffi_backend.__file__
27-
relative_path = f'coincurve/{os.path.basename(cffi_shared_lib)}'
28-
build_data['force_include'][cffi_shared_lib] = relative_path
27+
relative_path = f"coincurve/{os.path.basename(cffi_shared_lib)}"
28+
build_data["force_include"][cffi_shared_lib] = relative_path
2929

30-
dist = distribution('cffi')
31-
license_files = [f for f in dist.files if f.name == 'LICENSE' and f.parent.name.endswith('.dist-info')]
30+
dist = distribution("cffi")
31+
license_files = [f for f in dist.files if f.name == "LICENSE" and f.parent.name.endswith(".dist-info")]
3232
if len(license_files) != 1:
33-
message = f'Expected exactly one LICENSE file in cffi distribution, got {len(license_files)}'
33+
message = f"Expected exactly one LICENSE file in cffi distribution, got {len(license_files)}"
3434
raise RuntimeError(message)
3535

3636
license_file = license_files[0]

ruff.toml

-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ extend = "ruff_defaults.toml"
22

33
[format]
44
preview = true
5-
quote-style = "single"
65

76
[lint]
87
preview = true

src/coincurve/__about__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = '20.0.0'
1+
__version__ = "20.0.0"

src/coincurve/__init__.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
from coincurve.utils import verify_signature
44

55
__all__ = [
6-
'GLOBAL_CONTEXT',
7-
'Context',
8-
'PrivateKey',
9-
'PublicKey',
10-
'PublicKeyXOnly',
11-
'verify_signature',
6+
"GLOBAL_CONTEXT",
7+
"Context",
8+
"PrivateKey",
9+
"PublicKey",
10+
"PublicKeyXOnly",
11+
"verify_signature",
1212
]

0 commit comments

Comments
 (0)