brep_ecad_core/
kicad_git.rs1#![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
25pub const TAG: &str = "9.0.9.1";
29
30pub const BASE_URL: &str = "https://gitlab.com/kicad/libraries";
32
33#[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 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 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
68pub 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
82pub 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 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 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
175pub 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
188fn 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
219fn 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