use std::collections::BTreeSet;
use std::path::Path;
use crate::release::{InstallChannel, Marker, MARKER_FILE};
use crate::{
insert_dotted, remove_dotted, secure_fs, AiConfig, Config, Error, InstallationConfig,
InstallationEntry, Kind, Result, UiBefore,
};
pub const PRIMARY_NAME: &str = "GitPoulpi";
pub const INSTALL_ID_ENV: &str = "GITPOULPI_INSTALL_ID";
pub const ENV_OVERRIDE_ENV: &str = "GITPOULPI_ENV";
pub const DEV_LOGO_COLOR: &str = "sun";
pub const SEED_COLORS: [&str; 5] = ["teal", "orange", "magenta", "green", "ocean"];
pub trait InstallFs {
fn canonicalize(&self, path: &str) -> Option<String>;
fn is_file(&self, path: &str) -> bool;
fn is_dir(&self, path: &str) -> bool;
fn read_to_string(&self, path: &str) -> Option<String>;
}
pub struct RealFs;
impl InstallFs for RealFs {
fn canonicalize(&self, path: &str) -> Option<String> {
std::fs::canonicalize(path)
.ok()
.map(|p| p.to_string_lossy().into_owned())
}
fn is_file(&self, path: &str) -> bool {
Path::new(path).is_file()
}
fn is_dir(&self, path: &str) -> bool {
Path::new(path).is_dir()
}
fn read_to_string(&self, path: &str) -> Option<String> {
std::fs::read_to_string(path).ok()
}
}
pub struct IdentityEnv<'a> {
pub windows: bool,
pub host_target: String,
pub cargo_home: Option<String>,
pub install_id: Option<String>,
pub env_override: Option<String>,
pub fs: &'a dyn InstallFs,
}
impl<'a> IdentityEnv<'a> {
pub fn real(fs: &'a RealFs) -> Self {
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
Self {
windows: cfg!(windows),
host_target: crate::release::host_target(),
cargo_home: var("CARGO_HOME").or_else(|| {
crate::home_dir().map(|h| h.join(".cargo").to_string_lossy().into_owned())
}),
install_id: var(INSTALL_ID_ENV),
env_override: var(ENV_OVERRIDE_ENV),
fs,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
pub id: String,
pub kind: Kind,
pub root: String,
pub channel: Option<InstallChannel>,
}
impl Identity {
pub fn short(&self) -> String {
short_id(&self.id)
}
}
pub fn fnv1a64(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| {
(h ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)
})
}
pub fn short_id(id: &str) -> String {
let hex = if id.len() == 16 && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
id.to_string()
} else {
format!("{:016x}", fnv1a64(id.as_bytes()))
};
format!("i{}", &hex[..8])
}
pub fn sanitize(text: &str) -> String {
let mut out = String::new();
for c in text.trim().chars() {
let c = if c.is_ascii_alphanumeric() || c == '_' {
c.to_ascii_lowercase()
} else {
'-'
};
if c == '-' && out.ends_with('-') {
continue;
}
out.push(c);
}
out.trim_matches('-').chars().take(48).collect()
}
fn sep(windows: bool) -> char {
if windows {
'\\'
} else {
'/'
}
}
fn tidy(path: &str, windows: bool) -> String {
let path = if let Some(rest) = path.strip_prefix(r"\\?\UNC\") {
format!(r"\\{rest}")
} else {
path.strip_prefix(r"\\?\").unwrap_or(path).to_string()
};
let mut path = if windows {
path.replace('/', "\\")
} else {
path
};
let s = sep(windows);
while path.len() > 1 && path.ends_with(s) {
if windows && path.len() == 3 && path.as_bytes()[1] == b':' {
break;
}
path.pop();
}
path
}
fn norm(path: &str, windows: bool) -> String {
let t = tidy(path, windows);
if windows {
t.to_lowercase()
} else {
t
}
}
fn parent(path: &str, windows: bool) -> Option<String> {
let i = path.rfind(sep(windows))?;
Some(if i == 0 {
sep(windows).to_string()
} else {
path[..i].to_string()
})
}
fn file_name(path: &str, windows: bool) -> &str {
path.rsplit(sep(windows)).next().unwrap_or(path)
}
fn join(dir: &str, name: &str, windows: bool) -> String {
if dir.ends_with(sep(windows)) {
format!("{dir}{name}")
} else {
format!("{dir}{}{name}", sep(windows))
}
}
fn same_text(a: &str, b: &str, windows: bool) -> bool {
if windows {
a.eq_ignore_ascii_case(b)
} else {
a == b
}
}
fn checkout_root(exe: &str, env: &IdentityEnv) -> Option<String> {
let w = env.windows;
let profile = parent(exe, w)?;
let target = parent(&profile, w)?;
if !same_text(file_name(&target, w), "target", w) {
return None;
}
let root = parent(&target, w)?;
let crates = join(&root, "crates", w);
(env.fs.is_file(&join(&root, "Cargo.toml", w))
&& env.fs.is_dir(&join(&crates, "gitpoulpi-tui", w)))
.then_some(root)
}
fn scoop_current(dir: &str, env: &IdentityEnv) -> Option<String> {
let w = env.windows;
let app = parent(dir, w)?;
let apps = parent(&app, w)?;
if !same_text(file_name(&apps, w), "apps", w) {
return None;
}
let current = join(&app, "current", w);
env.fs.is_dir(¤t).then_some(current)
}
fn cellar_formula(dir: &str, env: &IdentityEnv) -> Option<String> {
let w = env.windows;
if file_name(dir, w) != "bin" {
return None;
}
let version = parent(dir, w)?;
let formula = parent(&version, w)?;
let cellar = parent(&formula, w)?;
(file_name(&cellar, w) == "Cellar").then_some(formula)
}
fn hashed(kind: Kind, root: String, channel: Option<InstallChannel>, w: bool) -> Identity {
Identity {
id: format!("{:016x}", fnv1a64(norm(&root, w).as_bytes())),
kind,
root,
channel,
}
}
pub fn identify(exe: &Path, env: &IdentityEnv) -> Identity {
let w = env.windows;
let given = exe.to_string_lossy();
let canonical = env
.fs
.canonicalize(&given)
.unwrap_or_else(|| given.into_owned());
let exe = tidy(&canonical, w);
let dir = parent(&exe, w).unwrap_or_default();
if let Some(name) = env
.install_id
.as_deref()
.map(sanitize)
.filter(|n| !n.is_empty())
{
return Identity {
id: format!("p-{name}"),
kind: Kind::Pinned,
root: dir,
channel: None,
};
}
if let Some(root) = checkout_root(&exe, env) {
return hashed(Kind::Dev, root, None, w);
}
let marker = env
.fs
.read_to_string(&join(&dir, MARKER_FILE, w))
.and_then(|text| Marker::parse(&text))
.filter(|m| m.target == env.host_target);
if let Some(marker) = marker {
let root = if w {
scoop_current(&dir, env)
} else {
cellar_formula(&dir, env)
}
.unwrap_or_else(|| dir.clone());
return hashed(Kind::Install, root, marker.channel, w);
}
let cargo_bin = env.cargo_home.as_deref().map(|h| join(h, "bin", w));
if cargo_bin.is_some_and(|bin| norm(&bin, w) == norm(&dir, w)) {
return hashed(Kind::Cargo, dir, None, w);
}
hashed(Kind::Portable, dir, None, w)
}
pub fn environment(config: &Config, identity: &Identity, env: &IdentityEnv) -> String {
let usable = |t: &str| Some(sanitize(t)).filter(|s| !s.is_empty());
env.env_override
.as_deref()
.and_then(usable)
.or_else(|| {
config
.installation
.settings
.get(&identity.id)
.and_then(|e| usable(&e.env))
})
.unwrap_or_else(|| sanitize(&identity.id))
}
pub fn label(kind: Kind, channel: Option<InstallChannel>) -> &'static str {
match kind {
Kind::Dev => "dev",
Kind::Cargo => "cargo",
Kind::Pinned => "pinned",
Kind::Portable => "portable",
Kind::Install => match channel {
None | Some(InstallChannel::Archive) => "portable",
Some(InstallChannel::InnoUser) => "per-user",
Some(InstallChannel::InnoMachine) => "all users",
Some(InstallChannel::Choco | InstallChannel::ChocoInternal) => "Chocolatey",
Some(InstallChannel::Winget) => "winget",
Some(InstallChannel::Scoop) => "Scoop",
Some(InstallChannel::Msi) => "MSI",
Some(InstallChannel::Homebrew) => "Homebrew",
Some(InstallChannel::Apt) => "apt",
Some(InstallChannel::Aur) => "AUR",
Some(InstallChannel::Docker) => "Docker",
},
}
}
pub fn default_name(kind: Kind, channel: Option<InstallChannel>) -> String {
format!("{PRIMARY_NAME} ({})", label(kind, channel))
}
pub fn unique_name(base: &str, taken: &[String]) -> String {
let key = |s: &str| s.trim().to_lowercase();
let taken: BTreeSet<String> = taken.iter().map(|t| key(t)).collect();
if !taken.contains(&key(base)) {
return base.to_string();
}
(2..)
.map(|n| format!("{base} {n}"))
.find(|c| !taken.contains(&key(c)))
.expect("an unbounded range always yields")
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum NameError {
#[error("the name is empty")]
Empty,
#[error("the name is longer than 64 characters")]
TooLong,
#[error("the name contains {0:?}, which a launcher file name cannot hold")]
BadChar(char),
#[error("the name ends with a dot or a space")]
TrailingDotOrSpace,
#[error("{0} is a reserved device name on Windows")]
Reserved(String),
}
pub fn validate_name(name: &str) -> std::result::Result<(), NameError> {
if name.is_empty() {
return Err(NameError::Empty);
}
if name.chars().count() > 64 {
return Err(NameError::TooLong);
}
if let Some(c) = name
.chars()
.find(|c| c.is_control() || "\\/:*?\"<>|".contains(*c))
{
return Err(NameError::BadChar(c));
}
if name.ends_with('.') || name.ends_with(' ') {
return Err(NameError::TrailingDotOrSpace);
}
let stem = name.split('.').next().unwrap_or(name).trim_end();
let upper = stem.to_ascii_uppercase();
let numbered = |p: &str| {
upper
.strip_prefix(p)
.is_some_and(|n| n.len() == 1 && matches!(n.as_bytes()[0], b'1'..=b'9'))
};
if ["CON", "PRN", "AUX", "NUL"].contains(&upper.as_str()) || numbered("COM") || numbered("LPT")
{
return Err(NameError::Reserved(stem.to_string()));
}
Ok(())
}
pub fn major_minor(version: &str) -> String {
let mut parts = version.split('.').map(|p| {
let digits: String = p.chars().take_while(char::is_ascii_digit).collect();
if digits.is_empty() {
"0".to_string()
} else {
digits
}
});
let major = parts.next().unwrap_or_else(|| "0".to_string());
format!(
"{major}.{}",
parts.next().unwrap_or_else(|| "0".to_string())
)
}
pub fn launcher_name(base: &str, with_version: bool, version: &str) -> String {
if !with_version {
return base.to_string();
}
let v = major_minor(version);
match base.strip_prefix(PRIMARY_NAME) {
Some(rest) if !rest.chars().next().is_some_and(char::is_alphanumeric) => {
format!("{PRIMARY_NAME} {v}{rest}")
}
_ => format!("{base} {v}"),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Effective {
pub primary: bool,
pub name: String,
pub name_with_version: bool,
pub logo_color: String,
pub command_alias: String,
pub command_alias_add: String,
pub folder_menu_submenu: String,
pub env: String,
pub mcp_bind: String,
}
fn effective_from(
config: &Config,
id: &str,
kind: Kind,
channel: Option<InstallChannel>,
) -> Effective {
let entry = config.installation.settings.get(id);
let blank = InstallationEntry::default();
let e = entry.unwrap_or(&blank);
let primary = config.installation.primary.as_deref() == Some(id);
let pick = |own: &str, legacy: &str, default: &str| {
if !own.is_empty() {
own.to_string()
} else if primary && !legacy.is_empty() {
legacy.to_string()
} else {
default.to_string()
}
};
let ui_alias = |name: &str| {
if claimed_by_another(config, id, name) {
String::new()
} else {
name.to_string()
}
};
let kind_color = if kind == Kind::Dev {
DEV_LOGO_COLOR
} else {
""
};
Effective {
primary,
name: if primary {
PRIMARY_NAME.to_string()
} else if e.name.is_empty() {
default_name(kind, channel)
} else {
e.name.clone()
},
name_with_version: e.name_with_version,
logo_color: pick(&e.logo_color, &config.ui.logo_color, kind_color),
command_alias: pick(&e.command_alias, &ui_alias(&config.ui.command_alias), ""),
command_alias_add: pick(
&e.command_alias_add,
&ui_alias(&config.ui.command_alias_add),
"",
),
folder_menu_submenu: e.folder_menu_submenu.clone(),
env: if e.env.trim().is_empty() {
id.to_string()
} else {
e.env.trim().to_string()
},
mcp_bind: pick(&e.mcp_bind, "", &config.mcp.bind),
}
}
pub fn effective(config: &Config, identity: &Identity) -> Effective {
let channel = identity.channel.or_else(|| {
config
.installation
.settings
.get(&identity.id)
.and_then(|e| InstallChannel::parse(&e.channel))
});
effective_from(config, &identity.id, identity.kind, channel)
}
pub fn effective_of(config: &Config, id: &str) -> Option<Effective> {
let e = config.installation.settings.get(id)?;
Some(effective_from(
config,
id,
e.kind,
InstallChannel::parse(&e.channel),
))
}
pub fn alias_claims(config: &Config) -> Vec<(String, String)> {
let mut claims: Vec<(String, String)> = Vec::new();
let mut claim = |name: &str, id: &str| {
let name = name.trim().to_ascii_lowercase();
if !name.is_empty() && !claims.iter().any(|(n, _)| *n == name) {
claims.push((name, id.to_string()));
}
};
for (id, e) in &config.installation.settings {
claim(&e.command_alias, id);
claim(&e.command_alias_add, id);
}
if let Some(primary) = config.installation.primary.as_deref() {
claim(&config.ui.command_alias, primary);
claim(&config.ui.command_alias_add, primary);
}
claims
}
fn claimed_by_another(config: &Config, id: &str, name: &str) -> bool {
!name.is_empty()
&& config.installation.settings.iter().any(|(other, e)| {
other != id
&& [&e.command_alias, &e.command_alias_add]
.iter()
.any(|n| n.eq_ignore_ascii_case(name))
})
}
pub trait AliasEvidence {
fn target_of(&self, alias: &str) -> Option<String>;
}
fn new_entry(identity: &Identity, name: String) -> InstallationEntry {
InstallationEntry {
path: identity.root.clone(),
kind: identity.kind,
channel: identity
.channel
.map(|c| c.as_str().to_string())
.unwrap_or_default(),
name,
..InstallationEntry::default()
}
}
pub fn seed(
config: &Config,
identity: &Identity,
env: &IdentityEnv,
aliases: &dyn AliasEvidence,
is_live: &dyn Fn(&InstallationEntry) -> bool,
) -> Option<InstallationEntry> {
let w = env.windows;
if let Some(existing) = config.installation.settings.get(&identity.id) {
let mut updated = existing.clone();
if norm(&existing.path, w) != norm(&identity.root, w) {
updated.path = identity.root.clone();
}
if let Some(c) = identity.channel {
updated.channel = c.as_str().to_string();
}
updated.kind = identity.kind;
return (updated != *existing).then_some(updated);
}
let others: Vec<(&String, &InstallationEntry)> = config
.installation
.settings
.iter()
.filter(|(id, e)| **id != identity.id && is_live(e))
.collect();
let taken_names: Vec<String> = others
.iter()
.filter_map(|(id, _)| effective_of(config, id))
.map(|e| e.name)
.collect();
let worn: Vec<String> = others
.iter()
.filter_map(|(id, _)| effective_of(config, id))
.map(|e| e.logo_color)
.collect();
let mut entry = new_entry(
identity,
unique_name(&default_name(identity.kind, identity.channel), &taken_names),
);
entry.logo_color = if identity.kind == Kind::Dev {
DEV_LOGO_COLOR.to_string()
} else if !worn.contains(&config.ui.logo_color) {
config.ui.logo_color.clone()
} else {
SEED_COLORS
.iter()
.find(|c| !worn.iter().any(|w| w == **c))
.unwrap_or(&SEED_COLORS[0])
.to_string()
};
let mine = |alias: &str| {
!alias.is_empty()
&& aliases
.target_of(alias)
.is_some_and(|t| identify(Path::new(&t), env).id == identity.id)
};
if mine(&config.ui.command_alias) {
entry.command_alias = config.ui.command_alias.clone();
}
if mine(&config.ui.command_alias_add) {
entry.command_alias_add = config.ui.command_alias_add.clone();
}
Some(entry)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UiLook {
pub logo_color: String,
pub command_alias: String,
pub command_alias_add: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PrimaryHandover {
pub installation: InstallationConfig,
pub ui: Option<UiLook>,
pub ui_restore: Option<UiBefore>,
pub demoted: Option<String>,
pub promoted: Option<String>,
}
fn other_names(config: &Config, except: &str) -> Vec<String> {
config
.installation
.settings
.keys()
.filter(|id| id.as_str() != except)
.filter_map(|id| effective_of(config, id))
.map(|e| e.name)
.collect()
}
fn freeze_own_values(config: &Config, inst: &mut InstallationConfig, id: &str) {
let eff = effective_of(config, id)
.unwrap_or_else(|| effective_from(config, id, Kind::default(), None));
let entry = inst.settings.entry(id.to_string()).or_default();
entry.logo_color = eff.logo_color;
entry.command_alias = eff.command_alias;
entry.command_alias_add = eff.command_alias_add;
if entry.name.is_empty() {
let channel = InstallChannel::parse(&entry.channel);
entry.name = unique_name(&default_name(entry.kind, channel), &other_names(config, id));
}
}
pub fn plan_primary(config: &Config, new: &Identity) -> Option<PrimaryHandover> {
if config.installation.primary.as_deref() == Some(new.id.as_str()) {
return None;
}
let mut inst = config.installation.clone();
let wanted = effective(config, new);
let demoted = config.installation.primary.clone();
let own = config.installation.settings.get(&new.id);
let inherit = |own: Option<&str>, wanted: String, legacy: &str| match own {
Some(v) if !v.is_empty() => wanted,
_ if demoted.is_none() => legacy.to_string(),
_ => wanted,
};
let inherit_alias = |own: Option<&str>, wanted: String, legacy: &str| {
let name = inherit(own, wanted, legacy);
if claimed_by_another(config, &new.id, &name) {
String::new()
} else {
name
}
};
if let Some(old) = &demoted {
freeze_own_values(config, &mut inst, old);
}
let channel = new.channel;
let name = unique_name(
&default_name(new.kind, channel),
&other_names(config, &new.id),
);
let entry = inst
.settings
.entry(new.id.clone())
.or_insert_with(|| new_entry(new, name));
entry.logo_color.clear();
entry.command_alias.clear();
entry.command_alias_add.clear();
inst.primary = Some(new.id.clone());
if demoted.is_none() && inst.ui_before.is_none() {
inst.ui_before = Some(UiBefore {
logo_color: Some(config.ui.logo_color.clone()),
command_alias: Some(config.ui.command_alias.clone()),
command_alias_add: Some(config.ui.command_alias_add.clone()),
});
}
Some(PrimaryHandover {
ui_restore: None,
installation: inst,
ui: Some(UiLook {
logo_color: inherit(
own.map(|e| e.logo_color.as_str()),
wanted.logo_color,
&config.ui.logo_color,
),
command_alias: inherit_alias(
own.map(|e| e.command_alias.as_str()),
wanted.command_alias,
&config.ui.command_alias,
),
command_alias_add: inherit_alias(
own.map(|e| e.command_alias_add.as_str()),
wanted.command_alias_add,
&config.ui.command_alias_add,
),
}),
demoted,
promoted: Some(new.id.clone()),
})
}
pub fn plan_resign(config: &Config, id: &str) -> Option<PrimaryHandover> {
if config.installation.primary.as_deref() != Some(id) {
return None;
}
let mut inst = config.installation.clone();
freeze_own_values(config, &mut inst, id);
inst.primary = None;
let ui_restore = inst.ui_before.take();
Some(PrimaryHandover {
installation: inst,
ui: None,
ui_restore,
demoted: Some(id.to_string()),
promoted: None,
})
}
type UiAction = (&'static str, Option<String>);
fn read_raw(path: &Path) -> Result<String> {
Ok(if path.exists() {
std::fs::read_to_string(path)?
} else {
String::new()
})
}
fn parse_document(raw: &str) -> Result<toml::Value> {
let mut document = if raw.trim().is_empty() {
toml::Value::Table(toml::map::Map::new())
} else {
toml::from_str(raw)?
};
AiConfig::migrate_document(&mut document);
Ok(document)
}
fn put_installation(document: &mut toml::Value, installation: &InstallationConfig) -> Result<()> {
if installation.is_empty() {
remove_dotted(document, "installation");
Ok(())
} else {
insert_dotted(
document,
"installation",
toml::Value::try_from(installation)?,
)
}
}
fn validate(document: &toml::Value) -> Result<()> {
let _: Config = document
.clone()
.try_into()
.map_err(|err: toml::de::Error| Error::BadValue {
key: "installation".to_string(),
value: "<table>".to_string(),
expected: err.to_string(),
})?;
Ok(())
}
fn write_text(path: &Path, raw: &str, text: &str) -> Result<()> {
if text == raw {
return Ok(());
}
if let Some(parent) = path.parent() {
secure_fs::create_private_dir_all(parent)?;
}
secure_fs::write_private(path, text.as_bytes())?;
Ok(())
}
fn splice(
raw: &str,
document: &toml::Value,
installation: &InstallationConfig,
ui: &[UiAction],
) -> Result<String> {
let table = if installation.is_empty() {
String::new()
} else {
let mut root = toml::map::Map::new();
root.insert(
"installation".to_string(),
toml::Value::try_from(installation)?,
);
toml::to_string(&toml::Value::Table(root))?
};
let mut text = text_edit::replace_table(raw, "installation", &table);
for (key, value) in ui {
text = text.and_then(|t| match value {
Some(v) => {
let quoted = toml::Value::String(v.clone()).to_string();
text_edit::set_key(&t, "ui", key, "ed)
}
None => text_edit::remove_key(&t, "ui", key),
});
}
match text {
Some(t) => Ok(t),
None => Ok(toml::to_string_pretty(document)?),
}
}
pub fn set_installation_in_file(
path: &Path,
edit: impl FnOnce(&mut InstallationConfig),
) -> Result<()> {
let raw = read_raw(path)?;
let mut document = parse_document(&raw)?;
let mut installation: InstallationConfig = match document.get("installation") {
Some(v) => v.clone().try_into()?,
None => InstallationConfig::default(),
};
edit(&mut installation);
put_installation(&mut document, &installation)?;
validate(&document)?;
let text = splice(&raw, &document, &installation, &[])?;
write_text(path, &raw, &text)
}
fn apply_handover(
path: &Path,
plan: impl FnOnce(&Config) -> Option<PrimaryHandover>,
) -> Result<Option<PrimaryHandover>> {
let raw = read_raw(path)?;
let mut document = parse_document(&raw)?;
let config = Config::from_toml_str(&toml::to_string(&document)?)?.0;
let Some(mut handover) = plan(&config) else {
return Ok(None);
};
let present = |key: &str| document.get("ui").and_then(|u| u.get(key)).is_some();
if config.installation.ui_before.is_none() {
if let Some(before) = handover.installation.ui_before.as_mut() {
for (key, slot) in [
("logo_color", &mut before.logo_color),
("command_alias", &mut before.command_alias),
("command_alias_add", &mut before.command_alias_add),
] {
if !present(key) {
*slot = None;
}
}
}
}
let mut actions: Vec<UiAction> = Vec::new();
let current = [
("logo_color", &config.ui.logo_color),
("command_alias", &config.ui.command_alias),
("command_alias_add", &config.ui.command_alias_add),
];
if let Some(ui) = &handover.ui {
let wanted = [&ui.logo_color, &ui.command_alias, &ui.command_alias_add];
for ((key, now), want) in current.iter().zip(wanted) {
if now != &want {
actions.push((key, Some(want.clone())));
}
}
}
if let Some(before) = &handover.ui_restore {
let old = [
&before.logo_color,
&before.command_alias,
&before.command_alias_add,
];
for ((key, now), old) in current.iter().zip(old) {
match old {
Some(v) if v != *now || !present(key) => actions.push((key, Some(v.clone()))),
None if present(key) => actions.push((key, None)),
_ => {}
}
}
}
put_installation(&mut document, &handover.installation)?;
for (key, value) in &actions {
let dotted = format!("ui.{key}");
match value {
Some(v) => insert_dotted(&mut document, &dotted, toml::Value::String(v.clone()))?,
None => remove_dotted(&mut document, &dotted),
}
}
validate(&document)?;
let text = splice(&raw, &document, &handover.installation, &actions)?;
write_text(path, &raw, &text)?;
Ok(Some(handover))
}
pub fn become_primary_in_file(path: &Path, new: &Identity) -> Result<Option<PrimaryHandover>> {
apply_handover(path, |config| plan_primary(config, new))
}
pub fn resign_primary_in_file(path: &Path, id: &str) -> Result<Option<PrimaryHandover>> {
apply_handover(path, |config| plan_resign(config, id))
}
#[derive(Debug, Clone)]
pub struct Current {
pub identity: Identity,
pub config: Config,
pub effective: Effective,
pub environment: String,
pub ctx: crate::desktop::InstallCtx,
pub config_file: Option<std::path::PathBuf>,
}
struct DiskAliases(crate::desktop::alias::Env);
impl AliasEvidence for DiskAliases {
fn target_of(&self, alias: &str) -> Option<String> {
crate::desktop::alias::target_of(&self.0, alias).map(|p| p.to_string_lossy().into_owned())
}
}
fn persist_seed(file: &Path, identity: &Identity, entry: &InstallationEntry) -> bool {
if identity.kind == Kind::Pinned {
return true;
}
let id = identity.id.clone();
let stored = entry.clone();
set_installation_in_file(file, |i| {
i.settings.insert(id, stored);
})
.is_ok()
}
pub fn current() -> &'static Current {
static CURRENT: std::sync::OnceLock<Current> = std::sync::OnceLock::new();
CURRENT.get_or_init(|| {
let fs = RealFs;
let env = IdentityEnv::real(&fs);
let exe = std::env::current_exe().unwrap_or_default();
let identity = identify(&exe, &env);
let config_file = crate::ConfigPaths::discover().map(|p| p.config_file());
let mut config = config_file
.as_deref()
.and_then(|f| Config::load(f).ok())
.unwrap_or_default();
let live = |e: &InstallationEntry| !e.path.is_empty() && Path::new(&e.path).exists();
if let Some(home) = crate::home_dir() {
let lookup = |k: &str| std::env::var(k).ok();
let aliases = DiskAliases(crate::desktop::alias::Env::discover(
crate::open_in::Os::current(),
&lookup,
&home,
&exe,
));
if let (Some(entry), Some(file)) = (
seed(&config, &identity, &env, &aliases, &live),
config_file.as_deref(),
) {
if persist_seed(file, &identity, &entry) {
config
.installation
.settings
.insert(identity.id.clone(), entry);
}
}
}
let effective = effective(&config, &identity);
let environment = environment(&config, &identity, &env);
let ctx = crate::desktop::InstallCtx::from_config(&config, &identity, &|path| {
!path.is_empty() && Path::new(path).exists()
});
Current {
identity,
config,
effective,
environment,
ctx,
config_file,
}
})
}
pub fn path_keep(cur: &Current, aliases: &crate::desktop::alias::Env) -> Vec<std::path::PathBuf> {
let mut keep = other_live_paths(&cur.config, &cur.identity.id);
if crate::desktop::alias::others_have_aliases(aliases) {
keep.push(aliases.bin_dir.clone());
}
keep
}
pub fn other_live_paths(config: &Config, id: &str) -> Vec<std::path::PathBuf> {
config
.installation
.settings
.iter()
.filter(|(other, e)| other.as_str() != id && !e.path.is_empty())
.filter(|(_, e)| Path::new(&e.path).exists())
.map(|(_, e)| std::path::PathBuf::from(&e.path))
.collect()
}
#[cfg(test)]
mod tests;
mod text_edit;