common/sexpr.py: Whitespaces in footprint description break the footprint after sexpr_build()
Problem
Parsing a .kicad_mod
file contents using sexpr.parse_sexpr()
and converting it back to a footprint again using sexpr.build_sexpr()
breaks the footprint. When trying to reimport it into a KiCad's footprint editor, The following error pops up:
Using the method described below on a footprint that is already registered in a project's footprint library makes it disappear from said library.
Expected behavior
Parsing a footprint using the sexpr
module and then converting it back to a .kicad_mod
file without changing anything should not break the footprint.
How to reproduce
Using KiCad's built-in footprint SOT-89-3.kicad_mod
as an example, the following MWE can be used to read, parse and save a copy of the footprint to a different file:
from common import sexpr
footprintPath = 'D:\\bin\\kicad\\6.0\\share\\kicad\\footprints\\Package_TO_SOT_SMD.pretty\\SOT-89-3.kicad_mod'
outputPath = 'D:\\home\\Desktop\\SOT-89-3-parsed-build.kicad_mod'
# Open footprint file and read its contents
with open(footprintPath, 'r') as file:
rawFrootprint = file.read()
# Parse sexpr data
fpData = sexpr.parse_sexp(rawFrootprint)
# Build parsed data back to sexpr and write back to disc
with open(outputPath, 'w') as outfile:
outfile.write(sexpr.format_sexp(sexpr.build_sexp(fpData)))
The newly created footprint file SOT-89-3-parsed-build.kicad_mod
cannot be imported into KiCad.
Workaround
The issue seems to be related to whitespaces in the description of the used footprint. Before parsing and building the footprint with the sexpr
module, the description in the footprint file contains a string with whitespaces that is also enclosed in double-quotes. After parsing and building these double-quotes are gone.
I currently implemented the following workaround into common/sexpr.py
that adds double-quotes to a string-type object when building the sexpr string, but only if the string contains whitespaces:
def build_sexp(exp, key=None):
(...)
elif type(exp) == str:
# Use double-quotes when whitespaces are found in string
if exp.find(" ") != -1:
out += f"\"{exp}\""
else:
out += exp
(...)
If this workaround presents an acceptable solution to the issue, i will happily provide a merge request.
Misc
System: Windows 11 Pro, 10.0.22000 Build 22000
KiCad: KiCad (64-bit)
Version: (6.0.0), release build
Libraries: wxWidgets 3.1.5 libcurl/7.78.0-DEV Schannel zlib/1.2.11
Platform: Windows 10 (build 22000), 64-bit edition, 64 bit, Little endian, wxMSW
Build Info: Date: Dec 24 2021 19:17:02 wxWidgets: 3.1.5 (wchar_t,wx containers) Boost: 1.76.0 OCC: 7.5.0 Curl: 7.78.0-DEV ngspice: 35 Compiler: Visual C++ 1929 without C++ ABI
Build settings: KICAD_USE_OCC=ON KICAD_SPICE=ON