Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Last active June 29, 2019 11:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save internetimagery/936bc455d9ecd88988e5747d9294d52e to your computer and use it in GitHub Desktop.
Simple lightweight blackd client. Black, the uncompromising python formatter.
// For use with an active blackd service. eg:
// >>> rustc -Oo blackfmt blackfmt.rs
// >>> blackd --bind-port 6789
// >>> blackfmt --port 6789 /path/to/file.py
use std::fs;
use std::io::{Read, Write};
use std::net;
use std::path;
use std::time;
fn main() -> Result<(), Box<std::error::Error>> {
let mut port = 6789;
let mut host = String::from("127.0.0.1");
let mut sources = Vec::new();
let mut last_arg = String::new();
for arg in std::env::args().skip(1) {
match last_arg.as_ref() {
"--port" => port = arg.parse()?,
"--host" => host = arg.clone(),
_ => match arg.as_ref() {
"-h" | "--help" => {
eprintln!("Usage: blackfmt /path/to/file");
return Ok(());
}
_ => sources.push(path::Path::new(&arg).canonicalize()?),
},
}
last_arg = arg;
}
if sources.len() == 0 {
eprintln!("Please provide some sources.");
return Ok(());
}
let url = format!("{}:{}", host, port);
println!("Connecting to {}", url);
for source in sources {
let now = time::Instant::now();
let mut content = String::new();
fs::File::open(&source)?.read_to_string(&mut content)?;
let body = format!(
"POST / HTTP/1.0
Content-Type: text/plain; charset=UTF-8
Content-Length: {}
X-Fast-Or-Safe: fast
{}",
content.len(),
content
);
let mut stream = net::TcpStream::connect(&url)?;
stream.write(body.as_bytes())?;
let mut response = String::new();
stream.read_to_string(&mut response)?;
let response_code = &response[9..12];
let body = match response.find("\r\n\r\n") {
Some(pos) => &response[pos + 4..],
None => "",
};
match response_code {
"200" => {
let tempfile = format!("{}.black", source.to_str().unwrap());
fs::File::create(&tempfile)?.write_all(body.as_bytes())?;
fs::rename(tempfile, &source)?;
eprintln!(
"Formatted file ({}): {}",
now.elapsed().as_millis(),
source.to_str().unwrap()
);
}
"204" => eprintln!("No change required in {:?}", source),
"400" => eprintln!("Syntax error: {}", body),
_ => eprintln!("Error: {}", body),
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment