espanso/espanso-config/src/util.rs

75 lines
2.1 KiB
Rust
Raw Normal View History

2021-03-09 15:06:50 +00:00
/*
* This file is part of espanso.
*
* Copyright (C) 2019-2021 Federico Terzi
*
* espanso is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* espanso is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with espanso. If not, see <https://www.gnu.org/licenses/>.
*/
2021-02-26 21:33:33 +00:00
/// Check if the given string represents an empty YAML.
/// In other words, it checks if the document is only composed
/// of spaces and/or comments
pub fn is_yaml_empty(yaml: &str) -> bool {
for line in yaml.lines() {
let trimmed_line = line.trim();
if !trimmed_line.starts_with('#') && !trimmed_line.is_empty() {
2021-03-09 15:06:50 +00:00
return false;
2021-02-26 21:33:33 +00:00
}
}
true
}
#[cfg(test)]
pub mod tests {
2021-02-26 21:33:33 +00:00
use super::*;
use std::{fs::create_dir_all, path::Path};
use tempdir::TempDir;
pub fn use_test_directory(callback: impl FnOnce(&Path, &Path, &Path)) {
let dir = TempDir::new("tempconfig").unwrap();
let match_dir = dir.path().join("match");
create_dir_all(&match_dir).unwrap();
let config_dir = dir.path().join("config");
create_dir_all(&config_dir).unwrap();
2021-03-14 09:30:53 +00:00
callback(
&dunce::canonicalize(&dir.path()).unwrap(),
&dunce::canonicalize(match_dir).unwrap(),
&dunce::canonicalize(config_dir).unwrap(),
);
}
2021-02-26 21:33:33 +00:00
#[test]
fn is_yaml_empty_document_empty() {
2021-10-05 20:05:53 +00:00
assert!(is_yaml_empty(""));
2021-02-26 21:33:33 +00:00
}
#[test]
fn is_yaml_empty_document_with_comments() {
2021-10-05 20:05:53 +00:00
assert!(is_yaml_empty("\n#comment \n \n"));
2021-02-26 21:33:33 +00:00
}
#[test]
fn is_yaml_empty_document_with_comments_and_content() {
2021-10-05 20:05:53 +00:00
assert!(!is_yaml_empty("\n#comment \n field: true\n"));
2021-02-26 21:33:33 +00:00
}
#[test]
fn is_yaml_empty_document_with_content() {
2021-10-05 20:05:53 +00:00
assert!(!is_yaml_empty("\nfield: true\n"));
2021-02-26 21:33:33 +00:00
}
2021-03-09 15:06:50 +00:00
}