From 386990ba09edc21edd3a0c9cba7200be8c3b709b Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Fri, 22 May 2020 10:55:31 +0200 Subject: [PATCH] tools: add file_get_non_comment_lines Signed-off-by: Wolfgang Bumiller --- src/tools.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/tools.rs b/src/tools.rs index 59fee2a7..9cfd95b7 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -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>( + path: P, +) -> Result>, 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)), + })) +}