app
AI Flow: PCBWay
Public Made by Adomby adom
Prepare PCBWay RFQs, preserve manufacturing gates, track complete vendor quotes and compare assembly costs. MIT Rust CLI with Pup workflow skill.
main
Colby Knox
adom-aiflow-pcbway 0.1.3: a guide, never a gate (checks report findings; only could-not-run is an error)
80bd934
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
//! A small RFC 4180 CSV reader and writer (quoted fields, doubled quotes, commas and newlines in quotes).
pub fn parse(text: &str) -> Vec<Vec<String>> {
let mut rows = Vec::new();
let mut row = Vec::new();
let mut field = String::new();
let mut quoted = false;
let mut chars = text.chars().peekable();
let mut any = false;
while let Some(c) = chars.next() {
any = true;
if quoted {
if c == '"' {
if chars.peek() == Some(&'"') {
field.push('"');
chars.next();
} else {
quoted = false;
}
} else {
field.push(c);
}
continue;
}
match c {
'"' => quoted = true,
',' => row.push(std::mem::take(&mut field)),
'\r' => {}
'\n' => {
row.push(std::mem::take(&mut field));
rows.push(std::mem::take(&mut row));
any = false;
}
_ => field.push(c),
}
}
if any {
row.push(field);
rows.push(row);
}
rows
}
/// Header and rows as maps, like Python's csv.DictReader (missing cells read as "").
pub struct Table {
pub head: Vec<String>,
pub rows: Vec<Vec<String>>,
}
impl Table {
pub fn read(path: &std::path::Path) -> std::io::Result<Table> {
let t = std::fs::read_to_string(path)?;
let t = t.strip_prefix('\u{feff}').unwrap_or(&t);
let mut all = parse(t);
if all.is_empty() {
return Ok(Table {
head: vec![],
rows: vec![],
});
}
let head = all
.remove(0)
.into_iter()
.map(|h| h.trim().to_string())
.collect();
Ok(Table {
head,
rows: all
.into_iter()
.filter(|r| !(r.len() == 1 && r[0].is_empty()))
.collect(),
})
}
/// A column by name: exact first, then case and punctuation ignored, then the usual aliases, so AI Flow's
/// `export` files (Reference/MPN/Manufacturer/Value; kicad-cli's Ref/PosX/PosY/Rot/Side) and JLCPCB-style
/// files both read as they are.
pub fn col(&self, name: &str) -> Option<usize> {
if let Some(i) = self.head.iter().position(|h| h == name) {
return Some(i);
}
let norm = |s: &str| {
s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.collect::<String>()
.to_ascii_lowercase()
};
let aliases: &[&str] = match name {
"ref" | "Designator" => &["ref", "refs", "reference", "references", "designator", "designators", "refdes"],
"mpn" => &["mpn", "manufacturerpartnumber", "manufacturerpn", "mfrpn", "partnumber"],
"manufacturer" => &["manufacturer", "mfr", "mfg", "maker"],
"value" => &["value", "comment", "val", "description"],
"Mid X" => &["midx", "posx", "x", "centerx", "locationx"],
"Mid Y" => &["midy", "posy", "y", "centery", "locationy"],
"Rotation" => &["rotation", "rot", "angle"],
"Layer" => &["layer", "side"],
_ => &[],
};
std::iter::once(norm(name))
.chain(aliases.iter().map(|a| a.to_string()))
.find_map(|w| self.head.iter().position(|h| norm(h) == w))
}
pub fn get<'a>(&self, row: &'a [String], name: &str) -> &'a str {
self.col(name)
.and_then(|i| row.get(i))
.map(|s| s.as_str())
.unwrap_or("")
}
}
fn quote(f: &str) -> String {
if f.contains([',', '"', '\n', '\r']) {
format!("\"{}\"", f.replace('"', "\"\""))
} else {
f.to_string()
}
}
/// Rows joined with `eol` ("\r\n" matches Python's csv module default, which JLCPCB's files were made with).
pub fn write(rows: &[Vec<String>], eol: &str) -> String {
rows.iter()
.map(|r| r.iter().map(|f| quote(f)).collect::<Vec<_>>().join(",") + eol)
.collect()
}
#[cfg(test)]
mod tests {
#[test]
fn quoted_fields_round_trip() {
let rows = super::parse("a,\"b, c\",\"d \"\"e\"\"\"\r\n1,2,3\n");
assert_eq!(
rows,
vec![vec!["a", "b, c", "d \"e\""], vec!["1", "2", "3"]]
);
assert_eq!(
super::write(&rows, "\n"),
"a,\"b, c\",\"d \"\"e\"\"\"\n1,2,3\n"
);
}
}