pub mod alias;
pub mod folder_menu;
pub mod icons;
mod linux;
mod macos;
pub mod owner;
pub mod path;
pub mod registry;
pub mod terminals;
mod windows;
use std::path::{Path, PathBuf};
pub use icons::IconSet;
pub use linux::{entry_text, entry_text_with_action, exec_quote};
pub use macos::sh_quote;
pub use windows::quote_arg;
use crate::open_in::Os;
pub const MARKER: &str = "X-GitPoulpi=1";
pub const OWNER_TAG: &str = "X-GitPoulpi-Install";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KnownInstall {
pub id: String,
pub exists: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallCtx {
pub id: String,
pub short: String,
pub name: String,
pub primary: Option<String>,
pub known: Vec<KnownInstall>,
pub alias_claims: Vec<(String, String)>,
}
impl InstallCtx {
pub fn sole(identity: &crate::installation::Identity) -> Self {
Self {
id: identity.id.clone(),
short: identity.short(),
name: crate::installation::PRIMARY_NAME.to_string(),
primary: Some(identity.id.clone()),
known: Vec::new(),
alias_claims: Vec::new(),
}
}
pub fn legacy() -> Self {
Self::sole(&crate::installation::Identity {
id: String::new(),
kind: crate::Kind::default(),
root: String::new(),
channel: None,
})
}
pub fn legacy_ref() -> &'static InstallCtx {
static LEGACY: std::sync::OnceLock<InstallCtx> = std::sync::OnceLock::new();
LEGACY.get_or_init(InstallCtx::legacy)
}
pub fn from_config(
config: &crate::Config,
identity: &crate::installation::Identity,
exists: &dyn Fn(&str) -> bool,
) -> Self {
let eff = crate::installation::effective(config, identity);
Self {
id: identity.id.clone(),
short: identity.short(),
name: eff.name,
primary: config.installation.primary.clone(),
known: config
.installation
.settings
.iter()
.map(|(id, e)| KnownInstall {
id: id.clone(),
exists: exists(&e.path),
})
.collect(),
alias_claims: crate::installation::alias_claims(config),
}
}
pub fn alias_claimed_by(&self, name: &str) -> Option<&str> {
self.alias_claims
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, id)| id.as_str())
}
pub fn is_primary(&self) -> bool {
self.primary.as_deref() == Some(self.id.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Place {
Launcher,
Desktop,
StartMenu,
}
impl Place {
pub fn as_str(self) -> &'static str {
match self {
Place::Launcher => "launcher",
Place::Desktop => "desktop",
Place::StartMenu => "startmenu",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"launcher" => Some(Place::Launcher),
"desktop" => Some(Place::Desktop),
"startmenu" => Some(Place::StartMenu),
_ => None,
}
}
pub fn for_os(os: Os) -> &'static [Place] {
match os {
Os::Linux => &[Place::Launcher, Place::Desktop],
Os::Windows => &[Place::StartMenu, Place::Desktop],
Os::Macos => &[Place::Launcher],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
NotInstalled,
Installed,
Outdated,
Foreign,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Status {
pub state: State,
pub icon_stale: bool,
}
#[derive(Debug, Clone, Default)]
pub struct Dirs {
pub applications: PathBuf,
pub icon_root: PathBuf,
pub desktop: Option<PathBuf>,
pub start_menu: Option<PathBuf>,
pub mac_apps: PathBuf,
pub assets: PathBuf,
pub taskbar_pinned: Option<PathBuf>,
pub implicit_pinned: Option<PathBuf>,
}
impl Dirs {
pub fn discover(os: Os, env: &dyn Fn(&str) -> Option<String>, home: &Path) -> Dirs {
let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
match os {
Os::Linux => {
let data = var("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"));
let config = var("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config"));
Dirs {
applications: data.join("applications"),
icon_root: data.join("icons/hicolor"),
desktop: linux::desktop_dir(home, &config),
..Dirs::default()
}
}
Os::Windows => {
let profile = var("USERPROFILE").unwrap_or_else(|| home.to_path_buf());
let one_drive = profile.join("OneDrive").join("Desktop");
let desktop = if one_drive.is_dir() {
one_drive
} else {
profile.join("Desktop")
};
let appdata = var("APPDATA").unwrap_or_else(|| profile.join("AppData/Roaming"));
Dirs {
desktop: Some(desktop),
start_menu: Some(appdata.join("Microsoft/Windows/Start Menu/Programs")),
taskbar_pinned: Some(
appdata
.join("Microsoft/Internet Explorer/Quick Launch/User Pinned/TaskBar"),
),
implicit_pinned: Some(appdata.join(
"Microsoft/Internet Explorer/Quick Launch/User Pinned/ImplicitAppShortcuts",
)),
assets: var("LOCALAPPDATA")
.unwrap_or_else(|| profile.join("AppData/Local"))
.join("GitPoulpi"),
..Dirs::default()
}
}
Os::Macos => Dirs {
mac_apps: home.join("Applications"),
..Dirs::default()
},
}
}
pub fn places(&self, os: Os) -> Vec<Place> {
Place::for_os(os)
.iter()
.copied()
.filter(|p| *p != Place::Desktop || self.desktop.is_some())
.collect()
}
}
#[derive(Debug, Clone, Copy)]
pub struct Request<'a> {
pub os: Os,
pub exe: &'a Path,
pub terminal: &'a str,
pub terminal_exe: Option<&'a Path>,
pub launch_exe: Option<&'a Path>,
pub newest: bool,
pub icons: &'a IconSet,
pub ctx: &'a InstallCtx,
pub refresh_icon_cache: bool,
}
pub fn status(place: Place, dirs: &Dirs, req: &Request) -> Status {
if req.newest && req.os != Os::Windows {
let mut first = None;
for (exe, launch) in variants(req) {
let r = Request {
exe: &exe,
launch_exe: launch.as_deref(),
..*req
};
let st = status_of(place, dirs, &r);
if st.state == State::Installed {
return st;
}
first.get_or_insert(st);
}
return first.unwrap_or_else(|| status_of(place, dirs, req));
}
status_of(place, dirs, req)
}
fn status_of(place: Place, dirs: &Dirs, req: &Request) -> Status {
match req.os {
Os::Linux => linux::status(place, dirs, req),
Os::Windows => windows::status(place, dirs, req),
Os::Macos => macos::status(place, dirs, req),
}
}
fn variants(req: &Request) -> Vec<(PathBuf, Option<PathBuf>)> {
let exes = crate::dev_mode::build_variants(req.exe);
let launches = req.launch_exe.map(crate::dev_mode::build_variants);
exes.into_iter()
.enumerate()
.map(|(i, exe)| {
let launch = match (&launches, req.launch_exe) {
(Some(l), _) if l.len() == 2 => Some(l[i.min(1)].clone()),
(_, l) => l.map(Path::to_path_buf),
};
(exe, launch)
})
.collect()
}
fn newest_paths(req: &Request) -> (PathBuf, Option<PathBuf>) {
(
crate::dev_mode::newest_build(req.exe),
req.launch_exe.map(crate::dev_mode::newest_build),
)
}
pub fn install(place: Place, dirs: &Dirs, req: &Request) -> Result<PathBuf, String> {
if req.newest {
let (exe, launch) = newest_paths(req);
let r = Request {
exe: &exe,
launch_exe: launch.as_deref(),
..*req
};
return install_of(place, dirs, &r);
}
install_of(place, dirs, req)
}
fn install_of(place: Place, dirs: &Dirs, req: &Request) -> Result<PathBuf, String> {
match req.os {
Os::Linux => linux::install(place, dirs, req),
Os::Windows => windows::install(place, dirs, req),
Os::Macos => macos::install(place, dirs, req),
}
}
pub fn sync_pinned(dirs: &Dirs, req: &Request) -> bool {
if req.os != Os::Windows {
return false;
}
if req.newest {
let (exe, launch) = newest_paths(req);
let r = Request {
exe: &exe,
launch_exe: launch.as_deref(),
..*req
};
return windows::sync_pinned_args(dirs, &r);
}
windows::sync_pinned_args(dirs, req)
}
pub fn remove(place: Place, dirs: &Dirs, os: Os, ctx: &InstallCtx) -> Result<bool, String> {
match os {
Os::Linux => linux::remove(place, dirs, ctx),
Os::Windows => windows::remove(place, dirs, ctx),
Os::Macos => macos::remove(place, dirs, ctx),
}
}
pub fn refresh_icon(dirs: &Dirs, req: &Request) -> Result<(), String> {
match req.os {
Os::Linux => linux::write_icon(dirs, req),
Os::Windows => windows::refresh_icon(dirs, req),
Os::Macos => {
macos::write_icon(dirs, req)?;
macos::touch_bundle(dirs, req.ctx);
Ok(())
}
}
}
pub fn ico_path(dirs: &Dirs, icons: &IconSet) -> PathBuf {
windows::ico_path(dirs, icons)
}
pub fn ico_path_for(dirs: &Dirs, icons: &IconSet, ctx: &InstallCtx) -> PathBuf {
windows::ico_path_for(dirs, icons, ctx)
}
pub fn release_icons(dirs: &Dirs, os: Os, ctx: &InstallCtx) {
match os {
Os::Windows => windows::release_icons(dirs, ctx),
Os::Linux => linux::release_icons(dirs, ctx),
Os::Macos => {}
}
}
pub fn ensure_ico_for(dirs: &Dirs, icons: &IconSet, ctx: &InstallCtx) -> Option<PathBuf> {
windows::ensure_ico(dirs, icons, ctx)
}
pub fn hand_over_shortcuts(dirs: &Dirs, os: Os, old: &InstallCtx) -> Result<Vec<PathBuf>, String> {
match os {
Os::Windows => windows::hand_over(dirs, old),
Os::Linux => linux::hand_over(dirs, old),
Os::Macos => Ok(Vec::new()),
}
}
pub fn rename_shortcuts(
dirs: &Dirs,
os: Os,
from: &InstallCtx,
to: &InstallCtx,
) -> Result<Vec<PathBuf>, String> {
match os {
Os::Windows => windows::rename(dirs, from, to),
Os::Linux => linux::rename_entries(dirs, from, to),
Os::Macos => Ok(Vec::new()),
}
}
pub fn ensure_ico(dirs: &Dirs, icons: &IconSet) -> Option<PathBuf> {
windows::ensure_ico(dirs, icons, InstallCtx::legacy_ref())
}
fn write_file(path: &Path, bytes: &[u8], executable: bool) -> Result<(), String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
std::fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display()))?;
#[cfg(unix)]
if executable {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
}
#[cfg(not(unix))]
let _ = executable;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn linux_dirs_honour_xdg_data_home_and_need_a_real_desktop_folder() {
let tmp = tempfile::tempdir().unwrap();
let env =
|k: &str| (k == "XDG_DATA_HOME").then(|| tmp.path().join("data").display().to_string());
let d = Dirs::discover(Os::Linux, &env, tmp.path());
assert_eq!(d.applications, tmp.path().join("data/applications"));
assert_eq!(d.icon_root, tmp.path().join("data/icons/hicolor"));
assert!(d.desktop.is_none());
assert_eq!(d.places(Os::Linux), [Place::Launcher]);
std::fs::create_dir(tmp.path().join("Desktop")).unwrap();
let d = Dirs::discover(Os::Linux, &env, tmp.path());
assert_eq!(d.places(Os::Linux), [Place::Launcher, Place::Desktop]);
}
#[test]
fn windows_dirs_follow_appdata_and_the_profile() {
let env = |k: &str| match k {
"USERPROFILE" => Some("/u/me".to_string()),
"APPDATA" => Some("/u/me/AppData/Roaming".to_string()),
_ => None,
};
let d = Dirs::discover(Os::Windows, &env, Path::new("/h"));
assert_eq!(
d.start_menu.unwrap(),
Path::new("/u/me/AppData/Roaming/Microsoft/Windows/Start Menu/Programs")
);
assert_eq!(d.desktop.unwrap(), Path::new("/u/me/Desktop"));
}
#[test]
fn places_parse_and_print() {
for p in [Place::Launcher, Place::Desktop, Place::StartMenu] {
assert_eq!(Place::parse(p.as_str()), Some(p));
}
assert_eq!(Place::parse("x"), None);
}
#[test]
fn newest_mode_keeps_a_linux_entry_installed_whichever_build_starts() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("co");
std::fs::create_dir_all(root.join("crates/gitpoulpi-tui")).unwrap();
std::fs::write(root.join("Cargo.toml"), "").unwrap();
let mk = |profile: &str, name: &str, age: u64| {
let dir = root.join("target").join(profile);
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join(name);
let f = std::fs::File::create(&p).unwrap();
f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(age))
.unwrap();
p
};
let (dist, dist_cli) = (
mk("dist", "gitpoulpi-tui", 100),
mk("dist", "gitpoulpi", 100),
);
let (release, release_cli) = (
mk("release", "gitpoulpi-tui", 1),
mk("release", "gitpoulpi", 1),
);
let dirs = Dirs {
applications: tmp.path().join("apps"),
icon_root: tmp.path().join("icons"),
..Dirs::default()
};
let icons: &'static IconSet = Box::leak(Box::default());
let req = |exe: &'static Path, launch: &'static Path, newest| Request {
os: Os::Linux,
exe,
terminal: "kitty",
terminal_exe: None,
launch_exe: Some(launch),
newest,
icons,
ctx: InstallCtx::legacy_ref(),
refresh_icon_cache: false,
};
let leak = |p: &PathBuf| -> &'static Path { Box::leak(p.clone().into_boxed_path()) };
let (dist, dist_cli) = (leak(&dist), leak(&dist_cli));
let (release, release_cli) = (leak(&release), leak(&release_cli));
install(Place::Launcher, &dirs, &req(dist, dist_cli, true)).unwrap();
let text = std::fs::read_to_string(dirs.applications.join("gitpoulpi.desktop")).unwrap();
assert!(text.contains("release") && !text.contains("dist"), "{text}");
for (exe, cli) in [(dist, dist_cli), (release, release_cli)] {
assert_eq!(
status(Place::Launcher, &dirs, &req(exe, cli, true)).state,
State::Installed
);
}
assert_eq!(
status(Place::Launcher, &dirs, &req(dist, dist_cli, false)).state,
State::Outdated
);
}
}