MCPcopy Create free account
hub / github.com/ElementsProject/lightning / fix_file_includes

Function fix_file_includes

devtools/include-order-fixer.py:297–367  ·  view source on GitHub ↗

Fix include ordering in a file. Returns: bool: True if file was modified, False otherwise

(filepath, file_type)

Source from the content-addressed store, hash-verified

295
296
297def fix_file_includes(filepath, file_type):
298 """
299 Fix include ordering in a file.
300
301 Returns:
302 bool: True if file was modified, False otherwise
303 """
304 try:
305 with open(filepath, "r", encoding="utf-8", errors="replace") as f:
306 content = f.read()
307 except IOError as e:
308 print(f"Error reading {filepath}: {e}", file=sys.stderr)
309 return False
310
311 # Extract includes
312 main_items, trailing_items, include_start, blank_line_index, include_end = extract_includes(
313 content
314 )
315
316 if include_start is None:
317 # No includes to sort
318 return False
319
320 # Sort only the main includes block (preserving comments, blanks, and whitespace-prefixed includes)
321 sorted_main_items = sort_includes(main_items, file_type)
322
323 # De-duplicate includes across main and trailing blocks, preserving the first occurrence
324 seen_includes = set()
325 sorted_main_items = dedupe_include_items(sorted_main_items, seen_includes)
326 trailing_items = dedupe_include_items(trailing_items, seen_includes)
327
328 # Reconstruct file content
329 lines = content.splitlines(keepends=True)
330 before_lines = lines[:include_start] if include_start > 0 else []
331 after_lines = lines[include_end:] if include_end < len(lines) else []
332
333 # Build the include section: main sorted items + trailing items
334 # Note: blank lines are already included in main_items/trailing_items, and
335 # blank_line_index is just a marker, so we don't need to add it separately
336 include_section = "".join(line for _, line in sorted_main_items)
337 if trailing_items:
338 # Add trailing items (blank line separator is already in trailing_items if present)
339 include_section += "".join(line for _, line in trailing_items)
340
341 # Combine: before + include section + after
342 new_content = "".join(before_lines) + include_section + "".join(after_lines)
343
344 # Check if content actually changed
345 if new_content == content:
346 return False
347
348 # Write back atomically using temp file
349 try:
350 with tempfile.NamedTemporaryFile(
351 mode="w",
352 encoding="utf-8",
353 dir=os.path.dirname(filepath),
354 delete=False,

Callers 1

mainFunction · 0.85

Calls 6

extract_includesFunction · 0.85
sort_includesFunction · 0.85
dedupe_include_itemsFunction · 0.85
joinMethod · 0.80
readMethod · 0.45
writeMethod · 0.45

Tested by

no test coverage detected