#![cfg(not(target_arch = "wasm32"))]
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
pub const TAG: &str = "9.0.9.1";
pub const BASE_URL: &str = "https://gitlab.com/kicad/libraries";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Repo {
Symbols,
Footprints,
Models,
}
impl Repo {
pub const ALL: [Repo; 3] = [Repo::Symbols, Repo::Footprints, Repo::Models];
pub fn project(self) -> &'static str {
match self {
Repo::Symbols => "kicad-symbols",
Repo::Footprints => "kicad-footprints",
Repo::Models => "kicad-packages3D",
}
}
pub fn install_folder(self) -> &'static str {
match self {
Repo::Symbols => "symbols",
Repo::Footprints => "footprints",
Repo::Models => "3dmodels",
}
}
pub fn url(self, base: &str) -> String {
format!("{}/{}.git", base.trim_end_matches('/'), self.project())
}
}
pub fn git_version() -> Result<String, String> {
let output = git()
.arg("--version")
.stdout(Stdio::piped())
.stderr(Stdio::null())
.output()
.map_err(spawn_error)?;
if !output.status.success() {
return Err(format!("`git --version` failed ({})", output.status));
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}
pub fn clone(
url: &str,
tag: &str,
dest: &Path,
progress: &mut dyn FnMut(&str),
cancel: &AtomicBool,
) -> Result<bool, String> {
if dest.is_dir() {
return Ok(false);
}
let partial = partial_path(dest);
if partial.exists() {
std::fs::remove_dir_all(&partial).map_err(|e| format!("{}: {e}", partial.display()))?;
}
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
let mut child = clone_command(url, tag, &partial).spawn().map_err(spawn_error)?;
let mut stderr = child.stderr.take().expect("stderr is piped");
let (send, lines) = std::sync::mpsc::channel::<String>();
let reader = std::thread::spawn(move || {
let mut buffer = [0u8; 4096];
let mut line = Vec::new();
while let Ok(read) = stderr.read(&mut buffer) {
if read == 0 {
break;
}
for &byte in &buffer[..read] {
if byte == b'\r' || byte == b'\n' {
if !line.is_empty() {
let _ = send.send(String::from_utf8_lossy(&line).trim().to_owned());
line.clear();
}
} else {
line.push(byte);
}
}
}
if !line.is_empty() {
let _ = send.send(String::from_utf8_lossy(&line).trim().to_owned());
}
});
let mut last = Vec::<String>::new();
let status = loop {
match lines.recv_timeout(Duration::from_millis(200)) {
Ok(line) => {
progress(&line);
if last.len() == 4 {
last.remove(0);
}
last.push(line);
continue;
}
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => std::thread::sleep(Duration::from_millis(20)),
}
if cancel.load(Ordering::Relaxed) {
let _ = child.kill();
let _ = child.wait();
let _ = reader.join();
let _ = std::fs::remove_dir_all(&partial);
return Err(format!("the clone of {url} was stopped"));
}
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
let _ = reader.join();
for line in lines.try_iter() {
progress(&line);
last.push(line);
}
break status;
}
};
if !status.success() {
let _ = std::fs::remove_dir_all(&partial);
let said = last.iter().rev().take(3).rev().cloned().collect::<Vec<_>>().join("; ");
return Err(format!("git clone {url} at {tag} failed ({status}): {said}"));
}
std::fs::rename(&partial, dest).map_err(|e| format!("moving {} to {}: {e}", partial.display(), dest.display()))?;
Ok(true)
}
pub fn symbol_libraries(dir: &Path) -> Result<Vec<String>, String> {
let entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let mut names: Vec<String> = entries
.filter_map(Result::ok)
.filter(|entry| entry.path().is_file())
.filter_map(|entry| entry.file_name().to_str()?.strip_suffix(".kicad_sym").map(str::to_owned))
.collect();
names.sort();
Ok(names)
}
fn clone_command(url: &str, tag: &str, partial: &Path) -> Command {
let mut command = git();
command
.args(["-c", "core.autocrlf=false", "-c", "core.longpaths=true", "-c", "advice.detachedHead=false"])
.args(["-c", "core.fsync=none"])
.args(["clone", "--progress", "--depth", "1", "--single-branch", "--branch", tag, url])
.arg(partial)
.stdout(Stdio::null())
.stderr(Stdio::piped());
command
}
fn partial_path(dest: &Path) -> PathBuf {
let mut name = dest.file_name().unwrap_or_default().to_os_string();
name.push(".partial");
dest.with_file_name(name)
}
fn git() -> Command {
let mut command = Command::new("git");
command.env("GIT_TERMINAL_PROMPT", "0").stdin(Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
command.creation_flags(CREATE_NO_WINDOW);
}
command
}
fn spawn_error(error: std::io::Error) -> String {
if error.kind() == std::io::ErrorKind::NotFound {
"git was not found on the PATH".into()
} else {
format!("git could not be started: {error}")
}
}