aboutsummarylogtreecommitdiffstats
path: root/main.py
blob: e6c9b65c462297c765dd8840a98791cd85a7e605 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env python

from argparse import ArgumentParser
from dataclasses import dataclass
import os
from typing import Optional
from pathlib import Path
import tempfile
import subprocess

import sexpdata
from sexpdata import Symbol


@dataclass
class SymbolInfo:
    name: str
    description: Optional[str] = None
    datasheet: Optional[str] = None
    image: Optional[str] = None


@dataclass
class FootprintInfo:
    name: str
    description: Optional[str] = None
    image: Optional[str] = None


def get_symbols(filename):
    with open(filename, "r") as fobj:
        data = sexpdata.loads(fobj.read())

    symbols = []

    symbol_defs = [x for x in data if x[0] == Symbol("symbol")]
    for symbol_def in symbol_defs:
        symbol_info = SymbolInfo(name=str(symbol_def[1]))
        for child in symbol_def:
            if child[0] == Symbol("property"):
                if child[1] == "ki_description":
                    symbol_info.description = child[2]
                if child[1] == "Datasheet":
                    symbol_info.datasheet = child[2]
        symbols.append(symbol_info)

    return symbols


def get_descr(filename):
    with open(filename, "r") as fobj:
        data = sexpdata.loads(fobj.read())

    for prop in data:
        if prop[0] == Symbol("descr"):
            return prop[1]


def extract_symbol_libraries(symbols_dir: Path, images_dir: Path):
    libs = {}

    for symbol_file in symbols_dir.glob("*.kicad_sym"):
        print(f"* Extracting symbols from {symbol_file}")
        lib = []
        svg_dir = images_dir / symbol_file.name
        subprocess.call(
            [
                "kicad-cli",
                "sym",
                "export",
                "svg",
                symbol_file,
                "-o",
                svg_dir,
                # "--black-and-white",
            ]
        )
        for symbol in get_symbols(symbol_file):
            image_noext = str(svg_dir / symbol.name.lower())
            if not Path(image_noext + ".svg").exists():
                image_noext += "_1"
            print(f"  - Rendering image for {symbol_file}")
            subprocess.call(
                [
                    "convert",
                    "-density",
                    "300",
                    image_noext + ".svg",
                    image_noext + ".png",
                ]
            )
            symbol.image = image_noext + ".png"
            lib.append(symbol)
        for svg in svg_dir.glob("*.svg"):
            svg.unlink()
        libs[symbol_file.name] = lib
    return libs


def extract_footprint_libraries(footprints_dir: Path, images_dir: Path):
    libs = {}

    for lib_dir in footprints_dir.glob("*.pretty"):
        print(f"* Extracting footprints from {lib_dir}")
        lib = []
        svg_dir = images_dir / lib_dir.name
        subprocess.call(
            [
                "kicad-cli",
                "fp",
                "export",
                "svg",
                lib_dir,
                "-o",
                svg_dir,
                "--black-and-white",
            ]
        )
        for fp_file in lib_dir.glob("*.kicad_mod"):
            descr = get_descr(fp_file)
            image_noext = str(svg_dir / fp_file.stem)
            print(f"  - Rendering image for {fp_file}")
            subprocess.call(
                [
                    "convert",
                    "-density",
                    "300",
                    image_noext + ".svg",
                    image_noext + ".png",
                ]
            )
            lib.append(
                FootprintInfo(
                    name=fp_file.stem, description=descr, image=image_noext + ".png"
                )
            )
        for svg in svg_dir.glob("*.svg"):
            svg.unlink()
        libs[lib_dir.name] = lib
    return libs


def main(
    symbols_dir: Path,
    footprints_dir: Path,
    images_dir: Path,
    readme_file: Path,
    no_credits: bool,
):
    Path(images_dir).mkdir(parents=True, exist_ok=True)

    symbol_libraries = extract_symbol_libraries(symbols_dir, images_dir)
    footprint_libraries = extract_footprint_libraries(footprints_dir, images_dir)

    with readme_file.open("w") as fobj:
        if not no_credits:
            print(
                "This listing was generated with [kicad-storybook](https://github.com/and3rson/kicad-storybook).",
                file=fobj,
            )
            print(file=fobj)

        print("# Symbols", file=fobj)
        print(file=fobj)
        for lib_name, symbols in symbol_libraries.items():
            print(f"## {lib_name}", file=fobj)
            print(file=fobj)
            print("| Image | Symbol name | Datasheet | Description |", file=fobj)
            print("| --- | --- | --- | --- |", file=fobj)
            for symbol in symbols:
                print(
                    f"![{symbol.name}]({symbol.image}) | {symbol.name} | {symbol.datasheet} | {symbol.description}",
                    file=fobj,
                )
            print(file=fobj)

        print("# Footprints", file=fobj)
        print(file=fobj)
        for lib_name, footprints in footprint_libraries.items():
            print(f"## {lib_name}", file=fobj)
            print(file=fobj)
            print("| Image | Footprint name | Description |", file=fobj)
            print("| --- | --- | --- |", file=fobj)
            for footprint in footprints:
                print(
                    f"![{footprint.name}]({footprint.image}) | {footprint.name} | {footprint.description}",
                    file=fobj,
                )
            print(file=fobj)


if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("symbols_dir", help="Directory containing KiCad symbol files")
    parser.add_argument(
        "footprints_dir", help="Directory containing KiCad footprint files"
    )
    parser.add_argument("images_dir", help="Directory to write images to")
    parser.add_argument("readme_file", help="Destination README.md file")
    parser.add_argument(
        "--no-credits",
        action="store_true",
        help="Do not include the message about the README being auto-generated",
        default=False,
    )
    args = parser.parse_args()
    main(
        Path(args.symbols_dir),
        Path(args.footprints_dir),
        Path(args.images_dir),
        Path(args.readme_file),
        no_credits=args.no_credits,
    )