use std::ffi::OsString;
use std::path::{Path, PathBuf};
use super::folder_menu::windows::{app_path_key, app_path_remove};
use super::owner::{decide, Facts, Owner};
use super::registry::{RegOp, Registry};
use crate::open_in::Os;
pub const CMD_MARKER: &str = "REM X-GitPoulpi=1";
pub const CMDLINE_ENV: &str = "GITPOULPI_CMDCMDLINE";
pub const UNIX_MARKER: &str = "# X-GitPoulpi=1";
pub const CMD_OWNER_PREFIX: &str = "REM X-GitPoulpi-Install=";
pub const UNIX_OWNER_PREFIX: &str = "# X-GitPoulpi-Install=";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Kind {
#[default]
Open,
Add,
}
impl Kind {
pub fn as_str(self) -> &'static str {
match self {
Kind::Open => "open",
Kind::Add => "add",
}
}
}
const TUI_STEM: &str = "gitpoulpi";
pub const LEGACY_TUI_STEM: &str = "gitpoulpi-tui";
const CLI_STEM: &str = "gitpoulpi";
const POWERSHELL_ALIASES: &[&str] = &[
"gp", "gc", "gl", "gm", "gi", "gu", "gv", "ls", "cp", "mv", "rm", "ps", "cat", "diff", "sort",
"sl", "sp", "sv", "man", "cd", "echo", "kill", "type",
];
#[derive(Debug, Clone)]
pub struct Env {
pub os: Os,
pub bin_dir: PathBuf,
pub exe: PathBuf,
pub newest: bool,
pub path_var: Option<OsString>,
pub pathext: Option<String>,
pub ctx: super::InstallCtx,
pub cargo_home: Option<String>,
}
impl Env {
pub fn discover(
os: Os,
env: &dyn Fn(&str) -> Option<String>,
home: &Path,
current_exe: &Path,
) -> Env {
let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
let bin_dir = match os {
Os::Windows => var("LOCALAPPDATA")
.unwrap_or_else(|| home.join("AppData/Local"))
.join("Programs")
.join("GitPoulpi")
.join("bin"),
Os::Linux | Os::Macos => home.join(".local/bin"),
};
Env {
os,
bin_dir,
exe: tui_exe(current_exe),
newest: false,
path_var: env("PATH").map(OsString::from),
pathext: env("PATHEXT"),
ctx: super::InstallCtx::legacy(),
cargo_home: env("CARGO_HOME")
.filter(|v| !v.is_empty())
.or_else(|| Some(home.join(".cargo").to_string_lossy().into_owned())),
}
}
pub fn with_ctx(mut self, ctx: super::InstallCtx) -> Env {
self.ctx = ctx;
self
}
fn is_current(&self, target: &Path) -> bool {
target == self.exe || (self.newest && crate::dev_mode::same_build_family(target, &self.exe))
}
fn wanted_exe(&self) -> PathBuf {
if self.newest {
crate::dev_mode::newest_build(&self.exe)
} else {
self.exe.clone()
}
}
fn file(&self, name: &str) -> PathBuf {
match self.os {
Os::Windows => self.bin_dir.join(format!("{name}.cmd")),
_ => self.bin_dir.join(name),
}
}
}
pub fn legacy_tui_exe(exe: &Path) -> Option<PathBuf> {
let text = exe.to_string_lossy();
let cut = text.rfind(['/', '\\']).map_or(0, |i| i + 1);
let (dir, file) = text.split_at(cut);
let (stem, ext) = match file.rfind('.') {
Some(i) => file.split_at(i),
None => (file, ""),
};
stem.eq_ignore_ascii_case(TUI_STEM)
.then(|| PathBuf::from(format!("{dir}{LEGACY_TUI_STEM}{ext}")))
}
pub fn tui_exe(current: &Path) -> PathBuf {
let tui = format!("{TUI_STEM}{}", std::env::consts::EXE_SUFFIX);
if current.file_name().is_some_and(|n| *n == *tui) {
return current.to_path_buf();
}
let sibling = current.with_file_name(&tui);
if sibling.is_file() {
sibling
} else {
current.to_path_buf()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameError {
Empty,
Space,
Separator,
BadChar,
BadStart,
TooLong,
}
impl NameError {
pub fn describe(self) -> &'static str {
match self {
NameError::Empty => "the alias name is empty",
NameError::Space => "the alias name has a space",
NameError::Separator => "the alias name has a path separator",
NameError::BadChar => "the alias name may only hold letters, digits, - _ and .",
NameError::BadStart => "the alias name cannot start with - or .",
NameError::TooLong => "the alias name is longer than 64 characters",
}
}
}
pub fn validate_name(name: &str) -> Result<(), NameError> {
if name.is_empty() {
return Err(NameError::Empty);
}
if name.chars().any(char::is_whitespace) {
return Err(NameError::Space);
}
if name.contains(['/', '\\', ':']) {
return Err(NameError::Separator);
}
if !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
{
return Err(NameError::BadChar);
}
if name.starts_with(['-', '.']) {
return Err(NameError::BadStart);
}
if name.len() > 64 {
return Err(NameError::TooLong);
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
NotInstalled,
Installed,
Outdated,
Foreign,
Other,
}
impl State {
pub fn as_str(self) -> &'static str {
match self {
State::NotInstalled => "not_installed",
State::Installed => "installed",
State::Outdated => "outdated",
State::Foreign => "foreign",
State::Other => "other",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
pub state: State,
pub owner: Option<String>,
pub shadowed_by: Option<PathBuf>,
pub powershell_builtin: bool,
}
pub fn cmd_shim_text(exe: &Path) -> String {
cmd_shim_text_for(exe, Kind::Open)
}
pub fn cmd_shim_text_for(exe: &Path, kind: Kind) -> String {
cmd_shim_text_owned(exe, kind, None, true)
}
pub fn cmd_shim_text_owned(exe: &Path, kind: Kind, tag: Option<&str>, legacy: bool) -> String {
let flag = match kind {
Kind::Open => "",
Kind::Add => " --add",
};
let mut owner = String::new();
if legacy {
owner.push_str(&format!("{CMD_MARKER}\r\n"));
}
if let Some(tag) = tag {
owner.push_str(&format!("{CMD_OWNER_PREFIX}{tag}\r\n"));
}
format!(
"@echo off\r\n{owner}set \"{CMDLINE_ENV}=%CMDCMDLINE%\"\r\n\"{}\"{flag} %*\r\n",
exe.display().to_string().replace('"', "")
)
}
pub fn sh_shim_text(exe: &Path) -> String {
sh_shim_text_owned(exe, None, true)
}
pub fn sh_shim_text_owned(exe: &Path, tag: Option<&str>, legacy: bool) -> String {
let mut owner = String::new();
if legacy {
owner.push_str(&format!("{UNIX_MARKER}\n"));
}
if let Some(tag) = tag {
owner.push_str(&format!("{UNIX_OWNER_PREFIX}{tag}\n"));
}
format!(
"#!/bin/sh\n{owner}exec {} --add \"$@\"\n",
sh_quote(&exe.display().to_string())
)
}
fn owner_lines(ctx: &super::InstallCtx) -> (Option<&str>, bool) {
(
Some(ctx.id.as_str()).filter(|t| !t.is_empty()),
ctx.is_primary(),
)
}
fn sh_quote(text: &str) -> String {
format!("'{}'", text.replace('\'', "'\\''"))
}
fn sh_unquote(text: &str) -> Option<(String, &str)> {
let mut out = String::new();
let mut rest = text;
loop {
rest = rest.strip_prefix('\'')?;
let end = rest.find('\'')?;
out.push_str(&rest[..end]);
rest = &rest[end + 1..];
match rest.strip_prefix("\\'") {
Some(more) => {
out.push('\'');
rest = more;
}
None => return Some((out, rest)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Shim {
exe: PathBuf,
kind: Kind,
tag: Option<String>,
legacy: bool,
}
fn owner_facts(text: &str, marker: &str, prefix: &str) -> Option<(Option<String>, bool)> {
let legacy = text.lines().any(|l| l.trim() == marker);
let tag = text
.lines()
.find_map(|l| l.trim().strip_prefix(prefix))
.map(|t| t.trim().to_string());
(legacy || tag.is_some()).then_some((tag, legacy))
}
fn shim_parts(text: &str) -> Option<Shim> {
let (tag, legacy) = owner_facts(text, CMD_MARKER, CMD_OWNER_PREFIX)?;
let line = text
.lines()
.find_map(|l| l.trim().strip_suffix("%*"))?
.trim();
let (exe, rest) = match line.strip_prefix('"') {
Some(inner) => {
let end = inner.find('"')?;
(&inner[..end], inner[end + 1..].trim())
}
None => (line, ""),
};
let kind = if rest == "--add" {
Kind::Add
} else {
Kind::Open
};
Some(Shim {
exe: PathBuf::from(exe),
kind,
tag,
legacy,
})
}
#[cfg(test)]
fn shim_target(text: &str) -> Option<PathBuf> {
shim_parts(text).map(|s| s.exe)
}
fn sh_parts(text: &str) -> Option<Shim> {
let (tag, legacy) = owner_facts(text, UNIX_MARKER, UNIX_OWNER_PREFIX)?;
let line = text.lines().find_map(|l| l.trim().strip_prefix("exec "))?;
let (exe, rest) = sh_unquote(line.trim())?;
(rest.trim() == "--add \"$@\"").then(|| Shim {
exe: PathBuf::from(exe),
kind: Kind::Add,
tag,
legacy,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Found {
target: PathBuf,
kind: Kind,
owner: Owner,
id: Option<String>,
}
impl Found {
fn is_mine(&self) -> bool {
matches!(self.owner, Owner::Mine | Owner::Adopt)
}
}
fn target_owner_id(env: &Env, target: &Path, link: &Path) -> String {
let absolute = if target.is_relative() {
link.parent()
.map_or_else(|| target.to_path_buf(), |d| d.join(target))
} else {
target.to_path_buf()
};
let fs = crate::installation::RealFs;
let ident = crate::installation::IdentityEnv {
windows: env.os == Os::Windows,
host_target: crate::release::host_target(),
cargo_home: env.cargo_home.clone(),
install_id: None,
env_override: None,
fs: &fs,
};
crate::installation::identify(&absolute, &ident).id
}
fn ours(env: &Env, path: &Path) -> Option<Found> {
let from_shim = |shim: Shim| {
let name = path.file_stem().map(|s| s.to_string_lossy().into_owned());
let facts = Facts {
tag: shim.tag.as_deref(),
legacy_marker: shim.legacy,
names_my_exe: shim.tag.is_none() && env.is_current(&shim.exe),
claimed_by: name.as_deref().and_then(|n| env.ctx.alias_claimed_by(n)),
};
let owner = decide(&facts, &env.ctx);
let id = shim.tag.clone().or_else(|| match &owner {
Owner::Other(id) | Owner::Orphan(Some(id)) => Some(id.clone()),
Owner::Adopt => Some(env.ctx.id.clone()),
_ => None,
});
Found {
target: shim.exe,
kind: shim.kind,
owner,
id,
}
};
match env.os {
Os::Windows => shim_parts(&std::fs::read_to_string(path).ok()?).map(from_shim),
_ => {
if let Ok(target) = std::fs::read_link(path) {
let name = target.file_name()?.to_string_lossy().into_owned();
if !name.starts_with(CLI_STEM) {
return None;
}
let (owner, id) = if env.is_current(&target) || target.parent() == env.exe.parent()
{
(Owner::Mine, env.ctx.id.clone())
} else {
let id = target_owner_id(env, &target, path);
let facts = Facts {
tag: Some(&id),
..Facts::default()
};
(decide(&facts, &env.ctx), id)
};
return Some(Found {
target,
kind: Kind::Open,
owner,
id: Some(id),
});
}
let meta = std::fs::metadata(path).ok()?;
if !meta.is_file() || meta.len() > 4096 {
return None;
}
sh_parts(&std::fs::read_to_string(path).ok()?).map(from_shim)
}
}
}
fn resolve_on_path(env: &Env, name: &str) -> Option<PathBuf> {
let exts: Vec<String> = if env.os == Os::Windows {
let ext = env
.pathext
.clone()
.unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD".into());
std::iter::once(String::new())
.chain(ext.split(';').filter(|e| !e.is_empty()).map(String::from))
.collect()
} else {
vec![String::new()]
};
std::env::split_paths(env.path_var.as_ref()?)
.filter(|d| !d.as_os_str().is_empty())
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{name}{e}"))))
.find(|p| p.is_file() || p.is_symlink())
}
fn shim_text_current(env: &Env, path: &Path) -> bool {
let (tag, legacy) = owner_lines(&env.ctx);
let Ok(text) = std::fs::read_to_string(path) else {
return true;
};
match env.os {
Os::Windows => shim_parts(&text)
.map(|s| text == cmd_shim_text_owned(&s.exe, s.kind, tag, legacy))
.unwrap_or(true),
_ => sh_parts(&text)
.map(|s| text == sh_shim_text_owned(&s.exe, tag, legacy))
.unwrap_or(true),
}
}
pub fn status(env: &Env, name: &str) -> Status {
status_kind(env, name, Kind::Open)
}
fn state_of(env: &Env, found: &Found, kind: Option<Kind>, path: &Path) -> State {
if matches!(found.owner, Owner::Other(_)) {
return State::Other;
}
if found.is_mine()
&& kind.is_none_or(|k| k == found.kind)
&& env.is_current(&found.target)
&& shim_text_current(env, path)
{
State::Installed
} else {
State::Outdated
}
}
pub fn status_kind(env: &Env, name: &str, kind: Kind) -> Status {
let path = env.file(name);
let (state, owner) = if std::fs::symlink_metadata(&path).is_err() {
(State::NotInstalled, None)
} else {
match ours(env, &path) {
Some(found) => (state_of(env, &found, Some(kind), &path), found.id),
None => (State::Foreign, None),
}
};
let shadowed_by = (state == State::NotInstalled)
.then(|| resolve_on_path(env, name))
.flatten();
Status {
state,
owner,
shadowed_by,
powershell_builtin: env.os == Os::Windows
&& POWERSHELL_ALIASES.contains(&name.to_ascii_lowercase().as_str()),
}
}
pub fn create(env: &Env, name: &str) -> Result<PathBuf, String> {
create_kind(env, name, Kind::Open)
}
pub fn create_kind(env: &Env, name: &str, kind: Kind) -> Result<PathBuf, String> {
validate_name(name).map_err(|e| e.describe().to_string())?;
let path = env.file(name);
if std::fs::symlink_metadata(&path).is_ok() {
match ours(env, &path) {
None => return Err(format!("{} is not ours; not replacing it", path.display())),
Some(Found {
owner: Owner::Other(id),
..
}) => {
return Err(format!(
"{name} belongs to another installation ({id}); pick another name"
))
}
Some(_) => {}
}
std::fs::remove_file(&path).map_err(|e| format!("{}: {e}", path.display()))?;
}
std::fs::create_dir_all(&env.bin_dir).map_err(|e| format!("{}: {e}", env.bin_dir.display()))?;
let exe = env.wanted_exe();
let (tag, legacy) = owner_lines(&env.ctx);
match (env.os, kind) {
(Os::Windows, kind) => std::fs::write(&path, cmd_shim_text_owned(&exe, kind, tag, legacy))
.map_err(|e| format!("{}: {e}", path.display()))?,
(_, Kind::Open) => symlink(&exe, &path)?,
(_, Kind::Add) => write_script(&path, &sh_shim_text_owned(&exe, tag, legacy))?,
}
Ok(path)
}
#[cfg(unix)]
fn write_script(path: &Path, text: &str) -> Result<(), String> {
use std::os::unix::fs::PermissionsExt;
std::fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
.map_err(|e| format!("{}: {e}", path.display()))
}
#[cfg(not(unix))]
fn write_script(_path: &Path, _text: &str) -> Result<(), String> {
Err("shell scripts are not available on this system".into())
}
#[cfg(unix)]
fn symlink(exe: &Path, path: &Path) -> Result<(), String> {
std::os::unix::fs::symlink(exe, path).map_err(|e| format!("{}: {e}", path.display()))
}
#[cfg(not(unix))]
fn symlink(_exe: &Path, _path: &Path) -> Result<(), String> {
Err("symbolic links are not available on this system".into())
}
pub fn remove(env: &Env, name: &str) -> Result<bool, String> {
validate_name(name).map_err(|e| e.describe().to_string())?;
let path = env.file(name);
if std::fs::symlink_metadata(&path).is_err() {
return Ok(false);
}
match ours(env, &path) {
None => return Err(format!("{} is not ours; not removing it", path.display())),
Some(Found {
owner: Owner::Other(id),
..
}) => {
return Err(format!(
"{name} belongs to another installation ({id}); not removing it"
))
}
Some(_) => {}
}
std::fs::remove_file(&path).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(true)
}
pub fn app_path_name(name: &str) -> String {
format!("{name}.exe")
}
const APP_MARK_NAME: &str = "X-GitPoulpi";
const APP_MARK_VALUE: &str = "1";
fn app_path_owner(
registry: &dyn Registry,
key: &str,
ctx: &super::InstallCtx,
) -> Result<Option<Owner>, String> {
let got = registry.read(&[app_path_key(key)])?;
let Some((values, _)) = got.into_iter().next().flatten() else {
return Ok(None);
};
let value = |n: &str| {
values
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(n))
.map(|(_, v)| v.as_str())
};
let facts = Facts {
tag: value(super::OWNER_TAG),
legacy_marker: value(APP_MARK_NAME) == Some(APP_MARK_VALUE),
claimed_by: None,
names_my_exe: false,
};
Ok(Some(decide(&facts, ctx)))
}
fn app_path_ops(key: &str, helper: &Path, ctx: &super::InstallCtx) -> Vec<RegOp> {
let (tag, legacy) = owner_lines(ctx);
let dir = helper
.parent()
.map(|p| p.display().to_string())
.unwrap_or_default();
let mut values = vec![
(String::new(), helper.display().to_string()),
("Path".to_string(), dir),
];
if legacy {
values.push((APP_MARK_NAME.to_string(), APP_MARK_VALUE.to_string()));
}
if let Some(tag) = tag {
values.push((super::OWNER_TAG.to_string(), tag.to_string()));
}
let full = app_path_key(key);
values
.into_iter()
.map(|(name, value)| RegOp::Set {
key: full.clone(),
name,
value,
})
.collect()
}
pub fn create_with_app_path(
env: &Env,
registry: &dyn Registry,
name: &str,
kind: Kind,
) -> Result<PathBuf, String> {
create_with_app_path_in(env, registry, name, kind, &|p| p.is_file())
}
fn create_with_app_path_in(
env: &Env,
registry: &dyn Registry,
name: &str,
kind: Kind,
exists: &dyn Fn(&Path) -> bool,
) -> Result<PathBuf, String> {
let path = create_kind(env, name, kind)?;
if env.os == Os::Windows && kind == Kind::Open {
let key = app_path_name(name);
let writable = !matches!(
app_path_owner(registry, &key, &env.ctx)?,
Some(Owner::Other(_) | Owner::Foreign)
);
if let (Some(helper), true) = (
super::terminals::folder_helper(env.os, &env.wanted_exe(), exists),
writable,
) {
registry.apply(&app_path_ops(&key, &helper, &env.ctx))?;
}
}
Ok(path)
}
pub fn remove_with_app_path(
env: &Env,
registry: &dyn Registry,
name: &str,
) -> Result<bool, String> {
let removed = remove(env, name)?;
if removed && env.os == Os::Windows {
let key = app_path_name(name);
if matches!(
app_path_owner(registry, &key, &env.ctx)?,
Some(Owner::Mine | Owner::Adopt | Owner::Orphan(_) | Owner::Legacy)
) {
registry.apply(&[app_path_remove(&key)])?;
}
}
Ok(removed)
}
pub fn remove_all_with_app_paths(
env: &Env,
registry: &dyn Registry,
) -> Result<Vec<String>, String> {
let mut gone = Vec::new();
for (name, _) in list(env) {
if remove_with_app_path(env, registry, &name)? {
gone.push(name);
}
}
if env.os == Os::Windows && !gone.is_empty() && std::fs::remove_dir(&env.bin_dir).is_ok() {
if let Some(parent) = env.bin_dir.parent() {
let _ = std::fs::remove_dir(parent);
}
}
Ok(gone)
}
pub fn list(env: &Env) -> Vec<(String, State)> {
list_kinds(env)
.into_iter()
.map(|(name, _, state)| (name, state))
.collect()
}
pub fn list_kinds(env: &Env) -> Vec<(String, Kind, State)> {
list_all(env)
.into_iter()
.filter(|e| e.mine)
.map(|e| (e.name, e.kind, e.state))
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub name: String,
pub kind: Kind,
pub state: State,
pub owner: Option<String>,
pub mine: bool,
}
pub fn list_all(env: &Env) -> Vec<Entry> {
let Ok(read) = std::fs::read_dir(&env.bin_dir) else {
return Vec::new();
};
let mut out: Vec<Entry> = read
.flatten()
.filter_map(|e| {
let file = e.file_name().to_string_lossy().into_owned();
let name = match env.os {
Os::Windows => file.strip_suffix(".cmd")?.to_string(),
_ => file,
};
let found = ours(env, &e.path())?;
Some(Entry {
state: state_of(env, &found, None, &e.path()),
mine: found.is_mine(),
owner: found.id,
kind: found.kind,
name,
})
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
pub fn target_of(env: &Env, name: &str) -> Option<PathBuf> {
let path = env.file(name);
std::fs::symlink_metadata(&path).ok()?;
ours(env, &path).map(|f| f.target)
}
pub fn others_have_aliases(env: &Env) -> bool {
list_all(env).iter().any(|e| e.state == State::Other)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::desktop::folder_menu::windows::{app_path_is_ours, app_path_key};
fn parts(shim: Option<Shim>) -> Option<(PathBuf, Kind)> {
shim.map(|s| (s.exe, s.kind))
}
fn env(root: &Path, os: Os) -> Env {
Env {
os,
bin_dir: root.join("bin"),
exe: PathBuf::from("/opt/gp/gitpoulpi"),
newest: false,
path_var: None,
pathext: None,
ctx: crate::desktop::InstallCtx::legacy(),
cargo_home: None,
}
}
fn ctx_of(
id: &str,
primary: Option<&str>,
known: &[(&str, bool)],
) -> crate::desktop::InstallCtx {
crate::desktop::InstallCtx {
id: id.into(),
short: format!("i{id}"),
name: format!("GitPoulpi ({id})"),
primary: primary.map(str::to_string),
alias_claims: Vec::new(),
known: known
.iter()
.map(|(id, exists)| crate::desktop::KnownInstall {
id: (*id).into(),
exists: *exists,
})
.collect(),
}
}
const KNOWN: [(&str, bool); 3] = [("aaaa", true), ("bbbb", true), ("cccc", false)];
fn windows_as(root: &Path, id: &str, primary: Option<&str>) -> Env {
let mut e = env(root, Os::Windows);
e.exe = PathBuf::from(format!("C:/{id}/gitpoulpi.exe"));
e.ctx = ctx_of(id, primary, &KNOWN);
e
}
#[test]
fn only_the_primary_writes_the_legacy_marker_everyone_the_tag() {
let tmp = tempfile::tempdir().unwrap();
let mine = windows_as(tmp.path(), "aaaa", None);
let text = std::fs::read_to_string(create(&mine, "gpd").unwrap()).unwrap();
assert!(
text.contains("\r\nREM X-GitPoulpi-Install=aaaa\r\n"),
"{text}"
);
assert!(
!text.contains(CMD_MARKER),
"old builds must not see it: {text}"
);
let primary = windows_as(tmp.path(), "bbbb", Some("bbbb"));
let text = std::fs::read_to_string(create(&primary, "gp").unwrap()).unwrap();
assert!(
text.contains(CMD_MARKER) && text.contains("Install=bbbb"),
"{text}"
);
assert_eq!(status(&mine, "gpd").state, State::Installed);
assert_eq!(status(&primary, "gp").state, State::Installed);
std::fs::write(
mine.bin_dir.join("old.cmd"),
cmd_shim_text(Path::new("C:/aaaa/gitpoulpi.exe")),
)
.unwrap();
assert_eq!(status(&mine, "old").state, State::Outdated);
create(&mine, "old").unwrap();
assert_eq!(status(&mine, "old").state, State::Installed);
}
#[test]
fn another_installations_shim_reads_other_not_outdated() {
let tmp = tempfile::tempdir().unwrap();
let theirs = windows_as(tmp.path(), "bbbb", None);
create(&theirs, "gpd").unwrap();
create_kind(&theirs, "gpda", Kind::Add).unwrap();
let mine = windows_as(tmp.path(), "aaaa", None);
for (name, kind) in [("gpd", Kind::Open), ("gpda", Kind::Add)] {
let st = status_kind(&mine, name, kind);
assert_eq!(st.state, State::Other, "{name}");
assert_eq!(st.owner.as_deref(), Some("bbbb"));
}
assert!(list_kinds(&mine).is_empty(), "only mine are listed");
let all = list_all(&mine);
assert_eq!(all.len(), 2);
assert!(all
.iter()
.all(|e| e.state == State::Other && !e.mine && e.owner.as_deref() == Some("bbbb")));
assert!(others_have_aliases(&mine));
assert!(!others_have_aliases(&theirs));
let legacy = mine.bin_dir.join("lp.cmd");
std::fs::write(&legacy, cmd_shim_text(Path::new("C:/zzzz/gitpoulpi.exe"))).unwrap();
let with_primary = Env {
ctx: ctx_of("aaaa", Some("bbbb"), &KNOWN),
..mine.clone()
};
assert_eq!(status(&with_primary, "lp").state, State::Other);
assert_eq!(
status(&mine, "lp").state,
State::Outdated,
"no primary: legacy"
);
}
#[test]
fn a_legacy_alias_goes_to_the_installation_that_claims_it_not_to_the_primary() {
let tmp = tempfile::tempdir().unwrap();
let dev_exe = Path::new("C:/bbbb/gitpoulpi.exe");
let mut primary = windows_as(tmp.path(), "aaaa", Some("aaaa"));
primary.ctx.alias_claims = vec![
("gpd".into(), "bbbb".into()),
("gpda".into(), "bbbb".into()),
("gp".into(), "aaaa".into()),
];
std::fs::create_dir_all(&primary.bin_dir).unwrap();
let legacy = |exe: &Path, kind| cmd_shim_text_owned(exe, kind, None, true);
std::fs::write(primary.bin_dir.join("gpd.cmd"), legacy(dev_exe, Kind::Open)).unwrap();
std::fs::write(primary.bin_dir.join("gpda.cmd"), legacy(dev_exe, Kind::Add)).unwrap();
std::fs::write(primary.bin_dir.join("gp.cmd"), legacy(dev_exe, Kind::Open)).unwrap();
for (name, kind) in [("gpd", Kind::Open), ("gpda", Kind::Add)] {
let st = status_kind(&primary, name, kind);
assert_eq!(st.state, State::Other, "{name}");
assert_eq!(st.owner.as_deref(), Some("bbbb"), "{name}");
}
let before = std::fs::read_to_string(primary.bin_dir.join("gpd.cmd")).unwrap();
assert!(create(&primary, "gpd").is_err());
assert!(remove(&primary, "gpd").is_err());
assert_eq!(
std::fs::read_to_string(primary.bin_dir.join("gpd.cmd")).unwrap(),
before
);
assert!(!before.contains("Install="), "still untagged: {before}");
let owners: Vec<_> = list_all(&primary)
.into_iter()
.map(|e| (e.name, e.owner))
.collect();
assert_eq!(
owners,
[
("gp".to_string(), Some("aaaa".to_string())),
("gpd".to_string(), Some("bbbb".to_string())),
("gpda".to_string(), Some("bbbb".to_string())),
]
);
create(&primary, "gp").unwrap();
assert_eq!(status(&primary, "gp").state, State::Installed);
let mut dev = windows_as(tmp.path(), "bbbb", Some("aaaa"));
dev.ctx.alias_claims = primary.ctx.alias_claims.clone();
assert_eq!(
status_kind(&dev, "gpd", Kind::Open).owner.as_deref(),
Some("bbbb")
);
assert!(list_all(&dev).iter().any(|e| e.name == "gpd" && e.mine));
}
#[test]
fn create_refuses_a_name_another_installation_owns_but_replaces_an_orphan() {
let tmp = tempfile::tempdir().unwrap();
let mine = windows_as(tmp.path(), "aaaa", None);
let theirs = windows_as(tmp.path(), "bbbb", None);
let gone = windows_as(tmp.path(), "cccc", None);
create(&theirs, "gpb").unwrap();
create(&gone, "gpc").unwrap();
let err = create(&mine, "gpb").unwrap_err();
assert!(err.contains("another installation"), "{err}");
assert!(remove(&mine, "gpb").is_err(), "not removable either");
let kept = std::fs::read_to_string(theirs.bin_dir.join("gpb.cmd")).unwrap();
assert!(kept.contains("Install=bbbb"), "left as it was: {kept}");
assert_eq!(status(&mine, "gpc").state, State::Outdated);
let text = std::fs::read_to_string(create(&mine, "gpc").unwrap()).unwrap();
assert!(
text.contains("Install=aaaa") && !text.contains("cccc"),
"{text}"
);
assert_eq!(status(&mine, "gpc").state, State::Installed);
}
#[test]
fn remove_all_drops_the_emptied_windows_bin_folder_but_never_one_with_a_file() {
use crate::desktop::registry::MemoryRegistry;
let tmp = tempfile::tempdir().unwrap();
let mine = windows_as(tmp.path(), "aaaa", None);
let reg = MemoryRegistry::new();
create(&mine, "gpm").unwrap();
let gone = remove_all_with_app_paths(&mine, ®).unwrap();
assert_eq!(gone, ["gpm"]);
assert!(!mine.bin_dir.exists(), "the empty bin folder stays");
create(&mine, "gpm").unwrap();
std::fs::write(mine.bin_dir.join("notes.txt"), "x").unwrap();
remove_all_with_app_paths(&mine, ®).unwrap();
assert!(mine.bin_dir.join("notes.txt").exists());
}
#[test]
fn remove_all_drops_the_emptied_parent_of_the_bin_folder_too_but_never_one_with_a_file() {
use crate::desktop::registry::MemoryRegistry;
let tmp = tempfile::tempdir().unwrap();
let mut mine = windows_as(tmp.path(), "aaaa", None);
let parent = tmp.path().join("Programs").join("GitPoulpi");
mine.bin_dir = parent.join("bin");
let reg = MemoryRegistry::new();
create(&mine, "gpm").unwrap();
remove_all_with_app_paths(&mine, ®).unwrap();
assert!(
!parent.exists(),
"the empty parent goes with the bin folder"
);
assert!(tmp.path().join("Programs").exists(), "only our own folders");
create(&mine, "gpm").unwrap();
std::fs::write(parent.join("gitpoulpi.exe"), "x").unwrap();
remove_all_with_app_paths(&mine, ®).unwrap();
assert!(!mine.bin_dir.exists());
assert!(parent.join("gitpoulpi.exe").exists());
}
#[test]
fn the_windows_bin_dir_is_built_from_components() {
let env = |k: &str| (k == "LOCALAPPDATA").then(|| "/u/AppData/Local".to_string());
let w = Env::discover(Os::Windows, &env, Path::new("/h"), Path::new("/x/gp.exe"));
let want: PathBuf = ["/u/AppData/Local", "Programs", "GitPoulpi", "bin"]
.iter()
.collect();
assert_eq!(w.bin_dir, want);
}
#[test]
fn remove_all_removes_only_my_aliases_and_app_paths() {
use crate::desktop::registry::MemoryRegistry;
let tmp = tempfile::tempdir().unwrap();
let mine = windows_as(tmp.path(), "aaaa", None);
let theirs = windows_as(tmp.path(), "bbbb", None);
let reg = MemoryRegistry::new();
let helper = |id: &str| PathBuf::from(format!("C:/{id}/gitpoulpi-launch.exe"));
let has = |p: &Path| p == helper("aaaa") || p == helper("bbbb");
create_with_app_path_in(&mine, ®, "gpm", Kind::Open, &has).unwrap();
create_with_app_path_in(&mine, ®, "gpma", Kind::Add, &has).unwrap();
create_with_app_path_in(&theirs, ®, "gpt", Kind::Open, &has).unwrap();
let ours_in_registry = |reg: &MemoryRegistry, key: &str| {
let key = app_path_key(key);
reg.dump()
.iter()
.any(|(k, _, _)| k.eq_ignore_ascii_case(&key))
};
assert!(ours_in_registry(®, "gpm.exe") && ours_in_registry(®, "gpt.exe"));
let gone = remove_all_with_app_paths(&mine, ®).unwrap();
assert_eq!(gone, ["gpm", "gpma"]);
assert!(!mine.bin_dir.join("gpm.cmd").exists());
assert!(
theirs.bin_dir.join("gpt.cmd").exists(),
"the other's shim stays"
);
assert!(!ours_in_registry(®, "gpm.exe"));
assert!(
ours_in_registry(®, "gpt.exe"),
"the other's App Paths stays"
);
let dump = reg.dump();
assert!(
dump.iter()
.any(|(_, n, v)| n == crate::desktop::OWNER_TAG && v == "bbbb"),
"{dump:?}"
);
reg.apply(&[RegOp::Set {
key: app_path_key("gpx.exe"),
name: crate::desktop::OWNER_TAG.into(),
value: "bbbb".into(),
}])
.unwrap();
create_with_app_path_in(&mine, ®, "gpx", Kind::Open, &has).unwrap();
assert_eq!(
app_path_owner(®, "gpx.exe", &mine.ctx).unwrap(),
Some(Owner::Other("bbbb".into()))
);
}
#[cfg(unix)]
#[test]
fn unix_symlink_owner_follows_the_target() {
use crate::installation::{identify, IdentityEnv, RealFs};
let tmp = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(tmp.path()).unwrap();
let exe = |name: &str| {
let dir = root.join(name);
std::fs::create_dir_all(&dir).unwrap();
let exe = dir.join("gitpoulpi");
std::fs::write(&exe, "").unwrap();
exe
};
let (a, b, c) = (exe("a"), exe("b"), exe("c"));
let fs = RealFs;
let ident = IdentityEnv {
windows: false,
host_target: crate::release::host_target(),
cargo_home: None,
install_id: None,
env_override: None,
fs: &fs,
};
let (ida, idb, idc) = (
identify(&a, &ident).id,
identify(&b, &ident).id,
identify(&c, &ident).id,
);
assert!(ida != idb && idb != idc);
let mut e = env(&root, Os::Linux);
e.exe = a.clone();
e.ctx = ctx_of(&ida, None, &[(&ida, true), (&idb, true), (&idc, false)]);
std::fs::create_dir_all(&e.bin_dir).unwrap();
let link = |name: &str, to: &Path| {
std::os::unix::fs::symlink(to, e.bin_dir.join(name)).unwrap();
};
link("mine", &a);
link("theirs", &b);
link("orphan", &c);
assert_eq!(status(&e, "mine").state, State::Installed);
let theirs = status(&e, "theirs");
assert_eq!(
(theirs.state, theirs.owner),
(State::Other, Some(idb.clone()))
);
assert_eq!(status(&e, "orphan").state, State::Outdated);
assert_eq!(list(&e), [("mine".to_string(), State::Installed)]);
assert!(create(&e, "theirs").is_err());
assert_eq!(std::fs::read_link(e.bin_dir.join("theirs")).unwrap(), b);
create(&e, "orphan").unwrap();
assert_eq!(std::fs::read_link(e.bin_dir.join("orphan")).unwrap(), a);
assert_eq!(
remove_all_with_app_paths(&e, &crate::desktop::registry::MemoryRegistry::new())
.unwrap(),
["mine", "orphan"]
);
assert!(e.bin_dir.join("theirs").is_symlink());
}
#[test]
fn names_are_checked() {
assert_eq!(validate_name("gp"), Ok(()));
assert_eq!(validate_name("git-poulpi_2.x"), Ok(()));
assert_eq!(validate_name(""), Err(NameError::Empty));
assert_eq!(validate_name("g p"), Err(NameError::Space));
assert_eq!(validate_name("a/b"), Err(NameError::Separator));
assert_eq!(validate_name("a\\b"), Err(NameError::Separator));
assert_eq!(validate_name("c:x"), Err(NameError::Separator));
assert_eq!(validate_name("a;b"), Err(NameError::BadChar));
assert_eq!(validate_name("-rf"), Err(NameError::BadStart));
assert_eq!(validate_name(&"a".repeat(65)), Err(NameError::TooLong));
}
#[test]
fn aliases_start_gitpoulpi_even_when_a_stub_runs() {
let tmp = tempfile::tempdir().unwrap();
let sfx = std::env::consts::EXE_SUFFIX;
let cli = tmp.path().join(format!("gitpoulpi{sfx}"));
let stub = tmp.path().join(format!("gitpoulpi-tui{sfx}"));
assert_eq!(tui_exe(&stub), stub, "no sibling: the program itself");
std::fs::write(&cli, "").unwrap();
assert_eq!(tui_exe(&cli), cli);
assert_eq!(tui_exe(&stub), cli, "the stub maps to the real program");
let mcp = tmp.path().join(format!("gitpoulpi-mcp{sfx}"));
assert_eq!(tui_exe(&mcp), cli);
}
#[test]
fn the_retired_spelling_of_an_exe_is_known() {
assert_eq!(
legacy_tui_exe(Path::new("/o/gitpoulpi")),
Some(PathBuf::from("/o/gitpoulpi-tui"))
);
assert_eq!(
legacy_tui_exe(Path::new("C:/GP/gitpoulpi.exe")),
Some(PathBuf::from("C:/GP/gitpoulpi-tui.exe"))
);
assert_eq!(legacy_tui_exe(Path::new("/o/gitpoulpi-tui")), None);
assert_eq!(legacy_tui_exe(Path::new("/o/other")), None);
}
#[cfg(unix)]
#[test]
fn an_alias_to_the_retired_tui_is_ours_stale_and_rewritten() {
let tmp = tempfile::tempdir().unwrap();
let e = Env {
exe: PathBuf::from("/opt/gp/gitpoulpi"),
..env(tmp.path(), Os::Linux)
};
std::fs::create_dir_all(&e.bin_dir).unwrap();
let (open, add) = (e.bin_dir.join("gp"), e.bin_dir.join("gpa"));
std::os::unix::fs::symlink("/opt/gp/gitpoulpi-tui", &open).unwrap();
std::fs::write(
&add,
format!("#!/bin/sh\n{UNIX_MARKER}\nexec '/opt/gp/gitpoulpi-tui' --add \"$@\"\n"),
)
.unwrap();
assert_eq!(status(&e, "gp").state, State::Outdated, "never Foreign");
assert_eq!(
status_kind(&e, "gpa", Kind::Add).state,
State::Outdated,
"never Foreign"
);
create(&e, "gp").unwrap();
create_kind(&e, "gpa", Kind::Add).unwrap();
assert_eq!(std::fs::read_link(&open).unwrap(), e.exe);
assert_eq!(status(&e, "gp").state, State::Installed);
assert_eq!(status_kind(&e, "gpa", Kind::Add).state, State::Installed);
assert!(std::fs::read_to_string(&add)
.unwrap()
.contains("exec '/opt/gp/gitpoulpi' --add"));
}
#[test]
fn a_cmd_shim_of_the_retired_tui_is_ours_stale_and_rewritten() {
let tmp = tempfile::tempdir().unwrap();
let mut e = env(tmp.path(), Os::Windows);
e.exe = PathBuf::from("C:/GP/gitpoulpi.exe");
std::fs::create_dir_all(&e.bin_dir).unwrap();
let path = e.bin_dir.join("gp.cmd");
std::fs::write(&path, cmd_shim_text(Path::new("C:/GP/gitpoulpi-tui.exe"))).unwrap();
assert_eq!(status(&e, "gp").state, State::Outdated, "never Foreign");
create(&e, "gp").unwrap();
assert_eq!(status(&e, "gp").state, State::Installed);
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("\"C:/GP/gitpoulpi.exe\""), "{text}");
assert!(!text.contains("gitpoulpi-tui"), "{text}");
}
#[cfg(unix)]
#[test]
fn a_symlink_is_created_recognised_and_removed_only_when_ours() {
let tmp = tempfile::tempdir().unwrap();
let e = env(tmp.path(), Os::Linux);
assert_eq!(status(&e, "gp").state, State::NotInstalled);
let path = create(&e, "gp").unwrap();
assert_eq!(std::fs::read_link(&path).unwrap(), e.exe);
assert_eq!(status(&e, "gp").state, State::Installed);
assert_eq!(list(&e), [("gp".to_string(), State::Installed)]);
let moved = Env {
exe: PathBuf::from("/elsewhere/gitpoulpi-tui"),
newest: false,
..e.clone()
};
assert_eq!(status(&moved, "gp").state, State::Outdated);
create(&moved, "gp").unwrap();
assert_eq!(std::fs::read_link(&path).unwrap(), moved.exe);
assert!(remove(&moved, "gp").unwrap());
assert!(!remove(&moved, "gp").unwrap(), "already gone");
assert!(std::fs::symlink_metadata(&path).is_err());
}
#[cfg(unix)]
#[test]
fn a_link_to_the_cli_is_ours_when_no_tui_sits_next_to_it() {
let tmp = tempfile::tempdir().unwrap();
let e = Env {
exe: PathBuf::from("/opt/gp/gitpoulpi"),
..env(tmp.path(), Os::Linux)
};
create(&e, "gp").unwrap();
assert_eq!(list(&e), [("gp".to_string(), State::Installed)]);
assert!(remove(&e, "gp").unwrap());
}
#[cfg(unix)]
#[test]
fn a_file_or_a_link_that_is_not_ours_is_left_alone() {
let tmp = tempfile::tempdir().unwrap();
let e = env(tmp.path(), Os::Linux);
std::fs::create_dir_all(&e.bin_dir).unwrap();
let file = e.bin_dir.join("gp");
std::fs::write(&file, "#!/bin/sh\n").unwrap();
assert_eq!(status(&e, "gp").state, State::Foreign);
assert!(create(&e, "gp").is_err());
assert!(remove(&e, "gp").is_err());
assert_eq!(std::fs::read_to_string(&file).unwrap(), "#!/bin/sh\n");
std::fs::remove_file(&file).unwrap();
std::os::unix::fs::symlink("/usr/bin/git", &file).unwrap();
assert_eq!(status(&e, "gp").state, State::Foreign);
assert!(remove(&e, "gp").is_err());
assert!(std::fs::symlink_metadata(&file).is_ok());
assert!(list(&e).is_empty());
}
#[cfg(unix)]
#[test]
fn a_name_already_on_path_is_reported_not_blocked() {
let tmp = tempfile::tempdir().unwrap();
let other = tmp.path().join("other");
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("gp"), "").unwrap();
let e = Env {
path_var: Some(other.clone().into_os_string()),
..env(tmp.path(), Os::Linux)
};
let st = status(&e, "gp");
assert_eq!(st.shadowed_by, Some(other.join("gp")));
assert!(!st.powershell_builtin);
assert_eq!(status(&e, "zz").shadowed_by, None);
create(&e, "gp").unwrap();
assert_eq!(status(&e, "gp").shadowed_by, None, "ours now");
}
#[test]
fn the_windows_shim_carries_the_marker_and_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let mut e = env(tmp.path(), Os::Windows);
e.exe = PathBuf::from("C:/Program Files/GP/gitpoulpi-tui.exe");
let text = cmd_shim_text(&e.exe);
assert!(text.contains("\r\nREM X-GitPoulpi=1\r\n"));
assert!(text.ends_with("gitpoulpi-tui.exe\" %*\r\n"), "{text}");
let path = create(&e, "gp").unwrap();
assert_eq!(path, e.bin_dir.join("gp.cmd"));
let st = status(&e, "gp");
assert_eq!(st.state, State::Installed);
assert!(st.powershell_builtin, "gp is Get-ItemProperty there");
assert!(!status(&e, "gpx").powershell_builtin);
assert_eq!(list(&e), [("gp".to_string(), State::Installed)]);
std::fs::write(e.bin_dir.join("other.cmd"), "@echo hi\r\n").unwrap();
assert_eq!(status(&e, "other").state, State::Foreign);
assert!(remove(&e, "other").is_err());
assert!(remove(&e, "gp").unwrap());
assert!(!path.exists());
}
#[test]
fn discover_picks_the_per_user_bin_dirs() {
let env = |k: &str| (k == "LOCALAPPDATA").then(|| "/u/AppData/Local".to_string());
let w = Env::discover(
Os::Windows,
&env,
Path::new("/h"),
Path::new("/x/gitpoulpi.exe"),
);
assert_eq!(
w.bin_dir,
Path::new("/u/AppData/Local/Programs/GitPoulpi/bin")
);
let l = Env::discover(Os::Linux, &env, Path::new("/h"), Path::new("/x/gitpoulpi"));
assert_eq!(l.bin_dir, Path::new("/h/.local/bin"));
}
#[cfg(unix)]
#[test]
fn the_add_variant_is_a_marked_script_that_execs_with_add() {
let tmp = tempfile::tempdir().unwrap();
let e = env(tmp.path(), Os::Linux);
assert_eq!(status_kind(&e, "gpa", Kind::Add).state, State::NotInstalled);
let path = create_kind(&e, "gpa", Kind::Add).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert_eq!(
text,
format!("#!/bin/sh\n{UNIX_MARKER}\nexec '/opt/gp/gitpoulpi' --add \"$@\"\n")
);
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o111,
0o111,
"executable"
);
assert_eq!(status_kind(&e, "gpa", Kind::Add).state, State::Installed);
assert_eq!(status_kind(&e, "gpa", Kind::Open).state, State::Outdated);
assert_eq!(
list_kinds(&e),
[("gpa".to_string(), Kind::Add, State::Installed)]
);
create(&e, "gp").unwrap();
let kinds: Vec<_> = list_kinds(&e).into_iter().map(|(n, k, _)| (n, k)).collect();
assert_eq!(
kinds,
[
("gp".to_string(), Kind::Open),
("gpa".to_string(), Kind::Add)
]
);
let moved = Env {
exe: PathBuf::from("/elsewhere/gitpoulpi-tui"),
..e.clone()
};
assert_eq!(status_kind(&moved, "gpa", Kind::Add).state, State::Outdated);
create_kind(&moved, "gpa", Kind::Add).unwrap();
assert_eq!(
status_kind(&moved, "gpa", Kind::Add).state,
State::Installed
);
assert!(remove(&moved, "gpa").unwrap());
assert!(std::fs::symlink_metadata(&path).is_err());
}
#[cfg(unix)]
#[test]
fn a_script_without_the_marker_is_foreign_and_a_quote_in_the_path_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let e = env(tmp.path(), Os::Linux);
std::fs::create_dir_all(&e.bin_dir).unwrap();
std::fs::write(e.bin_dir.join("gpa"), "#!/bin/sh\necho hi\n").unwrap();
assert_eq!(status_kind(&e, "gpa", Kind::Add).state, State::Foreign);
assert!(create_kind(&e, "gpa", Kind::Add).is_err());
assert!(remove(&e, "gpa").is_err());
assert!(list_kinds(&e).is_empty());
let odd = Path::new("/it's here/gitpoulpi-tui");
let text = sh_shim_text(odd);
assert_eq!(parts(sh_parts(&text)), Some((odd.to_path_buf(), Kind::Add)));
}
#[test]
fn the_windows_add_shim_passes_add_and_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let mut e = env(tmp.path(), Os::Windows);
e.exe = PathBuf::from("C:/Program Files/GP/gitpoulpi-tui.exe");
let text = cmd_shim_text_for(&e.exe, Kind::Add);
assert!(text.ends_with("gitpoulpi-tui.exe\" --add %*\r\n"), "{text}");
assert_eq!(parts(shim_parts(&text)), Some((e.exe.clone(), Kind::Add)));
assert_eq!(
parts(shim_parts(&cmd_shim_text(&e.exe))),
Some((e.exe.clone(), Kind::Open))
);
let path = create_kind(&e, "gpa", Kind::Add).unwrap();
assert_eq!(path, e.bin_dir.join("gpa.cmd"));
assert_eq!(status_kind(&e, "gpa", Kind::Add).state, State::Installed);
assert_eq!(status_kind(&e, "gpa", Kind::Open).state, State::Outdated);
assert!(!status_kind(&e, "gpa", Kind::Add).powershell_builtin);
assert_eq!(
list_kinds(&e),
[("gpa".to_string(), Kind::Add, State::Installed)]
);
}
#[test]
fn newest_mode_points_at_the_newest_build_and_accepts_either() {
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, age: u64| {
let dir = root.join("target").join(profile);
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join("gitpoulpi-tui");
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 = mk("dist", 100);
let release = mk("release", 1);
let from_dist = Env {
exe: dist.clone(),
newest: true,
..env(tmp.path(), Os::Windows)
};
let path = create(&from_dist, "gp").unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert_eq!(shim_target(&text), Some(release.clone()), "the newest");
assert_eq!(status(&from_dist, "gp").state, State::Installed);
let from_release = Env {
exe: release,
..from_dist.clone()
};
assert_eq!(status(&from_release, "gp").state, State::Installed);
let plain = Env {
newest: false,
..from_dist
};
assert_eq!(status(&plain, "gp").state, State::Outdated);
}
#[test]
fn the_windows_shim_exports_the_cmd_command_line_and_keeps_args_last() {
let exe = Path::new("C:/GP/gitpoulpi-tui.exe");
for (kind, flag) in [(Kind::Open, ""), (Kind::Add, " --add")] {
let text = cmd_shim_text_for(exe, kind);
assert_eq!(
text,
format!(
"@echo off\r\nREM X-GitPoulpi=1\r\nset \"GITPOULPI_CMDCMDLINE=%CMDCMDLINE%\"\r\n\"C:/GP/gitpoulpi-tui.exe\"{flag} %*\r\n"
)
);
assert_eq!(parts(shim_parts(&text)), Some((exe.to_path_buf(), kind)));
}
}
#[test]
fn an_old_shim_reads_outdated_and_create_rewrites_it() {
let tmp = tempfile::tempdir().unwrap();
let mut e = env(tmp.path(), Os::Windows);
e.exe = PathBuf::from("C:/GP/gitpoulpi-tui.exe");
std::fs::create_dir_all(&e.bin_dir).unwrap();
let old = "@echo off\r\nREM X-GitPoulpi=1\r\n\"C:/GP/gitpoulpi-tui.exe\" %*\r\n";
std::fs::write(e.bin_dir.join("gp.cmd"), old).unwrap();
assert_eq!(status(&e, "gp").state, State::Outdated);
assert_eq!(
list_kinds(&e),
[("gp".to_string(), Kind::Open, State::Outdated)]
);
create(&e, "gp").unwrap();
assert_eq!(status(&e, "gp").state, State::Installed);
}
fn windows_env_with_helper(root: &Path) -> (Env, PathBuf) {
let mut e = env(root, Os::Windows);
e.exe = PathBuf::from("C:/GP/gitpoulpi-tui.exe");
(e, PathBuf::from("C:/GP/gitpoulpi-launch.exe"))
}
#[test]
fn app_paths_follow_the_open_alias() {
use crate::desktop::registry::MemoryRegistry;
let tmp = tempfile::tempdir().unwrap();
let (e, helper) = windows_env_with_helper(tmp.path());
let reg = MemoryRegistry::new();
let has = |p: &Path| p == helper;
create_with_app_path_in(&e, ®, "gp", Kind::Open, &has).unwrap();
let key = app_path_key("gp.exe");
let dump = reg.dump();
assert!(
dump.iter().any(|(k, n, v)| k.eq_ignore_ascii_case(&key)
&& n.is_empty()
&& v.ends_with("gitpoulpi-launch.exe")),
"{dump:?}"
);
assert_eq!(app_path_is_ours(®, "gp.exe").unwrap(), Some(true));
create_with_app_path_in(&e, ®, "gpa", Kind::Add, &has).unwrap();
assert_eq!(app_path_is_ours(®, "gpa.exe").unwrap(), None);
assert!(remove_with_app_path(&e, ®, "gp").unwrap());
assert_eq!(app_path_is_ours(®, "gp.exe").unwrap(), None);
}
#[test]
fn app_paths_skip_without_a_launcher_and_spare_a_foreign_key() {
use crate::desktop::registry::{MemoryRegistry, RegOp};
let tmp = tempfile::tempdir().unwrap();
let (e, helper) = windows_env_with_helper(tmp.path());
let reg = MemoryRegistry::new();
create_with_app_path_in(&e, ®, "gp", Kind::Open, &|_| false).unwrap();
assert!(reg.dump().is_empty(), "no launcher: no key");
let key = app_path_key("gp.exe");
reg.apply(&[RegOp::Set {
key: key.clone(),
name: String::new(),
value: "D:/other.exe".into(),
}])
.unwrap();
create_with_app_path_in(&e, ®, "gp", Kind::Open, &|p| p == helper).unwrap();
assert_eq!(app_path_is_ours(®, "gp.exe").unwrap(), Some(false));
assert!(remove_with_app_path(&e, ®, "gp").unwrap());
assert_eq!(app_path_is_ours(®, "gp.exe").unwrap(), Some(false));
let lin = env(tmp.path(), Os::Linux);
let reg2 = MemoryRegistry::new();
let _ = create_with_app_path_in(&lin, ®2, "gp", Kind::Open, &|_| true);
assert!(reg2.dump().is_empty());
}
}