use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::RwLock;
use serde_json::{Map, Value};
use subspace_product::ValidatedProduct;
pub type Renames = BTreeMap<String, String>;
static INSTALLED: RwLock<Renames> = RwLock::new(Renames::new());
pub fn declared(product: &ValidatedProduct) -> Renames {
product
.boards
.iter()
.flat_map(|board| {
board
.former_ids
.iter()
.map(move |former| (former.as_str().to_owned(), board.id.as_str().to_owned()))
})
.collect()
}
pub fn install(renames: Renames) {
if let Ok(mut installed) = INSTALLED.write() {
*installed = renames;
}
}
pub(crate) fn installed() -> Renames {
INSTALLED
.read()
.map(|renames| renames.clone())
.unwrap_or_default()
}
#[derive(Clone, Copy)]
enum Shape {
Whole,
Trimmed,
Prefixed(&'static str),
}
const CONFIG_KEYS: &[(&[&str], Shape, &[&str])] = &[
(&["boards"], Shape::Trimmed, &[]),
(&["features"], Shape::Prefixed("board."), &[]),
(
&["mcp", "groups"],
Shape::Whole,
&[subspace_product::MCP_APPLICATION_GROUP],
),
(&["commands", "aliases"], Shape::Whole, &[]),
];
const STATE_KEYS: &[Shape] = &[
Shape::Prefixed(""),
Shape::Prefixed("board."),
Shape::Prefixed("notifications."),
];
const ACTIVE_SPACE: &str = "app.dashboard";
const FRAMEWORK_KEYS: &[&str] = &[crate::credentials::GITHUB_ACCOUNT_KEY];
fn normal(key: &str, shape: Shape) -> &str {
match shape {
Shape::Trimmed => key.trim(),
Shape::Whole | Shape::Prefixed(_) => key,
}
}
fn renamed(key: &str, renames: &Renames, shape: Shape) -> Option<String> {
match shape {
Shape::Whole | Shape::Trimmed => renames.get(normal(key, shape)).cloned(),
Shape::Prefixed(prefix) => {
let (id, rest) = key.strip_prefix(prefix)?.split_once('.')?;
renames.get(id).map(|to| format!("{prefix}{to}.{rest}"))
}
}
}
fn moves<'a>(
keys: impl IntoIterator<Item = &'a String>,
renames: &Renames,
shapes: &[Shape],
) -> Vec<(String, String)> {
keys.into_iter()
.filter_map(|key| {
let to = shapes
.iter()
.find_map(|shape| renamed(key, renames, *shape))?;
Some((key.clone(), to))
})
.collect()
}
fn unowned(moves: Vec<(String, String)>, owned: &[&str]) -> Vec<(String, String)> {
let is_owned = |key: &str| owned.contains(&key);
moves
.into_iter()
.filter(|(from, to)| !is_owned(from) && !is_owned(to))
.collect()
}
pub(crate) fn state_moves<'a>(
keys: impl IntoIterator<Item = &'a String>,
renames: &Renames,
) -> Vec<(String, String)> {
unowned(moves(keys, renames, STATE_KEYS), FRAMEWORK_KEYS)
}
pub(crate) fn renamed_value(key: &str, value: &str, renames: &Renames) -> Option<String> {
(key == ACTIVE_SPACE)
.then(|| renames.get(value).cloned())
.flatten()
}
fn rename_keys(
object: &mut Map<String, Value>,
renames: &Renames,
(shape, owned): (Shape, &[&str]),
) -> bool {
let moves = unowned(moves(object.keys(), renames, &[shape]), owned);
for (from, to) in &moves {
if let Some(value) = object.remove(from)
&& !object.keys().any(|key| normal(key, shape) == to)
{
object.insert(to.clone(), value);
}
}
!moves.is_empty()
}
fn object_at<'a>(
root: &'a mut Map<String, Value>,
path: &[&str],
) -> Option<&'a mut Map<String, Value>> {
path.iter()
.try_fold(root, |object, key| object.get_mut(*key)?.as_object_mut())
}
fn rename_order(root: &mut Map<String, Value>, renames: &Renames) -> bool {
let Some(Value::Array(order)) = root.get_mut("boardOrder") else {
return false;
};
let listed: BTreeSet<String> = order
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
let mut added = BTreeSet::new();
let renamed: Vec<Value> = order
.iter()
.filter_map(
|entry| match entry.as_str().and_then(|id| renames.get(id)) {
Some(to) => (!listed.contains(to) && added.insert(to.clone()))
.then(|| Value::String(to.clone())),
None => Some(entry.clone()),
},
)
.collect();
let changed = renamed != *order;
*order = renamed;
changed
}
pub fn rename_config(root: &mut Map<String, Value>, renames: &Renames) -> bool {
let mut changed = rename_order(root, renames);
for &(path, shape, owned) in CONFIG_KEYS {
if let Some(object) = object_at(root, path) {
changed |= rename_keys(object, renames, (shape, owned));
}
}
changed
}
pub(crate) fn board_file(dir: &Path, id: &str, renames: &Renames) -> PathBuf {
let file = |id: &str| dir.join(id).join("config.json");
let own = file(id);
if !matches!(own.try_exists(), Ok(false)) {
return own;
}
renames
.iter()
.filter(|(_, to)| to.as_str() == id)
.map(|(from, _)| file(from))
.find(|former| former.exists())
.unwrap_or(own)
}
#[cfg(test)]
mod tests;