Last active
July 19, 2018 10:16
-
-
Save Benestar/dbac2b7cb2f07bdfadd4517b45e94635 to your computer and use it in GitHub Desktop.
Align all equality signs in a source file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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