Skip to content

Instantly share code, notes, and snippets.

@Benestar
Last active July 19, 2018 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Benestar/dbac2b7cb2f07bdfadd4517b45e94635 to your computer and use it in GitHub Desktop.
Save Benestar/dbac2b7cb2f07bdfadd4517b45e94635 to your computer and use it in GitHub Desktop.
Align all equality signs in a source file
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if let Err(e) = doit(&args[1]) {
println!("Application error: {}", e);
process::exit(1);
}
}
fn doit(filename: &str) -> Result<(), Box<Error>> {
let mut f = File::open(filename)?;
let mut contents = String::new();
f.read_to_string(&mut contents)?;
let max_index = contents.lines()
.filter_map(|line| length_before_equal_sign(line))
.max()
.ok_or("no max index found")?;
for line in contents.lines() {
if let Some(n) = line.find('=') {
let lhs = &line[..n].trim_right();
let rhs = &line[n..];
let spacing = " ".repeat(max_index - lhs.len());
println!("{}{}{}", lhs, spacing, rhs);
}
else {
println!("{}", line);
}
}
Ok(())
}
fn length_before_equal_sign(line: &str) -> Option<usize> {
if let Some(n) = line.find('=') {
return Some(line[..n].trim_right().len());
}
None
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment