tools: add file_get_non_comment_lines

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2020-05-22 10:55:31 +02:00
parent bc853b028f
commit 386990ba09

View File

@ -5,8 +5,7 @@ use std::any::Any;
use std::collections::HashMap;
use std::hash::BuildHasher;
use std::fs::{File, OpenOptions};
use std::io::ErrorKind;
use std::io::Read;
use std::io::{self, BufRead, ErrorKind, Read};
use std::os::unix::io::{AsRawFd, RawFd};
use std::path::Path;
use std::time::Duration;
@ -572,3 +571,27 @@ pub const DEFAULT_ENCODE_SET: &AsciiSet = &percent_encoding::CONTROLS // 0..1f a
.add(b'?')
.add(b'{')
.add(b'}');
/// Get an iterator over lines of a file, skipping empty lines and comments (lines starting with a
/// `#`).
pub fn file_get_non_comment_lines<P: AsRef<Path>>(
path: P,
) -> Result<impl Iterator<Item = io::Result<String>>, Error> {
let path = path.as_ref();
Ok(io::BufReader::new(
File::open(path).map_err(|err| format_err!("error opening {:?}: {}", path, err))?,
)
.lines()
.filter_map(|line| match line {
Ok(line) => {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
None
} else {
Some(Ok(line.to_string()))
}
}
Err(err) => Some(Err(err)),
}))
}