← All Pull Requests

AI Flow: JLCPCB 0.1.8 (#5) #6

Merged Released in 0.1.8 on 20 Nov 2026 opened by Colby Knox
Merges jlcpcb-0.1.8 → main

AI Flow: JLCPCB 0.1.8: export and rules on a macOS or Linux desktop (#5).

  • desk.rs: the desktop kind from the reported kicad-cli path; POSIX quoting, TMPDIR, zip (python zipfile fallback), rm -rf; Windows unchanged.
  • export.rs: export and drc_with_rules use it.

Tests: 16 pass (one added).

🤖 Generated with Claude Code

Diff Skip to comments

Cargo.lock+1−1
@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"  [[package]] name = "adom-aiflow-jlcpcb"-version = "0.1.7"+version = "0.1.8" dependencies = [  "clap",  "regex",
Cargo.toml+1−1
@@ -2,7 +2,7 @@ # Copied from adom/adom-aiflow template/flow-app. This copy is yours: change anything, never depend on aiflow. [package] name = "adom-aiflow-jlcpcb"-version = "0.1.7"+version = "0.1.8" edition = "2021" license = "MIT" 
bin/adom-aiflow-jlcpcb
⋯ 1 unchanged line ⋯
docs/release-0.1.8.mdadded+8
@@ -0,0 +1,8 @@+# AI Flow: JLCPCB 0.1.8++- **`export` and `rules` on a macOS or Linux desktop** (#5, Ruben Wegener Martinez). The commands sent to the desktop+  were Windows-only: the kicad-cli path joined with backslashes, the temp folder from `echo %TEMP%`, the gerbers zipped+  with PowerShell and the temp folder removed with `rmdir /s /q`. On a Mac the DRC failed with `sh:+  \Applications\KiCad\...\kicad-cli: command not found`. The desktop's kind now comes from the kicad-cli path KiCad's+  bridge reports, and a POSIX desktop gets POSIX quoting, `$TMPDIR` (else /tmp), `zip` (Python's zipfile where zip is+  missing) and `rm -rf`. Windows desktops are unchanged. Test added.
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow-jlcpcb",   "type": "app",-  "version": "0.1.7",+  "version": "0.1.8",   "title": "AI Flow: JLCPCB",   "description": "The JLCPCB ordering stage of AI Flow: from a finished board to assembled boards from JLCPCB. Part substitutes proven from both datasheets, the gerber zip, BOM and CPL from the desktop's own KiCad, every part's rotation checked against JLCPCB's own footprint and corrected, placement-preview evidence, the quote, the human's recorded OK before payment, and rotation corrections shared on component pages. Open source (MIT): build it with ./build.sh.",   "category": "Developer Tools",
page.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow-jlcpcb",   "type": "app",-  "version": "0.1.7",+  "version": "0.1.8",   "title": "AI Flow: JLCPCB",   "description": "The JLCPCB ordering stage of AI Flow: from a finished board to assembled boards from JLCPCB. Part substitutes proven from both datasheets, the gerber zip, BOM and CPL from the desktop's own KiCad, every part's rotation checked against JLCPCB's own footprint and corrected, placement-preview evidence, the quote, the human's recorded OK before payment, and rotation corrections shared on component pages. Open source (MIT): build it with ./build.sh.",   "category": "Developer Tools",
src/desk.rsadded+67
@@ -0,0 +1,67 @@+//! Issue #5 (Ruben Wegener Martinez): the desktop that runs KiCad may be Windows, macOS or Linux. The commands+//! sent to it (`shell_execute`) were Windows-only: backslash paths, `echo %TEMP%`, PowerShell's Compress-Archive and+//! `rmdir /s /q`. On a Mac the kicad-cli path came out as `\Applications\KiCad\...` and the temp folder as a literal+//! `%TEMP%`. The kicad-cli path KiCad's bridge reports says which kind of desktop it is.++/// The desktop's shell: Windows (`cmd`/PowerShell) or POSIX (`sh` on macOS and Linux).+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Desk { pub windows: bool }++impl Desk {+    /// From the kicad-cli path the desktop reported: an absolute POSIX path (`/Applications/...`, `/usr/bin/...`) is+    /// a macOS or Linux desktop; a drive letter or backslashes is Windows.+    pub fn from_cli(cli: &str) -> Desk { Desk { windows: !cli.trim_start().starts_with('/') } }++    /// The command that prints the desktop's temp folder.+    pub fn temp_cmd(&self) -> &'static str { if self.windows { "echo %TEMP%" } else { "printf '%s' \"${TMPDIR:-/tmp}\"" } }++    /// The temp folder from that command's output, with forward slashes and no trailing one; empty when it did not+    /// answer (or answered the unexpanded `%TEMP%`).+    pub fn temp_dir(&self, out: &str) -> String {+        let t = out.trim().replace('\\', "/");+        if t.is_empty() || t.contains('%') { String::new() } else { t.trim_end_matches('/').to_string() }+    }++    /// A path quoted for the desktop's shell.+    pub fn q(&self, p: &str) -> String {+        if self.windows { format!("\"{}\"", p.replace('/', "\\")) } else { format!("'{}'", p.replace('\'', "'\\''")) }+    }++    /// Zip every file of `dir` into `zip` (names relative to `dir`).+    pub fn zip_cmd(&self, dir: &str, zip: &str) -> String {+        if self.windows {+            format!("powershell -NoProfile -Command \"Compress-Archive -Path '{}\\*' -DestinationPath '{}' -Force\"", dir.replace('/', "\\"), zip.replace('/', "\\"))+        } else {+            // zip is on macOS and most Linux desktops; Python's zipfile where it is not+            format!("cd {} && (zip -qr {} . || python3 -m zipfile -c {} .)", self.q(dir), self.q(zip), self.q(zip))+        }+    }++    /// Remove a folder and everything in it.+    pub fn rm_cmd(&self, dir: &str) -> String {+        if self.windows { format!("rmdir /s /q {}", self.q(dir)) } else { format!("rm -rf {}", self.q(dir)) }+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn a_mac_desktop_gets_posix_commands() {+        let mac = Desk::from_cli("/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli");+        assert!(!mac.windows);+        assert_eq!(mac.q("/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli"), "'/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli'");+        assert_eq!(mac.temp_dir("/var/folders/x/T/\n"), "/var/folders/x/T");+        assert_eq!(mac.temp_dir("%TEMP%"), "", "an unexpanded %TEMP% is no folder");+        assert!(mac.zip_cmd("/tmp/a/gerbers", "/tmp/a/gerbers.zip").starts_with("cd '/tmp/a/gerbers' && (zip -qr '/tmp/a/gerbers.zip' ."));+        assert_eq!(mac.rm_cmd("/tmp/a b"), "rm -rf '/tmp/a b'");+        assert_eq!(mac.q("/tmp/it's"), "'/tmp/it'\\''s'");+        let win = Desk::from_cli("C:\\Program Files\\KiCad\\10.0\\bin\\kicad-cli.exe");+        assert!(win.windows);+        assert_eq!(win.q("C:/Users/me/AppData/Local/Temp/x"), "\"C:\\Users\\me\\AppData\\Local\\Temp\\x\"");+        assert_eq!(win.temp_dir("C:\\Users\\me\\AppData\\Local\\Temp\r\n"), "C:/Users/me/AppData/Local/Temp");+        assert!(win.rm_cmd("C:/t/x").starts_with("rmdir /s /q \"C:\\t\\x\""));+        assert!(win.zip_cmd("C:/t/g", "C:/t/g.zip").contains("Compress-Archive"));+    }+}
src/export.rs+9−7
@@ -32,7 +32,8 @@ pub fn export(br: &Bridge, board: &Path, bom_path: &Path, out: &Path, rotations:     let cli = Bridge::field(&st, "install").and_then(|i| i["kicadCli"].as_str()).map(str::to_string)         .or_else(|| std::env::var("KICAD_REMOTE_CLI").ok()).ok_or(format!("no KiCad on {} (set KICAD_REMOTE_CLI)", br.target))?;     let sh = |cmd: &str, why: &str| br.call("shell_execute", &json!({"command": cmd, "timeoutSeconds": 240, "reason": why}));-    let tmpw = out_text(&sh("echo %TEMP%", "temp folder for the JLCPCB export")).trim().replace('\\', "/");+    let desk = crate::desk::Desk::from_cli(&cli);+    let tmpw = desk.temp_dir(&out_text(&sh(desk.temp_cmd(), "temp folder for the JLCPCB export")));     if tmpw.is_empty() { return Err(format!("the desktop {} did not answer (is it connected?)", br.target)); }     let dest = format!("{tmpw}/aiflow-jlcpcb-{}", crate::ledger::now().replace([':', '-'], ""));     let dir = board.parent().unwrap();@@ -49,12 +50,12 @@ pub fn export(br: &Bridge, board: &Path, bom_path: &Path, out: &Path, rotations:     let mut layers = vec!["F.Cu".to_string(), "B.Cu".into()];     layers.extend((1..=inner.len()).map(|i| format!("In{i}.Cu")));     layers.extend(["F.Paste", "B.Paste", "F.Silkscreen", "B.Silkscreen", "F.Mask", "B.Mask", "Edge.Cuts"].map(String::from));-    let q = |p: &str| format!("\"{}\"", p.replace('/', "\\"));+    let q = |p: &str| desk.q(p);     let cmds = [         (format!("{} pcb export gerbers --output {} --layers {} {}", q(&cli), q(&gdir), layers.join(","), q(&wb)), "gerbers"),         (format!("{} pcb export drill --output {} --format excellon --drill-origin absolute --excellon-zeros-format decimal --excellon-units mm {}", q(&cli), q(&gdir), q(&wb)), "drill"),         (format!("{} pcb export pos --output {} --format csv --units mm --side both {}", q(&cli), q(&format!("{dest}/pos.csv")), q(&wb)), "placement"),-        (format!("powershell -NoProfile -Command \"Compress-Archive -Path '{}\\*' -DestinationPath '{}' -Force\"", gdir.replace('/', "\\"), format!("{dest}/gerbers.zip").replace('/', "\\")), "zip"),+        (desk.zip_cmd(&gdir, &format!("{dest}/gerbers.zip")), "zip"),     ];     let mut log = Vec::new();     for (c, what) in &cmds {@@ -67,7 +68,7 @@ pub fn export(br: &Bridge, board: &Path, bom_path: &Path, out: &Path, rotations:     std::fs::create_dir_all(&tmp).map_err(|e| e.to_string())?;     let (gz_ok, gz) = br.pull(&format!("{dest}/gerbers.zip"), &tmp, 3);     let (pos_ok, pos) = br.pull(&format!("{dest}/pos.csv"), &tmp, 3);-    sh(&format!("rmdir /s /q {}", q(&dest)), "clean up the JLCPCB export temp folder");+    sh(&desk.rm_cmd(&dest), "clean up the JLCPCB export temp folder");     if !(gz_ok && pos_ok) { return Err(format!("files did not come back: {}", Value::from(log.clone()))); }     let names: Vec<String> = zip::ZipArchive::new(std::fs::File::open(&gz).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?.file_names().map(str::to_string).collect();     let mut missing: Vec<String> = ["F_Cu", "B_Cu", "F_Mask", "B_Mask", "F_Silkscreen", "Edge_Cuts", "F_Paste"].iter().filter(|n| !names.iter().any(|x| x.contains(*n))).map(|s| s.to_string()).collect();@@ -153,7 +154,8 @@ pub fn drc_with_rules(br: &Bridge, board: &Path, dru: &str) -> Result<Value, Str     let cli = Bridge::field(&st, "install").and_then(|i| i["kicadCli"].as_str()).map(str::to_string)         .or_else(|| std::env::var("KICAD_REMOTE_CLI").ok()).ok_or(format!("no KiCad on {} (set KICAD_REMOTE_CLI)", br.target))?;     let sh = |cmd: &str, why: &str| br.call("shell_execute", &json!({"command": cmd, "timeoutSeconds": 300, "reason": why}));-    let tmpw = out_text(&sh("echo %TEMP%", "temp folder for the JLCPCB rules check")).trim().replace('\\', "/");+    let desk = crate::desk::Desk::from_cli(&cli);+    let tmpw = desk.temp_dir(&out_text(&sh(desk.temp_cmd(), "temp folder for the JLCPCB rules check")));     if tmpw.is_empty() { return Err(format!("the desktop {} did not answer (is it connected?)", br.target)); }     let dest = format!("{tmpw}/aiflow-jlcpcb-drc-{}", crate::ledger::now().replace([':', '-'], ""));     let local = std::env::temp_dir().join(format!("aiflow-jlcpcb-drc-{}", std::process::id()));@@ -165,11 +167,11 @@ pub fn drc_with_rules(br: &Bridge, board: &Path, dru: &str) -> Result<Value, Str     std::fs::write(local.join(format!("{base}.kicad_dru")), dru).map_err(|e| e.to_string())?;     let send: Vec<String> = std::fs::read_dir(&local).map_err(|e| e.to_string())?.flatten().map(|e| e.path().display().to_string()).collect();     br.call("send_files", &json!({"filePaths": send, "dest": dest, "reason": "JLCPCB rules check (a copy of the board with JLCPCB's rules)"}));-    let q = |p: &str| format!("\"{}\"", p.replace('/', "\\"));+    let q = |p: &str| desk.q(p);     let report = format!("{dest}/drc.json");     let r = sh(&format!("{} pcb drc --format json --units mm --severity-all --output {} {}", q(&cli), q(&report), q(&format!("{dest}/{base}.kicad_pcb"))), "JLCPCB rules check: DRC");     let (ok, got) = br.pull(&report, &local, 3);-    sh(&format!("rmdir /s /q {}", q(&dest)), "clean up the JLCPCB rules check temp folder");+    sh(&desk.rm_cmd(&dest), "clean up the JLCPCB rules check temp folder");     if !ok { let _ = std::fs::remove_dir_all(&local); return Err(format!("no DRC report came back: {}", out_text(&r).chars().take(400).collect::<String>())); }     let v: Value = serde_json::from_str(&std::fs::read_to_string(&got).unwrap_or_default()).map_err(|e| format!("DRC report: {e}"))?;     let _ = std::fs::remove_dir_all(&local);
src/main.rs+1
@@ -3,6 +3,7 @@ //! KiCad, every part's placement rotation checked against JLCPCB's own footprint, the placement preview captured, //! the quote, the human's OK before any money moves, the order, the delivered boards, and the rotation corrections //! shared on the parts' wiki pages so the next board gets them right the first time.+mod desk; mod bridge; mod csvio; mod export;

Comments

No comments yet.

Log in to comment.