use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::host::{Machine, Result};
use super::import::Target;
use super::local::State;
use super::output::say;
use crate::profile::files::{self, Project};
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct Imported {
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub scopes: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub directories: BTreeMap<String, String>,
}
impl Imported {
pub fn is_empty(&self) -> bool {
self.scopes.is_empty() && self.directories.is_empty()
}
fn kept(&self, assigned: impl Fn(&str) -> bool) -> Self {
let keep = |map: &BTreeMap<String, String>| {
map.iter()
.filter(|(_, profile)| assigned(profile))
.map(|(key, profile)| (key.clone(), profile.clone()))
.collect()
};
Self {
scopes: keep(&self.scopes),
directories: keep(&self.directories),
}
}
pub fn select(&self, managed: &BTreeSet<String>, project: &Path) -> Option<&str> {
if self.is_empty() {
return None;
}
let dir = project
.canonicalize()
.unwrap_or_else(|_| project.to_path_buf());
let assigned = |profile: &&String| managed.contains(profile.as_str());
let exact = dir.to_str().and_then(|d| self.directories.get(d));
exact
.filter(assigned)
.or_else(|| {
let scope = crate::home::project_scope(&dir).ok()?;
self.scopes.get(&scope).filter(assigned)
})
.map(String::as_str)
}
}
pub(crate) struct Finish {
pub account: String,
pub scopes: BTreeSet<String>,
pub targets: Vec<Target>,
pub directory: PathBuf,
}
fn unbound(target: &Target, reason: &str) -> Value {
json!({"source": target.source, "profile": target.profile, "reason": reason})
}
fn map(finish: &Finish, assigned: impl Fn(&str) -> bool) -> (BTreeMap<String, String>, Vec<Value>) {
let mut mapped = BTreeMap::new();
let mut left = Vec::new();
let mut twice = BTreeSet::new();
for target in &finish.targets {
let reason = if !finish.scopes.contains(&target.source) {
"unknown"
} else if target.mount == "me" {
continue;
} else {
match target.profile.as_deref() {
None => "unnamed",
Some(p) if !assigned(p) => "unassigned",
Some(p) => match mapped.insert(target.source.clone(), p.to_string()) {
Some(other) if other != p => {
twice.insert(target.source.clone());
"twice"
}
_ => continue,
},
}
};
left.push(unbound(target, reason));
}
mapped.retain(|scope, _| !twice.contains(scope));
(mapped, left)
}
fn this_directory(
dir: &Path,
scopes: &BTreeMap<String, String>,
registry: &[Project],
chosen: Option<&Project>,
bound: &mut BTreeMap<String, String>,
) -> Value {
let Ok(dir) = dir.canonicalize() else {
return Value::Null;
};
let root = dir.to_string_lossy();
let scope = crate::home::project_scope(&dir).ok();
let covering = registry
.iter()
.chain(chosen)
.filter(|p| dir.starts_with(&p.root))
.max_by_key(|p| p.root.components().count());
if let Some(binding) = covering {
return json!({"root": root, "scope": scope, "profile": binding.profile, "bound": "kept"});
}
let profile = scope.as_ref().and_then(|s| scopes.get(s));
match (profile, dir.to_str()) {
(Some(profile), Some(key)) => {
bound.insert(key.to_string(), profile.clone());
json!({"root": root, "scope": scope, "profile": profile, "bound": "import"})
}
_ => json!({"root": root, "scope": scope, "profile": null, "bound": "none"}),
}
}
pub(super) fn settle(
home: &Path,
prior: Option<&State>,
doc: &Machine,
finishing: Option<&Finish>,
chosen: Option<&Project>,
) -> Result<(Imported, Option<Value>)> {
let assigned = |profile: &str| doc.profiles.contains_key(profile);
let mut imported = prior.map(|s| s.imported.kept(assigned)).unwrap_or_default();
let Some(finish) = finishing else {
return Ok((imported, None));
};
if doc.account.id != finish.account {
return Err(say("import_other_account"));
}
let (mapped, unbound) = map(finish, assigned);
imported.scopes.extend(mapped.clone());
let registry = files::registry(home)?;
let directory = this_directory(
&finish.directory,
&imported.scopes,
®istry.projects,
chosen,
&mut imported.directories,
);
let summary = json!({"status": "succeeded", "finished": true, "directory": directory,
"unbound": unbound, "mapped": mapped.len(), "default": doc.default_profile});
Ok((imported, Some(summary)))
}
#[cfg(test)]
#[path = "directories_tests.rs"]
mod tests;