chore: normalize schematic.py and apply black to create_schematic signature
Bundles two changes for python/commands/schematic.py:
1. CRLF → LF line-ending normalization (matches the bulk renormalize
from the previous commit — was held back here because black would
also need to re-reformat it).
2. Black reflow of create_schematic()'s parameter list, which exceeded
the line length. Pre-existing drift, no logic change.
`git show --ignore-all-space HEAD` shows just the 2-line signature diff.
This commit is contained in:
@@ -1,132 +1,134 @@
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import uuid
|
import uuid
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
|
|
||||||
from skip import Schematic
|
from skip import Schematic
|
||||||
|
|
||||||
logger = logging.getLogger("kicad_interface")
|
logger = logging.getLogger("kicad_interface")
|
||||||
|
|
||||||
|
|
||||||
class SchematicManager:
|
class SchematicManager:
|
||||||
"""Core schematic operations using kicad-skip"""
|
"""Core schematic operations using kicad-skip"""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create_schematic(name: str, metadata: Optional[Any] = None, *, path: Optional[str] = None) -> Any:
|
def create_schematic(
|
||||||
"""Create a new empty schematic from template"""
|
name: str, metadata: Optional[Any] = None, *, path: Optional[str] = None
|
||||||
try:
|
) -> Any:
|
||||||
# Determine template path (use template_with_symbols for component cloning support)
|
"""Create a new empty schematic from template"""
|
||||||
template_path = os.path.join(
|
try:
|
||||||
os.path.dirname(os.path.abspath(__file__)),
|
# Determine template path (use template_with_symbols for component cloning support)
|
||||||
"..",
|
template_path = os.path.join(
|
||||||
"templates",
|
os.path.dirname(os.path.abspath(__file__)),
|
||||||
"template_with_symbols.kicad_sch",
|
"..",
|
||||||
)
|
"templates",
|
||||||
|
"template_with_symbols.kicad_sch",
|
||||||
# Determine output path
|
)
|
||||||
base_name = name if name.endswith(".kicad_sch") else f"{name}.kicad_sch"
|
|
||||||
output_path = os.path.join(path, base_name) if path else base_name
|
# Determine output path
|
||||||
|
base_name = name if name.endswith(".kicad_sch") else f"{name}.kicad_sch"
|
||||||
if os.path.exists(template_path):
|
output_path = os.path.join(path, base_name) if path else base_name
|
||||||
# Copy template to target location
|
|
||||||
shutil.copy(template_path, output_path)
|
if os.path.exists(template_path):
|
||||||
|
# Copy template to target location
|
||||||
# Regenerate UUID to ensure uniqueness for each created schematic
|
shutil.copy(template_path, output_path)
|
||||||
import re
|
|
||||||
|
# Regenerate UUID to ensure uniqueness for each created schematic
|
||||||
with open(output_path, "r", encoding="utf-8") as f:
|
import re
|
||||||
content = f.read()
|
|
||||||
new_uuid = str(uuid.uuid4())
|
with open(output_path, "r", encoding="utf-8") as f:
|
||||||
content = re.sub(
|
content = f.read()
|
||||||
r"\(uuid [0-9a-fA-F-]+\)",
|
new_uuid = str(uuid.uuid4())
|
||||||
f"(uuid {new_uuid})",
|
content = re.sub(
|
||||||
content,
|
r"\(uuid [0-9a-fA-F-]+\)",
|
||||||
count=1, # Only replace first (schematic) UUID
|
f"(uuid {new_uuid})",
|
||||||
)
|
content,
|
||||||
with open(output_path, "w", encoding="utf-8", newline="\n") as f:
|
count=1, # Only replace first (schematic) UUID
|
||||||
f.write(content)
|
)
|
||||||
|
with open(output_path, "w", encoding="utf-8", newline="\n") as f:
|
||||||
logger.info(f"Created schematic from template: {output_path}")
|
f.write(content)
|
||||||
else:
|
|
||||||
# Fallback: create minimal schematic
|
logger.info(f"Created schematic from template: {output_path}")
|
||||||
logger.warning(f"Template not found at {template_path}, creating minimal schematic")
|
else:
|
||||||
# Generate unique UUID for this schematic
|
# Fallback: create minimal schematic
|
||||||
schematic_uuid = str(uuid.uuid4())
|
logger.warning(f"Template not found at {template_path}, creating minimal schematic")
|
||||||
# Write with explicit UTF-8 encoding and Unix line endings for cross-platform compatibility
|
# Generate unique UUID for this schematic
|
||||||
with open(output_path, "w", encoding="utf-8", newline="\n") as f:
|
schematic_uuid = str(uuid.uuid4())
|
||||||
f.write('(kicad_sch (version 20250114) (generator "KiCAD-MCP-Server")\n\n')
|
# Write with explicit UTF-8 encoding and Unix line endings for cross-platform compatibility
|
||||||
f.write(f" (uuid {schematic_uuid})\n\n")
|
with open(output_path, "w", encoding="utf-8", newline="\n") as f:
|
||||||
f.write(' (paper "A4")\n\n')
|
f.write('(kicad_sch (version 20250114) (generator "KiCAD-MCP-Server")\n\n')
|
||||||
f.write(" (lib_symbols\n )\n\n")
|
f.write(f" (uuid {schematic_uuid})\n\n")
|
||||||
f.write(' (sheet_instances\n (path "/" (page "1"))\n )\n')
|
f.write(' (paper "A4")\n\n')
|
||||||
f.write(")\n")
|
f.write(" (lib_symbols\n )\n\n")
|
||||||
|
f.write(' (sheet_instances\n (path "/" (page "1"))\n )\n')
|
||||||
# Load the schematic
|
f.write(")\n")
|
||||||
sch = Schematic(output_path)
|
|
||||||
logger.info(f"Loaded new schematic: {output_path}")
|
# Load the schematic
|
||||||
return sch
|
sch = Schematic(output_path)
|
||||||
|
logger.info(f"Loaded new schematic: {output_path}")
|
||||||
except Exception as e:
|
return sch
|
||||||
logger.error(f"Error creating schematic: {e}")
|
|
||||||
raise
|
except Exception as e:
|
||||||
|
logger.error(f"Error creating schematic: {e}")
|
||||||
@staticmethod
|
raise
|
||||||
def load_schematic(file_path: str) -> Optional[Any]:
|
|
||||||
"""Load an existing schematic"""
|
@staticmethod
|
||||||
if not os.path.exists(file_path):
|
def load_schematic(file_path: str) -> Optional[Any]:
|
||||||
logger.error(f"Schematic file not found at {file_path}")
|
"""Load an existing schematic"""
|
||||||
return None
|
if not os.path.exists(file_path):
|
||||||
try:
|
logger.error(f"Schematic file not found at {file_path}")
|
||||||
sch = Schematic(file_path)
|
return None
|
||||||
logger.info(f"Loaded schematic from: {file_path}")
|
try:
|
||||||
return sch
|
sch = Schematic(file_path)
|
||||||
except Exception as e:
|
logger.info(f"Loaded schematic from: {file_path}")
|
||||||
logger.error(f"Error loading schematic from {file_path}: {e}")
|
return sch
|
||||||
return None
|
except Exception as e:
|
||||||
|
logger.error(f"Error loading schematic from {file_path}: {e}")
|
||||||
@staticmethod
|
return None
|
||||||
def save_schematic(schematic: Any, file_path: str) -> bool:
|
|
||||||
"""Save a schematic to file"""
|
@staticmethod
|
||||||
try:
|
def save_schematic(schematic: Any, file_path: str) -> bool:
|
||||||
# kicad-skip uses write method, not save
|
"""Save a schematic to file"""
|
||||||
schematic.write(file_path)
|
try:
|
||||||
logger.info(f"Saved schematic to: {file_path}")
|
# kicad-skip uses write method, not save
|
||||||
return True
|
schematic.write(file_path)
|
||||||
except Exception as e:
|
logger.info(f"Saved schematic to: {file_path}")
|
||||||
logger.error(f"Error saving schematic to {file_path}: {e}")
|
return True
|
||||||
return False
|
except Exception as e:
|
||||||
|
logger.error(f"Error saving schematic to {file_path}: {e}")
|
||||||
@staticmethod
|
return False
|
||||||
def get_schematic_metadata(schematic: Any) -> dict[str, Any]:
|
|
||||||
"""Extract metadata from schematic"""
|
@staticmethod
|
||||||
# kicad-skip doesn't expose a direct metadata object on Schematic.
|
def get_schematic_metadata(schematic: Any) -> dict[str, Any]:
|
||||||
# We can return basic info like version and generator.
|
"""Extract metadata from schematic"""
|
||||||
metadata = {
|
# kicad-skip doesn't expose a direct metadata object on Schematic.
|
||||||
"version": schematic.version,
|
# We can return basic info like version and generator.
|
||||||
"generator": schematic.generator,
|
metadata = {
|
||||||
# Add other relevant properties if needed
|
"version": schematic.version,
|
||||||
}
|
"generator": schematic.generator,
|
||||||
logger.debug("Extracted schematic metadata")
|
# Add other relevant properties if needed
|
||||||
return metadata
|
}
|
||||||
|
logger.debug("Extracted schematic metadata")
|
||||||
|
return metadata
|
||||||
if __name__ == "__main__":
|
|
||||||
# Example Usage (for testing)
|
|
||||||
# Create a new schematic
|
if __name__ == "__main__":
|
||||||
new_sch = SchematicManager.create_schematic("MyTestSchematic")
|
# Example Usage (for testing)
|
||||||
|
# Create a new schematic
|
||||||
# Save the schematic
|
new_sch = SchematicManager.create_schematic("MyTestSchematic")
|
||||||
test_file = "test_schematic.kicad_sch"
|
|
||||||
SchematicManager.save_schematic(new_sch, test_file)
|
# Save the schematic
|
||||||
|
test_file = "test_schematic.kicad_sch"
|
||||||
# Load the schematic
|
SchematicManager.save_schematic(new_sch, test_file)
|
||||||
loaded_sch = SchematicManager.load_schematic(test_file)
|
|
||||||
if loaded_sch:
|
# Load the schematic
|
||||||
metadata = SchematicManager.get_schematic_metadata(loaded_sch)
|
loaded_sch = SchematicManager.load_schematic(test_file)
|
||||||
print(f"Loaded schematic metadata: {metadata}")
|
if loaded_sch:
|
||||||
|
metadata = SchematicManager.get_schematic_metadata(loaded_sch)
|
||||||
# Clean up test file
|
print(f"Loaded schematic metadata: {metadata}")
|
||||||
if os.path.exists(test_file):
|
|
||||||
os.remove(test_file)
|
# Clean up test file
|
||||||
print(f"Cleaned up {test_file}")
|
if os.path.exists(test_file):
|
||||||
|
os.remove(test_file)
|
||||||
|
print(f"Cleaned up {test_file}")
|
||||||
|
|||||||
Reference in New Issue
Block a user