From 162e5db94e773410c24edcc44c67c4faa241bf3f Mon Sep 17 00:00:00 2001 From: Francesc Date: Fri, 13 Nov 2026 08:26:45 +0100 Subject: [PATCH] feat: it says when there is a newer version, and brings its file down A program installed once that never says another word is one still on its first beta a year later. So it looks -- a little after the window opens and once a day -- and when there is something newer a word appears at the end of the tab strip, beside the gear. Nothing else happens until the word is pressed: no dialog, nothing brought down. Pressed, it offers the file for this system, the .deb to whoever took the .deb and the folder to whoever did not, puts it where downloads go and checks it against the SHA256SUMS published beside it. It has another name until it has been checked. A version can be told not to be mentioned again, the whole thing can be turned off, and a beta is offered to whoever asks for betas and to whoever is running one. It does not install anything. Each system installs a different way, one wants a password, another will not let a running program be written over, and none of the files is signed: a program that replaced itself with something it could not vouch for would be worse than one that leaves the last step to whoever is sitting there. Looking costs no dependency. A version is a tag, and listing a repository's tags is the one thing this program could always do -- no API, no account, nothing sent that a clone does not send. But a tag is not a release: the files take a while to be built from it, and a tag pushed by mistake never gets any, so a newer tag is mentioned only once the sums published with its files can be read, and one without them is passed over for the one before. Bringing the file down is curl, over HTTPS and nothing else, instead of a library for it and the forty crates behind one for a request a month. With no curl it says so and the release's page is a click away. The SHA-256 is written out, sixty lines held to the published answers. It is a connection to github.com that nobody asked for, and SECURITY.md now says so beside the other things the window does by itself. Opening an address went through xdg-open, which only Linux has. It goes through the program each system has for it now, here and for the links that were already there. Tried on Linux against the releases there are, by a build told it was older than it is: the look, the file, the check against sha256sum's own answer, a tag with no release behind it, the word, its menu, the preferences. The buttons that hand the file to the desktop were not pressed, and nothing of it has been seen on macOS or Windows. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Francesc --- README.md | 37 +- SECURITY.md | 15 +- crates/gitrust-core/src/lib.rs | 1 + crates/gitrust-core/src/settings.rs | 32 +- crates/gitrust-core/src/update.rs | 779 ++++++++++++++++++++++++++++ crates/gitrust-ui/src/main.rs | 62 ++- crates/gitrust-ui/src/prefs_view.rs | 66 +++ crates/gitrust-ui/src/updates.rs | 426 +++++++++++++++ 8 files changed, 1412 insertions(+), 6 deletions(-) create mode 100644 crates/gitrust-core/src/update.rs create mode 100644 crates/gitrust-ui/src/updates.rs diff --git a/README.md b/README.md index c8e518d..302e466 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,8 @@ cherry-pick and an undo all stop here instead of being thrown away. is typed into it - [x] The window keeps up by itself with what an editor, a terminal or an agent does to the repository in front, with no button to press +- [x] It says when there is a newer version, and brings the file for this + system down, checked -- and leaves installing it to you - [ ] Three-way editor with line-by-line picking - [ ] A screen for the submodules themselves, bisect, LFS, signing @@ -147,6 +149,7 @@ crates/ merge.rs joining two branches or rebasing one, and stopping where it clashes conflict.rs getting out of a merge or rebase that clashed tag.rs lightweight and annotated tags + update.rs whether there is a newer version, and its file, checked remote.rs fetching, pushing, and the distance to the remote branch stash.rs the pile of changes set aside graph.rs the lane algorithm, and the uncommitted-changes row @@ -181,6 +184,7 @@ crates/ terminal.rs a shell per tab: the pseudo-terminal, the keys, the colours terminal_view.rs the grid painted, the mouse heard, and the bar above it watch.rs looking at the repository in front, off the painting thread + updates.rs the word for a newer version, and the menu under it chooser.rs asking the desktop for its own folder dialog graph_view.rs painting the graph and the references column board_view.rs the branches laid out in columns @@ -433,6 +437,35 @@ looked at when they are brought forward. Not a checkout on another machine, where every look is a round trip on a connection the window is using: its reload button is where it was. Run on Linux. +**A newer version:** a program installed once that never says another +word is one still on its first beta a year later. So it looks -- a little +after the window opens and once a day -- and when there is something newer +a word appears at the end of the tab strip. Nothing else: no dialog, and +nothing brought down until the word is pressed. Then it offers the file +for this system, the `.deb` to whoever took the `.deb` and the folder to +whoever did not, puts it where downloads go, and checks it against the +`SHA256SUMS` published beside it. There it stops. Each system installs a +different way, one wants a password, another will not let a running program +be written over, and none of the files is signed: a program that replaced +itself with something it could not vouch for would be worse than one that +leaves the last step to you. Looking costs no dependency -- a version is a +tag, and listing a repository's tags is the one thing this program could +always do; there is no API in it, no account and nothing sent that a clone +does not send. A tag is not a release, though: the files take a while to +be built from it, and a tag pushed by mistake never gets any. So a newer +tag is only mentioned once the sums published with its files can be read, +and one without them is passed over for the one before. Bringing the file down is `curl`, which Linux nearly always +has and macOS and Windows ship, instead of a library for HTTPS and the +forty crates behind it for one request a month; with no `curl` it says so +and the release's page is a click away. The SHA-256 is written out, sixty +lines held to the published answers. A beta is offered to whoever asks for +betas and to whoever is running one. It can be turned off, and a version +can be told not to be mentioned again. Tried on Linux against the releases +there are, by a build told it was older than it is: the look, the file, +the check, and the two refusals. The buttons that hand the file to the +desktop use a different program on each system, and only Linux's has been +run. + **The emulator:** the second dependency that was not part of the plan, and the one there was never going to be a way round. What a shell writes is forty years of escape sequences -- the second screen `vim` draws on, @@ -513,7 +546,9 @@ gets wrong is wanted as an issue. Take one: | macOS, Apple or Intel | the `.zip`: drag `Gitrust.app` to Applications | | Windows | the `.zip`: there is no installer, the `.exe` runs from wherever you put it | -Whichever you took, `gitrust --version` says which one it is. +Whichever you took, `gitrust --version` says which one it is, and from then +on the window says when there is a newer one and will bring its file down +for you. It will not install it: that is the same step as the first time. **None of it is signed.** There is no paid certificate behind these files, so macOS will say the developer cannot be verified -- right-click, Open, diff --git a/SECURITY.md b/SECURITY.md index 897bdc6..42b92fe 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -77,7 +77,7 @@ token is written down nowhere else. ## What the window does by itself -Three things happen without being asked for, and each can be turned off on +Four things happen without being asked for, and each can be turned off on the preferences screen. **It fetches**, every minute by default, from every remote of the repository @@ -103,6 +103,19 @@ submodule is left and named. **It tries the merge** into the target branch in memory. That reads the repository and writes nothing: no file, no index, no reference. +**It asks whether there is a newer version**, a little after the window +opens and once a day. That is a connection to github.com, to this project's +own repository, asking for the list of its tags: what a clone of a public +repository sends, with no credentials and nothing about you or your +repositories. When a tag is newer, the `SHA256SUMS` published with it is +asked for too, with `curl`, to know the release is really there. Nothing +else is brought down by it. A file is fetched only when +you press the button that says so, with `curl`, over HTTPS and nothing +else, and is checked against the `SHA256SUMS` the release publishes before +it is given its name. That check says the file arrived as it was built. It +does not say who built it: the sums come from the same place as the file, +and nothing here is signed. gitrust never installs what it brought down. + The tabs that were open are written into `~/.config/gitrust/settings` as paths, and remote checkouts as `ssh://user@host:port/path`. No password is among them, and a remote tab that comes back does not connect until asked. diff --git a/crates/gitrust-core/src/lib.rs b/crates/gitrust-core/src/lib.rs index 628c379..083e1f4 100644 --- a/crates/gitrust-core/src/lib.rs +++ b/crates/gitrust-core/src/lib.rs @@ -34,6 +34,7 @@ pub mod start; pub mod status; pub mod submodule; pub mod tag; +pub mod update; pub mod worktree; pub mod writer; diff --git a/crates/gitrust-core/src/settings.rs b/crates/gitrust-core/src/settings.rs index a7e677c..b43fca9 100644 --- a/crates/gitrust-core/src/settings.rs +++ b/crates/gitrust-core/src/settings.rs @@ -225,6 +225,17 @@ pub struct General { /// The program the terminal runs. Empty is the shell this account logs /// in with. pub terminal_shell: String, + /// Whether the window asks, now and then, if there is a newer version. + /// + /// On unless somebody says otherwise, like the fetch nobody asked for + /// and for the opposite reason: that one is off because it reaches a + /// remote with somebody's key, and this one reaches a public + /// repository with nothing. A program that never mentions the next + /// version is one still on its first a year later. + pub updates: bool, + /// Whether a beta counts as newer. Whoever is running a beta is told + /// about the next one whatever this says. + pub update_betas: bool, } impl Default for General { @@ -248,6 +259,8 @@ impl Default for General { terminal_caret: Caret::default(), terminal_dim: true, terminal_shell: String::new(), + updates: true, + update_betas: false, } } } @@ -312,6 +325,8 @@ impl General { // The rest of the line and not a word of it, as for a tab: a // program can live in a folder with a space in its name. "terminal-shell" => self.terminal_shell = value.to_string(), + "check-updates" => self.updates = on, + "update-betas" => self.update_betas = on, _ => return false, } true @@ -352,6 +367,11 @@ impl General { if !self.terminal_shell.trim().is_empty() { text.push_str(&format!("terminal-shell {}\n", self.terminal_shell.trim())); } + text.push_str(&format!( + "check-updates {}\nupdate-betas {}\n", + word(self.updates), + word(self.update_betas), + )); text } } @@ -384,6 +404,9 @@ pub struct Settings { pub terminal: Panel, /// How tall it is when all of it is showing, in points. pub terminal_height: u32, + /// The version somebody said not to mention again, as its tag. The + /// one after it is mentioned: this is "not this one", not "never". + pub skipped: String, } impl Default for Settings { @@ -397,6 +420,7 @@ impl Default for Settings { front: 0, terminal: Panel::default(), terminal_height: 280, + skipped: String::new(), } } } @@ -456,6 +480,7 @@ impl Settings { points.clamp(SHORTEST_TERMINAL, TALLEST_TERMINAL); } } + Some(("skip-update", value)) => settings.skipped = value.trim().to_string(), Some((name, value)) => { settings.general.take(name, value); } @@ -496,6 +521,9 @@ impl Settings { self.terminal.as_str(), self.terminal_height )); + if !self.skipped.is_empty() { + text.push_str(&format!("skip-update {}\n", self.skipped)); + } text } @@ -607,8 +635,10 @@ mod tests { terminal_caret: Caret::Underline, terminal_dim: false, terminal_shell: "/opt/my shells/fish".to_string(), + updates: false, + update_betas: true, }; - let settings = Settings { general, ..Settings::default() }; + let settings = Settings { general, skipped: "v0.2.0".to_string(), ..Settings::default() }; assert_eq!(Settings::parse(&settings.render()), settings); // And the defaults, which is the case with no branch name to write. assert_eq!(Settings::parse(&Settings::default().render()), Settings::default()); diff --git a/crates/gitrust-core/src/update.rs b/crates/gitrust-core/src/update.rs new file mode 100644 index 0000000..0179aca --- /dev/null +++ b/crates/gitrust-core/src/update.rs @@ -0,0 +1,779 @@ +//! Knowing there is a newer version, and bringing it down. +//! +//! A program that is installed once and never says another word is one +//! that is still on its first beta a year later. So it looks, and says +//! so, and will fetch the file for this system if asked -- and stops +//! there. It does not install anything. Each system installs a different +//! way, one of them wants a password, another will not let a running +//! program be written over, and none of these files is signed: a program +//! that replaced itself with something it could not vouch for would be +//! worse than one that left the last step to whoever is sitting there. +//! +//! **Looking** costs no dependency. A version is a tag, the tags of a +//! repository are what `git ls-remote` lists, and talking to a Git +//! remote is the one thing this program was always able to do. No API, +//! no account, no limit on how often -- and nothing sent but what any +//! clone of a public repository sends. +//! +//! A tag is not a release, though, and only a release is offered: see +//! `first_published`. +//! +//! **Bringing down** is `curl`, which Linux nearly always has and macOS +//! and Windows ship. The alternative was a library for HTTPS and the +//! forty crates behind it, for one request a month. Where there is no +//! `curl` this says so, and the page of the release is still a click +//! away. +//! +//! **Checking** is against the `SHA256SUMS` published beside the files, +//! with a SHA-256 written out here because it is sixty lines and the +//! same on every system. It proves what arrived is what was built. It +//! says nothing about who built it, which is what signing is for and +//! what there is none of. + +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use anyhow::{ensure, Context, Result}; + +/// Where the program lives: its repository, and under it the releases. +pub const HOME: &str = "https://github.com/FrancescBagur/gitrust"; + +/// One piece of what follows the hyphen in `0.1.0-beta.2`. +/// +/// In this order on purpose: a number sorts before a word, which is what +/// the people who write versions down agreed on and what deriving the +/// comparison gives for free. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +enum Part { + Number(u64), + Word(String), +} + +/// A version, as Cargo writes one and as a tag carries one behind a `v`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Version { + numbers: [u64; 3], + /// What follows a hyphen, in pieces. Empty for a version that is not + /// a beta of anything. + before: Vec, + /// As it was written, without the `v`. + text: String, +} + +impl Version { + /// Reads `0.1.0`, `v0.1.0` or `0.1.0-beta.2`. Anything else is not a + /// version: a tag called `nightly` is not a release to offer anybody. + pub fn parse(text: &str) -> Option { + let text = text.trim(); + let text = text.strip_prefix('v').unwrap_or(text); + // Build metadata says where a version came from, not which it is. + let plain = text.split('+').next()?; + let (numbers, before) = match plain.split_once('-') { + Some((numbers, before)) => (numbers, Some(before)), + None => (plain, None), + }; + let mut read = numbers.split('.').map(|number| match number.is_empty() { + true => None, + false => number.parse::().ok(), + }); + let numbers = [read.next()??, read.next()??, read.next()??]; + if read.next().is_some() { + return None; + } + let before = match before { + None => Vec::new(), + Some("") => return None, + Some(before) => before + .split('.') + .map(|part| match part.parse::() { + Ok(number) => Some(Part::Number(number)), + Err(_) if part.is_empty() => None, + Err(_) => Some(Part::Word(part.to_string())), + }) + .collect::>>()?, + }; + Some(Self { numbers, before, text: text.to_string() }) + } + + /// The version this program was built as. + pub fn running() -> Self { + Self::parse(env!("CARGO_PKG_VERSION")).expect("Cargo writes versions this can read") + } + + /// Whether it is a version on the way to one, and not one. + pub fn is_beta(&self) -> bool { + !self.before.is_empty() + } +} + +impl std::fmt::Display for Version { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.text) + } +} + +impl PartialOrd for Version { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Version { + /// `0.1.0-beta.1`, then `0.1.0-beta.2`, then `0.1.0`: a beta comes + /// before the version it is a beta of, however it is spelled. + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.numbers.cmp(&other.numbers).then_with(|| { + match (self.before.is_empty(), other.before.is_empty()) { + (true, true) => std::cmp::Ordering::Equal, + (true, false) => std::cmp::Ordering::Greater, + (false, true) => std::cmp::Ordering::Less, + (false, false) => self.before.cmp(&other.before), + } + }) + } +} + +/// A version that is out, and newer than the one running. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Release { + pub version: Version, + /// The tag it was published from, `v` and all. + pub tag: String, + /// The `SHA256SUMS` published with it, read when it was found. What + /// a file brought down later is checked against -- and having it at + /// all is how a release is known to be one, and not only a tag. + /// `None` when there was no way to ask. + sums: Option, +} + +impl Release { + /// The page that says what is in it, and has every file. + pub fn page(&self) -> String { + format!("{HOME}/releases/tag/{}", self.tag) + } + + /// The file for the system this is running on, when there is one. + pub fn file(&self) -> Option { + file_for( + &self.version.text, + std::env::consts::OS, + std::env::consts::ARCH, + installed_as_a_package(), + ) + } + + fn address(&self, name: &str) -> String { + format!("{HOME}/releases/download/{}/{name}", self.tag) + } +} + +/// The name a release gives the file for a system. +/// +/// These are the names the release workflow writes, and they are written +/// in both places: change one and this stops finding the file, which the +/// test beside it is there to say out loud. +/// +/// `packaged` is whether this copy came from the `.deb`. Whoever took the +/// `.deb` is given the next `.deb`; whoever unpacked the folder or built +/// it is given the folder. Only what the release builds is offered -- +/// there is no Linux file for a processor that is not x86-64, and saying +/// "none" is better than handing over one that will not start. +pub fn file_for(version: &str, system: &str, processor: &str, packaged: bool) -> Option { + match (system, processor, packaged) { + ("linux", "x86_64", true) => Some(format!("gitrust_{version}_amd64.deb")), + ("linux", "x86_64", false) => Some(format!("gitrust-{version}-linux-x86_64.tar.gz")), + ("macos", _, _) => Some(format!("gitrust-{version}-macos-universal.zip")), + ("windows", "x86_64", _) => Some(format!("gitrust-{version}-windows-x86_64.zip")), + _ => None, + } +} + +/// Whether dpkg put this program here. +fn installed_as_a_package() -> bool { + cfg!(target_os = "linux") && Path::new("/var/lib/dpkg/info/gitrust.list").exists() +} + +/// The newest of those tags that is newer than what is running. +/// +/// Betas are offered to whoever asked for them, and to whoever is running +/// one: they asked by installing it, and a beta that is never told about +/// the next beta is stuck on the one with the bug it reported. +pub fn newest<'a>(tags: impl IntoIterator, running: &Version, betas: bool) -> Option { + newer(tags, running, betas).into_iter().next() +} + +/// Every tag that is newer than what is running, newest first. +fn newer<'a>(tags: impl IntoIterator, running: &Version, betas: bool) -> Vec { + let betas = betas || running.is_beta(); + let mut found: Vec = tags + .into_iter() + .filter_map(|tag| { + let tag = tag.strip_prefix("refs/tags/").unwrap_or(tag); + // The second line a tag with a message gets in the listing. + if tag.ends_with("^{}") || !tag.starts_with('v') { + return None; + } + let version = Version::parse(tag)?; + Some(Release { version, tag: tag.to_string(), sums: None }) + }) + .filter(|release| release.version > *running && (betas || !release.version.is_beta())) + .collect(); + found.sort_by(|one, other| other.version.cmp(&one.version)); + found +} + +/// What asking for a release's sums came back with. +enum Asked { + /// They are there: it is published. + Sums(String), + /// The tag is there and the release is not, or not yet. + Nothing, + /// There is no `curl` to ask with. + NoWay, +} + +/// The newest of those that has really been published. +/// +/// A tag is not a release. The files are built from the tag and take a +/// while, and a tag pushed by mistake never gets any -- the workflow +/// refuses one that disagrees with the version in the source. Offering +/// a version on the strength of its tag would be offering, to everybody +/// who has the program, a download that is not there. So the sums are +/// asked for, and a tag without them is passed over for the one before. +/// +/// Only the few newest are asked about. With no way of asking, the +/// newest tag is offered as it is: its page is still worth a visit. +fn first_published( + candidates: Vec, + mut ask: impl FnMut(&Release) -> Result, +) -> Result> { + for mut release in candidates.into_iter().take(3) { + match ask(&release)? { + Asked::Sums(sums) => { + release.sums = Some(sums); + return Ok(Some(release)); + } + Asked::Nothing => continue, + Asked::NoWay => return Ok(Some(release)), + } + } + Ok(None) +} + +/// Asks the repository which versions there are, and gives back the one +/// worth mentioning, if any. +/// +/// Over the network, so never from the thread that paints. With no +/// network this is an error, and whoever asked decides whether it is one +/// worth showing -- looking unasked and finding no network is not. +pub fn look(running: &Version, betas: bool) -> Result> { + let mut remote = git2::Remote::create_detached(HOME).context("could not prepare to ask for the versions")?; + remote + .connect(git2::Direction::Fetch) + .with_context(|| format!("could not reach {HOME}"))?; + let listed = remote.list().context("the list of versions did not arrive")?; + let tags: Vec<&str> = listed.iter().map(|head| head.name()).collect(); + first_published(newer(tags, running, betas), |release| { + match ask(&release.address("SHA256SUMS"), None) { + Ok(sums) => Ok(String::from_utf8(sums).map(Asked::Sums).unwrap_or(Asked::Nothing)), + Err(Trouble::Refused(_)) => Ok(Asked::Nothing), + Err(Trouble::NoCurl(_)) => Ok(Asked::NoWay), + Err(trouble) => Err(trouble.into_error(&release.address("SHA256SUMS"))), + } + }) +} + +/// Brings a release's file for this system into `folder`, and checks it. +/// +/// Gives back where it is. A file already there under that name is kept +/// if it is the right one and written over if it is not. What is being +/// brought down has another name until it has been checked, so nothing +/// half-arrived or wrong is ever left looking like the real thing. +pub fn fetch(release: &Release, folder: &Path) -> Result { + let name = release + .file() + .with_context(|| format!("{} has no file for this system; its page has all of them", release.tag))?; + let sums = match &release.sums { + Some(sums) => sums.clone(), + None => String::from_utf8(get(&release.address("SHA256SUMS"), None)?) + .context("the release's SHA256SUMS is not text")?, + }; + let wanted = sum_for(&sums, &name) + .with_context(|| format!("the release's SHA256SUMS does not name {name}, so it cannot be checked"))? + .to_string(); + + let place = folder.join(&name); + if place.is_file() && sha256_of(&place).is_ok_and(|found| found == wanted) { + return Ok(place); + } + + std::fs::create_dir_all(folder).with_context(|| format!("could not make {}", folder.display()))?; + let arriving = folder.join(format!("{name}.part")); + let brought = get(&release.address(&name), Some(&arriving)).and_then(|_| { + let found = sha256_of(&arriving)?; + ensure!( + found == wanted, + "{name} did not arrive as it was published: its SHA-256 is {found} and the release says {wanted}" + ); + std::fs::rename(&arriving, &place).with_context(|| format!("could not write {}", place.display())) + }); + if brought.is_err() { + let _ = std::fs::remove_file(&arriving); + } + brought.map(|()| place) +} + +/// Why a request came back with nothing. +enum Trouble { + /// `curl` could not be run at all. + NoCurl(std::io::Error), + /// The server answered, and the answer was no: what was asked for is + /// not there. + Refused(String), + /// Anything else, which is nearly always the network. + Failed(String), +} + +impl Trouble { + fn into_error(self, address: &str) -> anyhow::Error { + match self { + Trouble::NoCurl(err) => anyhow::Error::new(err) + .context("curl is needed to bring a file down, and it could not be run"), + Trouble::Refused(said) | Trouble::Failed(said) => { + anyhow::anyhow!("{address} did not come down: {said}") + } + } + } +} + +/// One request, with `curl`: into a file, or into memory for something +/// small. +fn get(address: &str, into: Option<&Path>) -> Result> { + ask(address, into).map_err(|trouble| trouble.into_error(address)) +} + +/// The same, saying which way it went wrong. +/// +/// HTTPS and nothing else, at the first address and at every one it is +/// sent on to -- a release file is served from somewhere other than +/// where it is asked for. +fn ask(address: &str, into: Option<&Path>) -> std::result::Result, Trouble> { + let mut curl = Command::new("curl"); + curl.args([ + "--fail", + "--location", + "--silent", + "--show-error", + "--proto", + "=https", + "--proto-redir", + "=https", + "--connect-timeout", + "20", + "--max-time", + "900", + "--output", + ]); + match into { + Some(file) => curl.arg(file), + None => curl.arg("-"), + }; + curl.arg(address); + quiet(&mut curl); + let done = curl.output().map_err(Trouble::NoCurl)?; + if done.status.success() { + return Ok(done.stdout); + } + let said = String::from_utf8_lossy(&done.stderr); + let said = said.trim().trim_start_matches("curl: ").to_string(); + // What `--fail` leaves with when the server said no. + Err(match done.status.code() { + Some(22) => Trouble::Refused(said), + _ => Trouble::Failed(said), + }) +} + +/// A program run from a window on Windows opens a black one of its own +/// unless it is told not to. +fn quiet(command: &mut Command) { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x0800_0000); + } + #[cfg(not(windows))] + { + let _ = command; + } +} + +/// The line of a `SHA256SUMS` that is about `name`: its sum. +/// +/// `sha256sum` writes the sum, two spaces or a space and a star, and the +/// name. Only a whole name counts, and only a sum that is one. +pub fn sum_for<'a>(sums: &'a str, name: &str) -> Option<&'a str> { + sums.lines().find_map(|line| { + let (sum, file) = line.split_once(' ')?; + let file = file.trim_start_matches([' ', '*']).trim_end(); + (file == name && sum.len() == 64 && sum.bytes().all(|byte| byte.is_ascii_hexdigit())).then_some(sum) + }) +} + +/// Where a file somebody asked for goes: the folder the desktop calls +/// Downloads, whatever it is called in their language. +/// +/// On Linux that is written down in `user-dirs.dirs`; everywhere else, +/// and where that file says nothing, it is `Downloads` under the home +/// folder, and failing that the home folder. +pub fn downloads() -> Option { + let home = crate::home::folder()?; + let named = crate::home::config() + .and_then(|ours| Some(ours.parent()?.join("user-dirs.dirs"))) + .and_then(|file| std::fs::read_to_string(file).ok()) + .and_then(|text| downloads_in(&text, &home)); + let usual = home.join("Downloads"); + named + .filter(|folder| folder.is_dir()) + .or_else(|| usual.is_dir().then_some(usual)) + .or(Some(home)) +} + +/// The `XDG_DOWNLOAD_DIR="$HOME/Descargas"` line of `user-dirs.dirs`. +fn downloads_in(text: &str, home: &Path) -> Option { + let value = text + .lines() + .find_map(|line| line.trim().strip_prefix("XDG_DOWNLOAD_DIR="))? + .trim() + .trim_matches('"'); + match value.strip_prefix("$HOME/") { + Some(rest) => Some(home.join(rest)), + None if value.starts_with('/') => Some(PathBuf::from(value)), + None => None, + } +} + +/// The SHA-256 of a file, as `sha256sum` prints it. +pub fn sha256_of(file: &Path) -> Result { + let mut file = File::open(file).with_context(|| format!("could not read {}", file.display()))?; + let mut sum = Sha256::new(); + let mut piece = vec![0u8; 1 << 16]; + loop { + let read = file.read(&mut piece).context("could not read what was brought down")?; + if read == 0 { + break; + } + sum.take(&piece[..read]); + } + Ok(sum.finish()) +} + +/// SHA-256, as FIPS 180-4 writes it down. +/// +/// Here and not in a crate because it is this much, has not changed since +/// 2002, and the test beside it holds it to the published answers. +struct Sha256 { + state: [u32; 8], + /// What has arrived and does not yet fill a block. + held: Vec, + length: u64, +} + +const ROUNDS: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +impl Sha256 { + fn new() -> Self { + Self { + state: [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ], + held: Vec::with_capacity(64), + length: 0, + } + } + + fn take(&mut self, mut bytes: &[u8]) { + self.length += bytes.len() as u64; + if !self.held.is_empty() { + let wanted = (64 - self.held.len()).min(bytes.len()); + self.held.extend_from_slice(&bytes[..wanted]); + bytes = &bytes[wanted..]; + if self.held.len() < 64 { + return; + } + let block: [u8; 64] = self.held[..].try_into().expect("sixty-four were counted"); + self.block(&block); + self.held.clear(); + } + let mut blocks = bytes.chunks_exact(64); + for block in &mut blocks { + self.block(block.try_into().expect("chunks of sixty-four")); + } + self.held.extend_from_slice(blocks.remainder()); + } + + fn finish(mut self) -> String { + let bits = self.length.wrapping_mul(8); + let mut tail = vec![0x80u8]; + let filled = (self.held.len() + 1) % 64; + tail.resize(1 + (120 - filled) % 64, 0); + tail.extend_from_slice(&bits.to_be_bytes()); + // Not counted: `length` was read above, and this is not the file. + self.take(&tail); + debug_assert!(self.held.is_empty()); + self.state.iter().map(|word| format!("{word:08x}")).collect() + } + + fn block(&mut self, block: &[u8; 64]) { + let mut words = [0u32; 64]; + for (word, bytes) in words.iter_mut().zip(block.chunks_exact(4)) { + *word = u32::from_be_bytes(bytes.try_into().expect("chunks of four")); + } + for at in 16..64 { + let early = words[at - 15].rotate_right(7) ^ words[at - 15].rotate_right(18) ^ (words[at - 15] >> 3); + let late = words[at - 2].rotate_right(17) ^ words[at - 2].rotate_right(19) ^ (words[at - 2] >> 10); + words[at] = words[at - 16] + .wrapping_add(early) + .wrapping_add(words[at - 7]) + .wrapping_add(late); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state; + for at in 0..64 { + let mix = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let choice = (e & f) ^ (!e & g); + let one = h + .wrapping_add(mix) + .wrapping_add(choice) + .wrapping_add(ROUNDS[at]) + .wrapping_add(words[at]); + let mix = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let majority = (a & b) ^ (a & c) ^ (b & c); + let two = mix.wrapping_add(majority); + h = g; + g = f; + f = e; + e = d.wrapping_add(one); + d = c; + c = b; + b = a; + a = one.wrapping_add(two); + } + for (kept, new) in self.state.iter_mut().zip([a, b, c, d, e, f, g, h]) { + *kept = kept.wrapping_add(new); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn version(text: &str) -> Version { + Version::parse(text).unwrap_or_else(|| panic!("{text} is a version")) + } + + fn sha256(bytes: &[u8]) -> String { + let mut sum = Sha256::new(); + sum.take(bytes); + sum.finish() + } + + #[test] + fn a_beta_comes_before_the_version_it_is_a_beta_of() { + let order = [ + "0.1.0-alpha", + "0.1.0-beta.1", + "0.1.0-beta.2", + "0.1.0-beta.10", + "0.1.0-rc.1", + "0.1.0", + "0.1.1", + "0.2.0-beta.1", + "0.2.0", + "1.0.0", + ]; + for pair in order.windows(2) { + assert!(version(pair[0]) < version(pair[1]), "{} is not before {}", pair[0], pair[1]); + } + // A tag is the same version with a letter in front. + assert_eq!(version("v0.1.0-beta.1"), version("0.1.0-beta.1")); + assert_eq!(version("v0.1.0-beta.1").to_string(), "0.1.0-beta.1"); + assert!(version("0.1.0-beta.1").is_beta()); + assert!(!version("0.1.0").is_beta()); + } + + #[test] + fn what_is_not_a_version_is_not_read_as_one() { + for text in ["", "v", "nightly", "1.2", "1.2.3.4", "1.2.x", "1.2.3-", "1.2.3-beta..1", "1..3", "-1.2.3"] { + assert!(Version::parse(text).is_none(), "{text:?} was read as a version"); + } + // And the one this was built as is. + assert_eq!(Version::running().to_string(), env!("CARGO_PKG_VERSION")); + } + + #[test] + fn the_newest_tag_is_offered_and_betas_only_to_whoever_wants_them() { + let tags = [ + "refs/heads/master", + "refs/tags/v0.1.0-beta.1", + "refs/tags/v0.1.0", + "refs/tags/v0.1.0^{}", + "refs/tags/v0.2.0-beta.1", + "refs/tags/nightly", + "refs/tags/0.9.0", + "refs/pull/14/head", + ]; + + // On a release, with nothing said: the newest release, and it has + // to be newer. + assert_eq!(newest(tags, &version("0.0.9"), false).unwrap().tag, "v0.1.0"); + assert_eq!(newest(tags, &version("0.1.0"), false), None); + // Having asked for betas, the beta of the next one. + let beta = newest(tags, &version("0.1.0"), true).unwrap(); + assert_eq!(beta.tag, "v0.2.0-beta.1"); + assert_eq!(beta.page(), format!("{HOME}/releases/tag/v0.2.0-beta.1")); + // Running a beta is having asked. + assert_eq!(newest(tags, &version("0.1.0-beta.1"), false).unwrap().tag, "v0.2.0-beta.1"); + // Nothing is offered to the newest there is, or to a newer one + // somebody built for themselves. + assert_eq!(newest(tags, &version("0.2.0-beta.1"), true), None); + assert_eq!(newest(tags, &version("3.0.0"), true), None); + } + + #[test] + fn a_tag_with_no_release_behind_it_is_passed_over() { + let tags = ["refs/tags/v0.1.0", "refs/tags/v0.2.0", "refs/tags/v0.3.0"]; + let candidates = || newer(tags, &version("0.0.9"), false); + assert_eq!( + candidates().iter().map(|release| release.tag.as_str()).collect::>(), + ["v0.3.0", "v0.2.0", "v0.1.0"] + ); + + // The newest is only a tag so far: the one before it is offered, + // with the sums it will be checked against. + let found = first_published(candidates(), |release| { + Ok(match release.tag.as_str() { + "v0.3.0" => Asked::Nothing, + _ => Asked::Sums(format!("sums of {}", release.tag)), + }) + }) + .unwrap() + .unwrap(); + assert_eq!(found.tag, "v0.2.0"); + assert_eq!(found.sums.as_deref(), Some("sums of v0.2.0")); + + // None of them published: nothing to say. + assert_eq!(first_published(candidates(), |_| Ok(Asked::Nothing)).unwrap(), None); + // No way of asking: the newest tag, as it is. + let found = first_published(candidates(), |_| Ok(Asked::NoWay)).unwrap().unwrap(); + assert_eq!((found.tag.as_str(), &found.sums), ("v0.3.0", &None)); + // And no network is an error, not "nothing newer". + assert!(first_published(candidates(), |_| anyhow::bail!("no network")).is_err()); + // With nothing newer, nobody is asked anything. + assert_eq!( + first_published(newer(tags, &version("1.0.0"), false), |_| panic!("asked")).unwrap(), + None + ); + } + + /// The names here are the ones `.github/workflows/release.yml` gives + /// the files. They are written in both places and nowhere else. + #[test] + fn each_system_is_given_the_file_the_release_made_for_it() { + let name = |system, processor, packaged| file_for("0.1.0-beta.2", system, processor, packaged); + assert_eq!(name("linux", "x86_64", true).unwrap(), "gitrust_0.1.0-beta.2_amd64.deb"); + assert_eq!(name("linux", "x86_64", false).unwrap(), "gitrust-0.1.0-beta.2-linux-x86_64.tar.gz"); + assert_eq!(name("macos", "aarch64", false).unwrap(), "gitrust-0.1.0-beta.2-macos-universal.zip"); + assert_eq!(name("macos", "x86_64", false).unwrap(), "gitrust-0.1.0-beta.2-macos-universal.zip"); + assert_eq!(name("windows", "x86_64", false).unwrap(), "gitrust-0.1.0-beta.2-windows-x86_64.zip"); + // What the release does not build is not offered. + assert_eq!(name("linux", "aarch64", false), None); + assert_eq!(name("windows", "aarch64", false), None); + assert_eq!(name("freebsd", "x86_64", false), None); + + let workflow = include_str!("../../../.github/workflows/release.yml"); + for written in [ + "gitrust-$version-linux-x86_64", + "gitrust_${version}_${deb##*_}", + "gitrust-$version-macos-universal.zip", + "gitrust-$version-windows-x86_64", + ] { + assert!(workflow.contains(written), "the release no longer names a file {written}"); + } + } + + #[test] + fn a_sum_is_found_by_the_whole_name_and_only_if_it_is_one() { + let sum = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"; + let sums = format!( + "{sum} gitrust-0.2.0-linux-x86_64.tar.gz\n\ + {} gitrust_0.2.0_amd64.deb\n\ + {sum} *gitrust-0.2.0-windows-x86_64.zip\n\ + not-a-sum gitrust-0.2.0-macos-universal.zip\n", + "0".repeat(64) + ); + assert_eq!(sum_for(&sums, "gitrust-0.2.0-linux-x86_64.tar.gz"), Some(sum)); + assert_eq!(sum_for(&sums, "gitrust-0.2.0-windows-x86_64.zip"), Some(sum)); + assert_eq!(sum_for(&sums, "gitrust_0.2.0_amd64.deb").unwrap(), "0".repeat(64)); + // Part of a name is not the name, and a line that is not a sum + // vouches for nothing. + assert_eq!(sum_for(&sums, "linux-x86_64.tar.gz"), None); + assert_eq!(sum_for(&sums, "gitrust-0.2.0-macos-universal.zip"), None); + assert_eq!(sum_for(&sums, "gitrust-0.3.0-linux-x86_64.tar.gz"), None); + } + + /// The answers the standard publishes, and the lengths around a block + /// where a mistake in the padding would be. + #[test] + fn sha256_gives_the_published_answers() { + assert_eq!(sha256(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + assert_eq!(sha256(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + assert_eq!( + sha256(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + assert_eq!( + sha256(&[b'a'; 1_000_000]), + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" + ); + for (length, wanted) in [ + (55, "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"), + (56, "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"), + (63, "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"), + (64, "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"), + (65, "635361c48bb9eab14198e76ea8ab7f1a41685d6ad62aa9146d301d4f17eb0ae0"), + ] { + assert_eq!(sha256(&vec![b'a'; length]), wanted, "{length} bytes"); + } + + // Handed over a piece at a time, as a file is, it is the same sum. + let mut sum = Sha256::new(); + for piece in [b'a'; 1000].chunks(7) { + sum.take(piece); + } + assert_eq!(sum.finish(), sha256(&[b'a'; 1000])); + } + + #[test] + fn the_downloads_folder_is_the_one_the_desktop_names() { + let home = Path::new("/home/someone"); + let text = "# comment\nXDG_DESKTOP_DIR=\"$HOME/Escritorio\"\nXDG_DOWNLOAD_DIR=\"$HOME/Descargas\"\n"; + assert_eq!(downloads_in(text, home), Some(PathBuf::from("/home/someone/Descargas"))); + assert_eq!( + downloads_in("XDG_DOWNLOAD_DIR=\"/srv/incoming\"\n", home), + Some(PathBuf::from("/srv/incoming")) + ); + assert_eq!(downloads_in("XDG_DESKTOP_DIR=\"$HOME/Desktop\"\n", home), None); + assert_eq!(downloads_in("XDG_DOWNLOAD_DIR=\"somewhere\"\n", home), None); + } +} diff --git a/crates/gitrust-ui/src/main.rs b/crates/gitrust-ui/src/main.rs index 87964a6..31fe3d8 100644 --- a/crates/gitrust-ui/src/main.rs +++ b/crates/gitrust-ui/src/main.rs @@ -33,6 +33,7 @@ mod terminal; mod terminal_view; mod theme; mod toast; +mod updates; mod watch; use anyhow::Result; @@ -308,6 +309,9 @@ struct App { /// anything. Started with the first frame, which is the first time /// there is a window to wake. watch: Option, + /// Whether there is a newer version than this one, and the file for + /// it if somebody has asked for that. + updates: updates::Updates, /// What one of the screens that is not a repository has to say. A tab's /// own bottom bar cannot say it: the tab is not on screen. note: Option, @@ -413,6 +417,7 @@ impl App { preferring: None, fetched: std::time::Instant::now(), watch: None, + updates: updates::Updates::new(), note: None, }; app.come_back(asked); @@ -545,6 +550,34 @@ impl App { ctx.request_repaint_after(every); } + /// Does what was pressed in the menu under the word for a newer + /// version. + /// + /// Opening is handing something to the desktop, and the one thing + /// that can go wrong with it is that there is nothing to hand it to. + /// That is said on whichever screen is up. + fn act_on_update(&mut self, ctx: &egui::Context, act: updates::Act) { + let opened = match act { + updates::Act::Fetch => { + self.updates.fetch(ctx); + return; + } + updates::Act::Skip(tag) => { + self.settings.skipped = tag; + if let Err(err) = self.settings.save() { + self.complain(err); + } + return; + } + updates::Act::Open(file) => updates::open_outside(file), + updates::Act::Folder(folder) => updates::open_outside(folder), + updates::Act::Page(address) => updates::open_outside(address), + }; + if let Err(err) = opened { + self.complain(anyhow::anyhow!("could not open it: {err}")); + } + } + /// Keeps the repository in front up to date with what other programs /// do to it: an editor, a terminal, an agent. /// @@ -862,6 +895,7 @@ impl App { let mut go = None; let mut shut = None; let mut toggle_maximized = false; + let mut newer = None; egui::TopBottomPanel::top("tabs") .frame( @@ -948,6 +982,12 @@ impl App { self.chip(ui); ui.add_space(6.0); self.gear(ui); + // A newer version, when there is one, beside the + // other two things that are about the program and + // not about a repository. A word and not a dialog: + // it is there to be noticed, not to be answered. + ui.add_space(6.0); + newer = self.updates.word(ui, &self.settings.skipped); }); }); ui.add_space(4.0); @@ -957,6 +997,9 @@ impl App { let maximized = ctx.input(|input| input.viewport().maximized.unwrap_or(false)); ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(!maximized)); } + if let Some(act) = newer { + self.act_on_update(ctx, act); + } if let Some(which) = shut { self.close(which); @@ -1209,7 +1252,12 @@ impl App { .inner_margin(egui::Margin::symmetric(14, 0)), ) .show(ctx, |ui| { - (changed, act) = prefs_view::show(ui, state, &mut self.settings.general, tokens); + let newer = prefs_view::Newer { + running: self.updates.running(), + looking: self.updates.looking(), + answer: self.updates.answer(), + }; + (changed, act) = prefs_view::show(ui, state, &mut self.settings.general, tokens, newer); }); // Said only when it fails, as the switch for the waves is: a @@ -1238,6 +1286,13 @@ impl App { })); } } + Some(prefs_view::Act::Look) => { + // Asking is asking about every version: what was said not + // to be mentioned is mentioned again. + self.settings.skipped.clear(); + let _ = self.settings.save(); + self.updates.look_now(ctx, self.settings.general.update_betas); + } Some(prefs_view::Act::Close) => { self.preferring = None; self.note = None; @@ -1620,6 +1675,7 @@ impl eframe::App for App { } self.note_tabs(); self.keep_up(ctx); + self.updates.tick(ctx, self.settings.general.updates, self.settings.general.update_betas); // Always, even with one repository open: the plus lives in it, and a // strip that appears only once you have two tabs is a way of opening @@ -3541,8 +3597,8 @@ impl Open { /// second or two to appear and there is nothing to report when it does. /// What there is to report is it not being there at all. fn open_in_browser(&mut self, url: &str) { - match std::process::Command::new("xdg-open").arg(url).spawn() { - Ok(_) => { + match updates::open_outside(url) { + Ok(()) => { self.said(format!("opening {url}")); } Err(err) => self.note_error(format!("could not open a browser: {err}")), diff --git a/crates/gitrust-ui/src/prefs_view.rs b/crates/gitrust-ui/src/prefs_view.rs index 70438e6..9dd9bc4 100644 --- a/crates/gitrust-ui/src/prefs_view.rs +++ b/crates/gitrust-ui/src/prefs_view.rs @@ -31,10 +31,23 @@ pub enum Act { /// Take the token out of every account of every profile. Sent only /// after the second click. Forget, + /// Ask now whether there is a newer version. + Look, /// Put the screen away. Close, } +/// What the screen is told about newer versions, to show under its last +/// heading. It decides nothing about them. +pub struct Newer<'a> { + /// The version this is. + pub running: String, + /// Whether the question is being asked at this moment. + pub looking: bool, + /// What the last asking found, and whether that was a failure. + pub answer: Option<(&'a str, bool)>, +} + /// What the screen remembers between frames. pub struct Preferring { /// What is in the branch box, which is not always what is kept: a name @@ -83,6 +96,7 @@ pub fn show( state: &mut Preferring, general: &mut General, tokens: usize, + newer: Newer, ) -> (bool, Option) { let mut act = None; let before = general.clone(); @@ -413,6 +427,58 @@ pub fn show( ); }); + ui.add_space(8.0); + theme::rule(ui); + ui.add_space(12.0); + ui.horizontal(|ui| { + ui.add_space(28.0); + ui.label(RichText::new("Updates").font(theme::strong(15.0)).color(theme::text())); + }); + ui.add_space(14.0); + + row(ui, "Look for newer versions", |ui| { + ui.checkbox(&mut general.updates, ""); + help( + ui, + "Asks the project's repository which versions there are, a little after \ + the window opens and once a day. A newer one is a word at the end of \ + the tab strip, with the file for this system behind it. Nothing is \ + brought down until you ask and nothing is ever installed for you.", + ); + warning( + ui, + "It is a connection to github.com that nobody asked for. What is sent \ + is what cloning a public repository sends, and nothing about you.", + ); + }); + + row(ui, "Include betas", |ui| { + ui.checkbox(&mut general.update_betas, ""); + help( + ui, + "A beta counts as newer. Whoever is running a beta is told about the \ + next one whatever this says.", + ); + }); + + row(ui, "This version", |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(&newer.running).font(theme::mono(12.0)).color(theme::text())); + ui.add_space(8.0); + if ui.add_enabled(!newer.looking, egui::Button::new("Look now")).clicked() { + act = Some(Act::Look); + } + if newer.looking { + ui.spinner(); + } + }); + match newer.answer { + Some((text, true)) => complaint(ui, text), + Some((text, false)) => help(ui, text), + None => {} + } + }); + ui.add_space(24.0); }); diff --git a/crates/gitrust-ui/src/updates.rs b/crates/gitrust-ui/src/updates.rs new file mode 100644 index 0000000..a399f99 --- /dev/null +++ b/crates/gitrust-ui/src/updates.rs @@ -0,0 +1,426 @@ +//! The newer version: looking for it, saying so, and bringing it down. +//! +//! What the window does about [`gitrust_core::update`]. It looks a little +//! after it opens and once a day after that, on a thread of its own, +//! and when there is something newer a word appears at the end of the +//! tab strip. Nothing else happens until that word is pressed: no dialog +//! over the repository, nothing brought down, nothing installed. +//! +//! Pressed, it offers the file for this system. That is brought down to +//! the folder downloads go to, checked against the sums published beside +//! it, and left there with a button that opens it -- which on most +//! systems is what installing it starts with. The last step is whoever +//! is sitting there's, and why is in the module this one speaks for. +//! +//! A look that nobody asked for says nothing when it fails: no network +//! is not news. One asked for from the preferences says what happened. + +use std::path::PathBuf; +use std::sync::mpsc::{self, Receiver, TryRecvError}; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use eframe::egui::{self, RichText}; +use gitrust_core::update::{self, Release, Version}; + +use crate::theme; + +/// How long after the window opens the first look is made. Not at once: +/// the first seconds belong to the repository being read. +const FIRST: Duration = Duration::from_secs(15); +/// And how often after that. +const EVERY: Duration = Duration::from_secs(24 * 60 * 60); +/// After a look that could not be made, which is usually no network. +const AGAIN: Duration = Duration::from_secs(60 * 60); +/// How wide the menu under the word is. +const MENU: f32 = 320.0; + +/// What was pressed in the menu. +pub enum Act { + /// Bring the file for this system down. + Fetch, + /// Open what was brought down. + Open(PathBuf), + /// Open the folder it is in. + Folder(PathBuf), + /// Open the page that says what is in the version. + Page(String), + /// Do not mention this version again. + Skip(String), +} + +/// What is known about newer versions, and what is under way. +pub struct Updates { + running: Version, + /// When the next look that nobody asked for is due. + next: Instant, + /// Whether betas counted in the last look. A look made under the + /// other answer is not an answer to this one. + betas: Option, + looking: Option>>>, + /// Whether the look under way was asked for, and so says how it went. + asked: bool, + found: Option, + /// What the last look that was asked for had to say. + answer: Option<(String, bool)>, + fetching: Option>>, + fetched: Option, + /// Why the file did not come down, when it did not. + trouble: Option, +} + +impl Updates { + pub fn new() -> Self { + Self { + running: running(), + next: Instant::now() + FIRST, + betas: None, + looking: None, + asked: false, + found: None, + answer: None, + fetching: None, + fetched: None, + trouble: None, + } + } + + /// The version this is, as the preferences show it. + pub fn running(&self) -> String { + self.running.to_string() + } + + /// Whether a look is under way. + pub fn looking(&self) -> bool { + self.looking.is_some() + } + + /// What the last look somebody asked for found, and whether that was + /// a failure. + pub fn answer(&self) -> Option<(&str, bool)> { + self.answer.as_ref().map(|(text, wrong)| (text.as_str(), *wrong)) + } + + /// Hears what the threads have to say, and looks when it is time to. + /// + /// Every frame. `wanted` is whether the preferences say to look + /// unasked, and `betas` whether a beta counts. + pub fn tick(&mut self, ctx: &egui::Context, wanted: bool, betas: bool) { + self.hear(); + if !wanted || self.looking.is_some() { + return; + } + // The answer on screen was to another question. + if self.betas.is_some_and(|looked| looked != betas) { + self.next = Instant::now(); + } + let now = Instant::now(); + match now >= self.next { + true => self.look(ctx, betas, false), + // egui sleeps when nothing moves. Without this the day would + // be up whenever somebody next touched the mouse. + false => ctx.request_repaint_after(self.next - now), + } + } + + /// Looks now, because somebody pressed the button that says so. + pub fn look_now(&mut self, ctx: &egui::Context, betas: bool) { + if self.looking.is_none() { + self.answer = None; + self.look(ctx, betas, true); + } + } + + fn look(&mut self, ctx: &egui::Context, betas: bool, asked: bool) { + let (say, heard) = mpsc::channel(); + let (running, ctx) = (self.running.clone(), ctx.clone()); + std::thread::spawn(move || { + let _ = say.send(update::look(&running, betas)); + ctx.request_repaint(); + }); + self.looking = Some(heard); + self.asked = asked; + self.betas = Some(betas); + self.next = Instant::now() + EVERY; + } + + /// Starts bringing the file down, unless it is already on its way. + pub fn fetch(&mut self, ctx: &egui::Context) { + let (Some(release), None) = (self.found.clone(), &self.fetching) else { + return; + }; + let Some(folder) = update::downloads() else { + self.trouble = Some("there is no home folder to put it in".to_string()); + return; + }; + let (say, heard) = mpsc::channel(); + let ctx = ctx.clone(); + std::thread::spawn(move || { + let _ = say.send(update::fetch(&release, &folder)); + ctx.request_repaint(); + }); + self.fetching = Some(heard); + self.fetched = None; + self.trouble = None; + } + + fn hear(&mut self) { + if let Some(looking) = &self.looking { + match looking.try_recv() { + Ok(Ok(found)) => { + if self.asked { + self.answer = Some(( + match &found { + Some(release) => format!("{} is out.", release.version), + None => "There is nothing newer than this.".to_string(), + }, + false, + )); + } + // Another version than the one a file was brought down + // for: that file is not this one's. + if found != self.found { + self.fetched = None; + self.trouble = None; + } + self.found = found; + self.looking = None; + } + Ok(Err(err)) => { + if self.asked { + self.answer = Some((format!("Could not look: {err:#}"), true)); + } + self.next = Instant::now() + AGAIN; + self.looking = None; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => self.looking = None, + } + } + if let Some(fetching) = &self.fetching { + match fetching.try_recv() { + Ok(Ok(place)) => { + self.fetched = Some(place); + self.fetching = None; + } + Ok(Err(err)) => { + self.trouble = Some(format!("{err:#}")); + self.fetching = None; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => self.fetching = None, + } + } + } + + /// The word at the end of the tab strip, and the menu under it. + /// + /// Nothing at all when there is nothing newer, or when the newer one + /// is the one somebody said not to mention. + pub fn word(&self, ui: &mut egui::Ui, skipped: &str) -> Option { + let release = self.found.as_ref().filter(|release| release.tag != skipped)?; + let mut act = None; + + let button = ui + .add( + egui::Button::new( + RichText::new(format!("{} is out", release.version)) + .font(theme::medium(11.5)) + .color(theme::text()), + ) + .fill(theme::chosen()) + .corner_radius(egui::CornerRadius::same(theme::RADIUS)), + ) + .on_hover_text(format!("A newer gitrust than this one, which is {}", self.running)); + let id = ui.make_persistent_id("menu-update"); + if button.clicked() { + ui.memory_mut(|memory| memory.toggle_popup(id)); + } + + egui::popup::popup_below_widget( + ui, + id, + &button, + egui::PopupCloseBehavior::CloseOnClickOutside, + |ui| { + ui.set_width(MENU); + // A menu stretches what is in it from edge to edge, which + // suits a list of choices and not a paragraph or a path. + ui.with_layout(egui::Layout::top_down(egui::Align::LEFT), |ui| { + ui.spacing_mut().item_spacing.y = 6.0; + ui.label( + RichText::new(format!("gitrust {} is out", release.version)) + .font(theme::strong(13.0)) + .color(theme::text()), + ); + ui.label( + RichText::new(format!("This one is {}.", self.running)) + .font(theme::body(11.5)) + .color(theme::muted()), + ); + ui.add_space(2.0); + + let file = release.file(); + match (&self.fetched, self.fetching.is_some(), &file) { + (Some(place), _, _) => { + small(ui, "Brought down, and checked against the sums the release publishes:"); + ui.label( + RichText::new(place.display().to_string()) + .font(theme::mono(11.0)) + .color(theme::text()), + ); + if let Some(next) = place.file_name().and_then(|name| what_next(&name.to_string_lossy())) { + small(ui, next); + } + ui.horizontal(|ui| { + if ui.add(egui::Button::new("Open it").fill(theme::chosen())).clicked() { + act = Some(Act::Open(place.clone())); + } + if ui.button("Show the folder").clicked() { + if let Some(folder) = place.parent() { + act = Some(Act::Folder(folder.to_path_buf())); + } + } + }); + } + (None, true, Some(name)) => { + small(ui, &format!("Bringing {name} down\u{2026}")); + ui.spinner(); + } + (None, _, Some(name)) => { + if let Some(trouble) = &self.trouble { + ui.label( + RichText::new(trouble).font(theme::body(11.0)).color(theme::removed()), + ); + } + let label = match self.trouble.is_some() { + true => "Try again", + false => "Download", + }; + if ui.add(egui::Button::new(label).fill(theme::chosen())).clicked() { + act = Some(Act::Fetch); + } + small( + ui, + &format!( + "{name}, into your downloads, checked against the release's \ + SHA256SUMS. Nothing is installed: that is left to you." + ), + ); + } + (None, _, None) => small( + ui, + "The release has no file for this system. Its page has every file, \ + and the source.", + ), + } + + theme::rule(ui); + ui.horizontal(|ui| { + if ui.button("What is in it").clicked() { + act = Some(Act::Page(release.page())); + } + if ui + .button("Not this version") + .on_hover_text("Says no more about this one. The one after it is mentioned.") + .clicked() + { + act = Some(Act::Skip(release.tag.clone())); + } + }); + }); + }, + ); + + // Everything but the download puts the menu away: the download is + // watched from it. + if act.as_ref().is_some_and(|act| !matches!(act, Act::Fetch)) { + ui.memory_mut(|memory| memory.close_popup()); + } + act + } +} + +/// The version this is. +/// +/// A build made for trying things can be told it is an older one, so +/// that the word at the top can be seen without waiting for a release. +/// Not a build anybody is given: there the variable is not read. +fn running() -> Version { + if cfg!(debug_assertions) { + if let Some(pretended) = std::env::var("GITRUST_PRETEND_VERSION") + .ok() + .and_then(|text| Version::parse(&text)) + { + return pretended; + } + } + Version::running() +} + +/// What to do with a file once it is open, in a line. +fn what_next(name: &str) -> Option<&'static str> { + if name.ends_with(".deb") { + Some("Opening it hands it to the system's installer.") + } else if name.ends_with(".tar.gz") { + Some("Unpack it, and run packaging/install.sh --no-build from inside.") + } else if name.contains("macos") { + Some("Open it and drag Gitrust.app to Applications.") + } else if name.contains("windows") { + Some("Unpack it; the .exe runs from wherever you put it.") + } else { + None + } +} + +fn small(ui: &mut egui::Ui, text: &str) { + ui.label(RichText::new(text).font(theme::body(11.0)).color(theme::faint())); +} + +/// Hands a file, a folder or an address to whatever the desktop opens +/// such things with. +/// +/// The three systems have three programs for it. Only the first has been +/// run from here. +pub fn open_outside(what: impl AsRef) -> std::io::Result<()> { + let mut command = if cfg!(target_os = "macos") { + std::process::Command::new("open") + } else if cfg!(windows) { + // Not `cmd /C start`, which reads an address with an ampersand in + // it as two commands. + let mut command = std::process::Command::new("rundll32"); + command.arg("url.dll,FileProtocolHandler"); + command + } else { + std::process::Command::new("xdg-open") + }; + command.arg(what).spawn().map(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_kind_of_file_says_what_is_done_with_it() { + assert!(what_next("gitrust_0.2.0_amd64.deb").unwrap().contains("installer")); + assert!(what_next("gitrust-0.2.0-linux-x86_64.tar.gz").unwrap().contains("install.sh")); + assert!(what_next("gitrust-0.2.0-macos-universal.zip").unwrap().contains("Applications")); + assert!(what_next("gitrust-0.2.0-windows-x86_64.zip").unwrap().contains(".exe")); + assert_eq!(what_next("SHA256SUMS"), None); + } + + #[test] + fn nothing_is_looked_for_before_its_time_or_when_not_wanted() { + let ctx = egui::Context::default(); + let mut updates = Updates::new(); + // Just opened: the first look is a few seconds off. + updates.tick(&ctx, true, false); + assert!(!updates.looking()); + // Its time has come, and the preferences say not to. + updates.next = Instant::now(); + updates.tick(&ctx, false, false); + assert!(!updates.looking()); + assert!(updates.answer().is_none()); + } +}