colmena/src/util.rs

71 lines
2 KiB
Rust
Raw Normal View History

2020-12-18 10:27:44 +01:00
use std::collections::HashMap;
2020-12-16 05:21:26 +01:00
use clap::{Arg, App};
use glob::Pattern as GlobPattern;
2020-12-18 10:27:44 +01:00
use super::nix::DeploymentConfig;
enum NodeFilter {
NameFilter(GlobPattern),
TagFilter(GlobPattern),
}
pub fn filter_nodes(nodes: &HashMap<String, DeploymentConfig>, filter: &str) -> Vec<String> {
let filters: Vec<NodeFilter> = filter.split(",").map(|pattern| {
use NodeFilter::*;
if let Some(tag_pattern) = pattern.strip_prefix("@") {
TagFilter(GlobPattern::new(tag_pattern).unwrap())
} else {
NameFilter(GlobPattern::new(pattern).unwrap())
}
}).collect();
2020-12-16 05:21:26 +01:00
if filters.len() > 0 {
2020-12-18 10:27:44 +01:00
nodes.iter().filter_map(|(name, node)| {
2020-12-16 05:21:26 +01:00
for filter in filters.iter() {
2020-12-18 10:27:44 +01:00
use NodeFilter::*;
match filter {
TagFilter(pat) => {
// Welp
for tag in node.tags() {
if pat.matches(tag) {
return Some(name);
}
}
}
NameFilter(pat) => {
if pat.matches(name) {
return Some(name)
}
}
2020-12-16 05:21:26 +01:00
}
}
2020-12-18 10:27:44 +01:00
None
2020-12-16 05:21:26 +01:00
}).cloned().collect()
} else {
2020-12-18 10:27:44 +01:00
nodes.keys().cloned().collect()
2020-12-16 05:21:26 +01:00
}
}
pub fn register_common_args<'a, 'b>(command: App<'a, 'b>) -> App<'a, 'b> {
command
.arg(Arg::with_name("config")
.short("f")
.long("config")
.help("Path to a Hive expression")
.default_value("hive.nix")
.required(true))
.arg(Arg::with_name("on")
.long("on")
.help("Select a list of machines")
2020-12-18 10:27:44 +01:00
.long_help(r#"The list is comma-separated and globs are supported. To match tags, prepend the filter by @.
2020-12-16 05:21:26 +01:00
Valid examples:
- host1,host2,host3
- edge-*
2020-12-18 10:27:44 +01:00
- edge-*,core-*
- @a-tag,@tags-can-have-*"#)
2020-12-16 05:21:26 +01:00
.takes_value(true))
}