Skip to main content

brep_ecad_core/
kicad_git.rs

1//! KiCad's official libraries, cloned with git.
2//!
3//! KiCad keeps its libraries in three GitLab projects, one per link of the
4//! symbol → footprint → 3D-model chain. An import clones each one, shallow and
5//! at one pinned release tag, and then reads the clones as an ordinary folder
6//! of KiCad files. `git` must be on the PATH; where it is not, or the clone
7//! cannot reach GitLab, the caller asks for the folders instead.
8//!
9//! A clone is written to `<dest>.partial` and renamed to `<dest>` only once git
10//! has finished, so a folder at `<dest>` is always a whole checkout and a clone
11//! that was stopped or killed leaves nothing that reads as one. The tag is the
12//! caller's to put in `dest`, so a different release is a different folder.
13//!
14//! At 9.0.9.1 the three checkouts are 220 MB, 195 MB and 5.2 GB (measured
15//! 2026-10-24); the models are most of it.
16
17#![cfg(not(target_arch = "wasm32"))]
18
19use std::io::Read;
20use std::path::{Path, PathBuf};
21use std::process::{Command, Stdio};
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::time::Duration;
24
25/// The release every import reads. A 9.x tag: KiCad 10 (the repositories'
26/// `master`) stores a symbol library as a `*.kicad_symdir` folder, which the
27/// importers do not read; 9.x keeps one `*.kicad_sym` file per library.
28pub const TAG: &str = "9.0.9.1";
29
30/// Where the three projects live; a test points [`clone`] at a local copy.
31pub const BASE_URL: &str = "https://gitlab.com/kicad/libraries";
32
33/// One of KiCad's three library repositories.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub enum Repo {
36    Symbols,
37    Footprints,
38    Models,
39}
40
41impl Repo {
42    pub const ALL: [Repo; 3] = [Repo::Symbols, Repo::Footprints, Repo::Models];
43
44    /// The GitLab project's name, which is also the last segment of its URL.
45    pub fn project(self) -> &'static str {
46        match self {
47            Repo::Symbols => "kicad-symbols",
48            Repo::Footprints => "kicad-footprints",
49            Repo::Models => "kicad-packages3D",
50        }
51    }
52
53    /// The folder KiCad's own install keeps this repository's files in, so a
54    /// root holding all three under these names is laid out like an install.
55    pub fn install_folder(self) -> &'static str {
56        match self {
57            Repo::Symbols => "symbols",
58            Repo::Footprints => "footprints",
59            Repo::Models => "3dmodels",
60        }
61    }
62
63    pub fn url(self, base: &str) -> String {
64        format!("{}/{}.git", base.trim_end_matches('/'), self.project())
65    }
66}
67
68/// `git --version`, or why git cannot be run.
69pub fn git_version() -> Result<String, String> {
70    let output = git()
71        .arg("--version")
72        .stdout(Stdio::piped())
73        .stderr(Stdio::null())
74        .output()
75        .map_err(spawn_error)?;
76    if !output.status.success() {
77        return Err(format!("`git --version` failed ({})", output.status));
78    }
79    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
80}
81
82/// Clone `url` at `tag` into `dest`, unless `dest` is already there.
83///
84/// `progress` is handed each line git prints about the transfer, for a status
85/// label. Setting `cancel` kills git; the partial clone is removed and the
86/// answer is an error. `Ok(true)` when this call cloned, `Ok(false)` when the
87/// folder was already present.
88pub fn clone(
89    url: &str,
90    tag: &str,
91    dest: &Path,
92    progress: &mut dyn FnMut(&str),
93    cancel: &AtomicBool,
94) -> Result<bool, String> {
95    if dest.is_dir() {
96        return Ok(false);
97    }
98    let partial = partial_path(dest);
99    if partial.exists() {
100        std::fs::remove_dir_all(&partial).map_err(|e| format!("{}: {e}", partial.display()))?;
101    }
102    if let Some(parent) = dest.parent() {
103        std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
104    }
105    let mut child = clone_command(url, tag, &partial).spawn().map_err(spawn_error)?;
106
107    // git writes its progress to stderr, rewriting a line with `\r`. A reader
108    // thread keeps the pipe drained so git never blocks on it, and this thread
109    // stays free to notice `cancel`.
110    let mut stderr = child.stderr.take().expect("stderr is piped");
111    let (send, lines) = std::sync::mpsc::channel::<String>();
112    let reader = std::thread::spawn(move || {
113        let mut buffer = [0u8; 4096];
114        let mut line = Vec::new();
115        while let Ok(read) = stderr.read(&mut buffer) {
116            if read == 0 {
117                break;
118            }
119            for &byte in &buffer[..read] {
120                if byte == b'\r' || byte == b'\n' {
121                    if !line.is_empty() {
122                        let _ = send.send(String::from_utf8_lossy(&line).trim().to_owned());
123                        line.clear();
124                    }
125                } else {
126                    line.push(byte);
127                }
128            }
129        }
130        if !line.is_empty() {
131            let _ = send.send(String::from_utf8_lossy(&line).trim().to_owned());
132        }
133    });
134
135    let mut last = Vec::<String>::new();
136    let status = loop {
137        match lines.recv_timeout(Duration::from_millis(200)) {
138            Ok(line) => {
139                progress(&line);
140                if last.len() == 4 {
141                    last.remove(0);
142                }
143                last.push(line);
144                continue;
145            }
146            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
147            // git closed stderr and is exiting; do not spin while it does.
148            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => std::thread::sleep(Duration::from_millis(20)),
149        }
150        if cancel.load(Ordering::Relaxed) {
151            let _ = child.kill();
152            let _ = child.wait();
153            let _ = reader.join();
154            let _ = std::fs::remove_dir_all(&partial);
155            return Err(format!("the clone of {url} was stopped"));
156        }
157        if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
158            let _ = reader.join();
159            for line in lines.try_iter() {
160                progress(&line);
161                last.push(line);
162            }
163            break status;
164        }
165    };
166    if !status.success() {
167        let _ = std::fs::remove_dir_all(&partial);
168        let said = last.iter().rev().take(3).rev().cloned().collect::<Vec<_>>().join("; ");
169        return Err(format!("git clone {url} at {tag} failed ({status}): {said}"));
170    }
171    std::fs::rename(&partial, dest).map_err(|e| format!("moving {} to {}: {e}", partial.display(), dest.display()))?;
172    Ok(true)
173}
174
175/// The `*.kicad_sym` library names in a symbols checkout, without their
176/// extension, sorted.
177pub fn symbol_libraries(dir: &Path) -> Result<Vec<String>, String> {
178    let entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
179    let mut names: Vec<String> = entries
180        .filter_map(Result::ok)
181        .filter(|entry| entry.path().is_file())
182        .filter_map(|entry| entry.file_name().to_str()?.strip_suffix(".kicad_sym").map(str::to_owned))
183        .collect();
184    names.sort();
185    Ok(names)
186}
187
188/// The `git clone` that fetches `url` at `tag` into `partial`: shallow, the one
189/// branch, progress on stderr for the caller to read.
190///
191/// `core.fsync=none`: the clone is a cache, written to `partial` and renamed
192/// into place only when whole, and cloned again when it is not there, so
193/// git's fsync of the pack buys it nothing. What it costs is a wait on the
194/// disk's journal behind every other writer: on a host with the root disk at
195/// 100% utilisation (measured 2026-10-26) the default clone of a three-file
196/// repository made 3 fsync calls and took 129 s, the same clone without them
197/// 5.5 s. The option precedes the subcommand so git hands it to index-pack and
198/// the other helpers it spawns. The trade: an unclean shutdown inside the
199/// seconds after the rename can leave a `dest` with a truncated pack, which
200/// the user clears by deleting the folder.
201fn clone_command(url: &str, tag: &str, partial: &Path) -> Command {
202    let mut command = git();
203    command
204        .args(["-c", "core.autocrlf=false", "-c", "core.longpaths=true", "-c", "advice.detachedHead=false"])
205        .args(["-c", "core.fsync=none"])
206        .args(["clone", "--progress", "--depth", "1", "--single-branch", "--branch", tag, url])
207        .arg(partial)
208        .stdout(Stdio::null())
209        .stderr(Stdio::piped());
210    command
211}
212
213fn partial_path(dest: &Path) -> PathBuf {
214    let mut name = dest.file_name().unwrap_or_default().to_os_string();
215    name.push(".partial");
216    dest.with_file_name(name)
217}
218
219/// A `git` command that cannot stop to ask for anything: no credential prompt
220/// (the projects are public; a prompt means the URL is wrong) and, on Windows,
221/// no console window flashing up beside a GUI program.
222fn git() -> Command {
223    let mut command = Command::new("git");
224    command.env("GIT_TERMINAL_PROMPT", "0").stdin(Stdio::null());
225    #[cfg(windows)]
226    {
227        use std::os::windows::process::CommandExt;
228        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
229        command.creation_flags(CREATE_NO_WINDOW);
230    }
231    command
232}
233
234fn spawn_error(error: std::io::Error) -> String {
235    if error.kind() == std::io::ErrorKind::NotFound {
236        "git was not found on the PATH".into()
237    } else {
238        format!("git could not be started: {error}")
239    }
240}
241