Skip to content

A visual git client, simple to use yet powerful. Light, fast and debloated.

Rust

feat: gitcraft 0.2.0 - interactive rebase, history and blame, HTTPS sign-in, installers

Ivánb3f92b16757b
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index b5f322d..ff4c52e 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -49,6 +49,16 @@ jobs:
Copy-Item target/release/gitcraft.exe, README.md, ATTRIBUTION.md, LICENSE-MIT, LICENSE-APACHE $dir
Compress-Archive -Path $dir -DestinationPath "$dir.zip"
+ - name: Installer (Windows)
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: |
+ choco install innosetup --no-progress -y
+ $version = (Select-String -Path Cargo.toml -Pattern '^version = "(.+)"').Matches[0].Groups[1].Value
+ & "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" /Qp "/DAppVersion=$version" "/DOutputName=gitcraft-${{ github.ref_name }}-${{ matrix.name }}-setup" packaging\windows\gitcraft.iss
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ Move-Item dist\*.exe .
+
- name: Package (Linux)
if: runner.os == 'Linux'
run: |
@@ -56,15 +66,29 @@ jobs:
mkdir "$dir"
cp target/release/gitcraft README.md ATTRIBUTION.md LICENSE-MIT LICENSE-APACHE \
packaging/gitcraft.desktop "$dir/"
+ cp assets/app-icon/gitcraft-256.png "$dir/gitcraft.png"
strip "$dir/gitcraft"
tar czf "$dir.tar.gz" "$dir"
+ - name: AppImage (Linux)
+ if: runner.os == 'Linux'
+ env:
+ # The runner has no FUSE: appimagetool unpacks itself instead.
+ APPIMAGE_EXTRACT_AND_RUN: "1"
+ run: |
+ sudo curl -fsSL -o /usr/local/bin/appimagetool \
+ https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage
+ sudo chmod +x /usr/local/bin/appimagetool
+ sh packaging/linux/build-appimage.sh "gitcraft-${{ github.ref_name }}-${{ matrix.name }}.AppImage"
+
- uses: actions/upload-artifact@v4
with:
name: gitcraft-${{ matrix.name }}
path: |
gitcraft-*.zip
gitcraft-*.tar.gz
+ gitcraft-*-setup.exe
+ gitcraft-*.AppImage
release:
needs: build
diff --git a/.gitignore b/.gitignore
index ea8c4bf..4f96631 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
/target
+/dist
diff --git a/Cargo.lock b/Cargo.lock
index 5d4472d..f65e9c3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1447,7 +1447,7 @@ dependencies = [
[[package]]
name = "gitcraft"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"eframe",
"egui",
@@ -1465,6 +1465,7 @@ dependencies = [
"syntect",
"ureq",
"vt100",
+ "winresource",
]
[[package]]
@@ -3892,10 +3893,12 @@ version = "1.1.8+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"
dependencies = [
+ "indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
+ "toml_writer",
"winnow",
]
@@ -3929,6 +3932,12 @@ dependencies = [
"winnow",
]
+[[package]]
+name = "toml_writer"
+version = "1.1.3+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
+
[[package]]
name = "tracing"
version = "0.1.44"
@@ -4892,6 +4901,16 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "winresource"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
+dependencies = [
+ "toml",
+ "version_check",
+]
+
[[package]]
name = "wit-bindgen"
version = "0.57.1"
diff --git a/Cargo.toml b/Cargo.toml
index 8baf494..1f4839b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "gitcraft"
-version = "0.1.0"
+version = "0.2.0"
edition = "2024"
rust-version = "1.95"
license = "MIT OR Apache-2.0"
@@ -39,5 +39,9 @@ opt-level = 2
opt-level = 3
lto = "thin"
+[build-dependencies]
+# Icon and version info for gitcraft.exe; build.rs only uses it when targeting Windows.
+winresource = "0.1"
+
[dev-dependencies]
egui_kittest = { version = "0.36", features = ["wgpu", "snapshot", "eframe"] }
diff --git a/README.md b/README.md
index 94dde01..ce3c614 100644
--- a/README.md
+++ b/README.md
@@ -23,15 +23,24 @@ so your config, credentials and hooks apply as usual.
it at that commit (`x` and `origin/x` make one pill), a pull-request icon when one is open,
`+N` when more refs share the commit, the author's avatar and how long ago it was ("2 hours
ago"). Author, date and hash columns are optional (Settings).
+- The checked-out branch's pill is solid, the others slightly see-through. Double-click a pill to
+ check that branch (or tag) out; hover `+N` to list every pill of the commit and double-click
+ the one you want.
- An *Uncommitted changes* row on top while the working tree is dirty.
- Search (Ctrl+F) through messages, authors and hashes of all history; Enter / Shift+Enter jump
between results, loading older history when needed.
-- Right-click a commit: create a branch or a tag, check it out, cherry-pick, revert, reset the
- current branch to it (soft / mixed / hard, confirmed), the menu of each branch on it.
+- Right-click a commit: create a branch or a tag, check it out, interactive rebase onto it,
+ cherry-pick, revert, reset the current branch to it (soft / mixed / hard, confirmed), the menu
+ of each branch on it, copy the hash, message or branch name. Right-click a branch's pill to get
+ check out, fast-forward, merge, rebase and interactive rebase for that branch on top.
+- Interactive rebase: the commits to rewrite, newest on top; pick, reword (edit the message in
+ place), squash, fix up or drop each one, move them up and down, then *Start rebase*. Ctrl+Z
+ undoes it.
**Branches, remotes, worktrees, stashes, tags** (left)
-- Local branches with ahead/behind; right-click: check out (or in a new worktree), merge into /
- rebase onto the current branch, push, create a pull request, rename, delete…
+- Local branches with ahead/behind; right-click: check out (or in a new worktree), fast-forward,
+ merge into / (interactively) rebase onto the current branch, push, create a pull request,
+ rename, delete…
- Remotes: add, edit (name and URL), fetch one, remove; their branches below each.
- Worktrees: add (existing or new branch), open in a tab, open a terminal there, lock, remove,
prune.
@@ -43,8 +52,9 @@ so your config, credentials and hooks apply as usual.
**Changes and commits** (right)
- Conflicted / unstaged / staged lists with stage, unstage, discard and mark-resolved buttons,
- *Stage all* / *Unstage all*; right-click a file to open it, open it in your editor or show it in
- its folder.
+ *Stage all* / *Unstage all*; right-click a file to open it, open it in your editor, show it in
+ its folder, see its history or blame, or ignore it (the file, its extension or its folder go
+ into `.gitignore`; a tracked file stops being tracked).
- Commit box (Ctrl+Enter; with nothing staged it stages everything), *Amend last commit*
(warns when the commit is already pushed), the identity you commit as, and saved identities to
switch a repository to.
@@ -58,18 +68,28 @@ so your config, credentials and hooks apply as usual.
*Both* buttons, and the result below (editable). *Use mine* / *Use theirs* for a whole file.
- A merge, rebase, cherry-pick or revert stopped on conflicts shows a banner with *Abort*; the
commit box finishes it (*Continue rebase* during a rebase).
+- File history (every commit that changed the file, following renames; click one for its diff)
+ and blame (who last changed each line, newer changes marked brighter; click to go to the
+ commit).
**Toolbar, terminal, app**
- Undo, redo, Fetch, Pull and Push (with incoming / outgoing counts), new branch, stash, terminal,
search, open the folder (Explorer / Finder, your editor), refresh (F5).
- Background fetch every few minutes (Settings; 0 turns it off).
+- HTTPS sign-in: when a remote wants a username and password (or token) and no credential helper
+ provides them, a dialog asks and the operation runs again. They stay in memory for the tab;
+ git's own credential helper, if there is one, stores them. Cloning asks the same way.
- Terminal panel with tabs: PowerShell, cmd, Git Bash, WSL… on Windows, your shells elsewhere, in a
real pseudo-terminal (ConPTY on Windows) with colours, scrollback, mouse selection and copy
(Ctrl+C with a selection, Ctrl+Shift+C or right-click).
- Command palette (Ctrl+P): every action and branch, fuzzy matched.
-- Settings: zoom, branch column width, graph columns, avatars from Gravatar / GitHub (sends a hash
- of each author's email; can be turned off), notifications, background fetch, editor command,
- default shell and terminal font size, saved identities.
+- Avatars: on a GitHub repository, the authors' GitHub accounts (through `gh` when installed, else
+ GitHub's API); on GitLab, the host's avatar API; elsewhere Gravatar (a hash of the email).
+ Cached on disk; can be turned off.
+- Settings: zoom, branch column width, graph columns, avatars, notifications, update check,
+ background fetch, editor command, default shell and terminal font size, saved identities.
+- Checks GitHub once a day for a newer release and shows a pill to download it (can be turned
+ off).
- Toasts, and a desktop notification when a long operation ends while the window is in the
background.
- Themes: Dark, Medium Gray and Light, from PhotoCraft's Pro palettes.
@@ -77,9 +97,17 @@ so your config, credentials and hooks apply as usual.
## Download
Ready-made builds for Windows and Linux (x86-64) are on the
-[releases page](https://github.com/Vancete/gitcraft/releases): unzip and run `gitcraft.exe`
-(Windows) or `gitcraft` (Linux). Git must be installed. A release is built by
-`.github/workflows/release.yml` whenever a `v*` tag is pushed.
+[releases page](https://github.com/Vancete/gitcraft/releases). Git must be installed.
+
+- **Windows:** `gitcraft-…-setup.exe` installs it for your user (no administrator rights), with a
+ Start menu entry, an optional desktop icon, *Open in gitcraft* on folders and an uninstaller.
+ The `.zip` is the same program without installing.
+- **Linux:** `gitcraft-….AppImage` runs on most distributions: make it executable
+ (`chmod +x`) and run it. The `.tar.gz` holds the bare binary and a `.desktop` file.
+
+A release is built by `.github/workflows/release.yml` whenever a `v*` tag is pushed
+(`packaging/windows/gitcraft.iss` for the installer, `packaging/linux/build-appimage.sh` for the
+AppImage).
## Build and run
@@ -112,7 +140,8 @@ was made this way, on a demo repository.
| `src/git.rs` | `git` CLI wrapper and output parsing (refs, log, status, stashes, remotes, search) |
| `src/graph.rs` | lane layout for the commit graph |
| `src/forge.rs` | pull / merge requests through `gh` and `glab` |
-| `src/avatars.rs` | avatars from Gravatar / GitHub, cached on disk |
+| `src/avatars.rs` | avatars from GitHub, GitLab or Gravatar, cached on disk |
+| `src/update.rs` | new-release check |
| `src/settings.rs` | user settings and their form |
| `src/theme.rs` | colour tokens, fonts, egui style (PhotoCraft's Pro themes) |
| `src/icons.rs` | embedded Lucide SVG icons, tinted |
@@ -124,6 +153,8 @@ was made this way, on a demo repository.
| `src/repo/diff.rs` | diff loading, pairing and the diff view (unified, split, images) |
| `src/repo/highlight.rs` | syntax colours (syntect) |
| `src/repo/conflict.rs` | three-pane conflict editor |
+| `src/repo/rebase.rs` | interactive rebase editor and its todo list |
+| `src/repo/file_view.rs` | a file's history and blame |
| `src/repo/dialogs.rs` | branch, tag, stash, remote, worktree, pull request and confirm dialogs |
| `src/repo/widgets.rs` | shared painted widgets (panel headers, file rows, avatars, tabs) |
| `src/app.rs` | window shell: tabs, start page, cloning, palette, settings, toasts |
diff --git a/assets/app-icon/gitcraft-256.png b/assets/app-icon/gitcraft-256.png
new file mode 100644
index 0000000..f25c34e
Binary files /dev/null and b/assets/app-icon/gitcraft-256.png differ
diff --git a/assets/app-icon/gitcraft.ico b/assets/app-icon/gitcraft.ico
new file mode 100644
index 0000000..2db53f2
Binary files /dev/null and b/assets/app-icon/gitcraft.ico differ
diff --git a/assets/app-icon/gitcraft.svg b/assets/app-icon/gitcraft.svg
new file mode 100644
index 0000000..e531ab9
--- /dev/null
+++ b/assets/app-icon/gitcraft.svg
@@ -0,0 +1,19 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
+ <defs>
+ <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stop-color="#4a9bf7"/>
+ <stop offset="1" stop-color="#2f7bf5"/>
+ </linearGradient>
+ </defs>
+ <rect width="512" height="512" rx="112" fill="url(#bg)"/>
+ <g fill="none" stroke="#ffffff" stroke-width="40" stroke-linecap="round">
+ <path d="M182 150V362"/>
+ <path d="M330 168C330 268 182 248 182 330"/>
+ </g>
+ <g fill="#ffffff">
+ <circle cx="182" cy="130" r="50"/>
+ <circle cx="182" cy="382" r="50"/>
+ <circle cx="330" cy="168" r="50"/>
+ </g>
+ <circle cx="182" cy="130" r="20" fill="#2f7bf5"/>
+</svg>
diff --git a/assets/icons/history.svg b/assets/icons/history.svg
new file mode 100644
index 0000000..67152e4
--- /dev/null
+++ b/assets/icons/history.svg
@@ -0,0 +1,15 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
+ <path d="M3 3v5h5" />
+ <path d="M12 7v5l4 2" />
+</svg>
diff --git a/build.rs b/build.rs
new file mode 100644
index 0000000..dbbdcd7
--- /dev/null
+++ b/build.rs
@@ -0,0 +1,20 @@
+//! Windows only: embed the app icon and version info into `gitcraft.exe`, so Explorer and
+//! shortcuts show it. Elsewhere this does nothing; a missing resource compiler is only a warning.
+
+fn main() {
+ println!("cargo:rerun-if-changed=build.rs");
+ println!("cargo:rerun-if-changed=assets/app-icon/gitcraft.ico");
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
+ return;
+ }
+ let mut res = winresource::WindowsResource::new();
+ res.set_icon("assets/app-icon/gitcraft.ico")
+ .set("ProductName", "gitcraft")
+ .set("FileDescription", "gitcraft")
+ .set("LegalCopyright", "MIT OR Apache-2.0")
+ .set("OriginalFilename", "gitcraft.exe")
+ .set("InternalName", "gitcraft");
+ if let Err(e) = res.compile() {
+ println!("cargo:warning=gitcraft.exe built without its icon: {e}");
+ }
+}
diff --git a/examples/ui_shot.rs b/examples/ui_shot.rs
index 3d23a3b..b6d6d21 100644
--- a/examples/ui_shot.rs
+++ b/examples/ui_shot.rs
@@ -24,6 +24,8 @@ fn main() {
let mut harness = Harness::builder()
.with_size([1400.0, 860.0])
+ // A frame's worth of time per step, so two clicks make a double-click.
+ .with_step_dt(1.0 / 60.0)
.build_eframe(|cc| gitcraft::app::App::new(cc, Some(repo.into())));
settle(&mut harness, 1500);
@@ -54,6 +56,7 @@ fn main() {
let pos = point(arg);
harness.event(Event::PointerMoved(pos));
harness.step();
+ // Each press and release in a frame of its own, as a real double-click arrives.
for _ in 0..2 {
for pressed in [true, false] {
harness.event(Event::PointerButton {
@@ -62,8 +65,8 @@ fn main() {
pressed,
modifiers: Modifiers::NONE,
});
+ harness.step();
}
- harness.step();
}
settle(&mut harness, 600);
}
diff --git a/packaging/gitcraft.desktop b/packaging/gitcraft.desktop
index c734eef..03f6fd6 100644
--- a/packaging/gitcraft.desktop
+++ b/packaging/gitcraft.desktop
@@ -5,3 +5,4 @@ Comment=A small visual git client
Exec=gitcraft %f
Terminal=false
Categories=Development;RevisionControl;
+Icon=gitcraft
diff --git a/packaging/linux/build-appimage.sh b/packaging/linux/build-appimage.sh
new file mode 100755
index 0000000..6c68c48
--- /dev/null
+++ b/packaging/linux/build-appimage.sh
@@ -0,0 +1,27 @@
+#!/bin/sh
+# Packs target/release/gitcraft into an AppImage: one file that runs on most Linux distributions.
+# Usage: packaging/linux/build-appimage.sh <output.AppImage>
+# Needs appimagetool on PATH (the release workflow downloads it).
+set -eu
+
+out="$1"
+app="$(mktemp -d)/gitcraft.AppDir"
+mkdir -p "$app/usr/bin" "$app/usr/share/applications" "$app/usr/share/icons/hicolor/256x256/apps"
+
+cp target/release/gitcraft "$app/usr/bin/gitcraft"
+strip "$app/usr/bin/gitcraft"
+cp packaging/gitcraft.desktop "$app/usr/share/applications/gitcraft.desktop"
+cp assets/app-icon/gitcraft-256.png "$app/usr/share/icons/hicolor/256x256/apps/gitcraft.png"
+
+# What appimagetool looks for at the top of the AppDir.
+cp packaging/gitcraft.desktop "$app/gitcraft.desktop"
+cp assets/app-icon/gitcraft-256.png "$app/gitcraft.png"
+ln -s gitcraft.png "$app/.DirIcon"
+cat > "$app/AppRun" <<'EOF'
+#!/bin/sh
+here="$(dirname "$(readlink -f "$0")")"
+exec "$here/usr/bin/gitcraft" "$@"
+EOF
+chmod +x "$app/AppRun"
+
+ARCH=x86_64 appimagetool "$app" "$out"
diff --git a/packaging/windows/gitcraft.iss b/packaging/windows/gitcraft.iss
new file mode 100644
index 0000000..b52a584
--- /dev/null
+++ b/packaging/windows/gitcraft.iss
@@ -0,0 +1,64 @@
+; Inno Setup script for gitcraft's Windows installer. Built by the release workflow:
+; iscc /DAppVersion=0.2.0 /DOutputName=gitcraft-v0.2.0-windows-x86_64-setup packaging\windows\gitcraft.iss
+; Installs per user (no administrator rights needed) unless the user picks "all users".
+
+#ifndef AppVersion
+ #define AppVersion "0.0.0"
+#endif
+#ifndef OutputName
+ #define OutputName "gitcraft-setup"
+#endif
+#define Root "..\.."
+
+[Setup]
+AppId={{86F6EE51-215B-489E-BB29-402DC3170FC5}
+AppName=gitcraft
+AppVersion={#AppVersion}
+AppVerName=gitcraft {#AppVersion}
+AppPublisher=Iván
+AppPublisherURL=https://github.com/Vancete/gitcraft
+AppSupportURL=https://github.com/Vancete/gitcraft/issues
+AppUpdatesURL=https://github.com/Vancete/gitcraft/releases
+DefaultDirName={autopf}\gitcraft
+DisableProgramGroupPage=yes
+PrivilegesRequired=lowest
+PrivilegesRequiredOverridesAllowed=dialog
+ArchitecturesAllowed=x64compatible
+ArchitecturesInstallIn64BitMode=x64compatible
+OutputDir={#Root}\dist
+OutputBaseFilename={#OutputName}
+SetupIconFile={#Root}\assets\app-icon\gitcraft.ico
+UninstallDisplayIcon={app}\gitcraft.exe
+UninstallDisplayName=gitcraft
+LicenseFile={#Root}\LICENSE-MIT
+Compression=lzma2/max
+SolidCompression=yes
+WizardStyle=modern
+ChangesAssociations=no
+
+[Tasks]
+Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
+Name: "foldermenu"; Description: "Add ""Open in gitcraft"" to the right-click menu of folders"; GroupDescription: "Explorer:"
+
+[Files]
+Source: "{#Root}\target\release\gitcraft.exe"; DestDir: "{app}"; Flags: ignoreversion
+Source: "{#Root}\README.md"; DestDir: "{app}"; Flags: ignoreversion
+Source: "{#Root}\ATTRIBUTION.md"; DestDir: "{app}"; Flags: ignoreversion
+Source: "{#Root}\LICENSE-MIT"; DestDir: "{app}"; Flags: ignoreversion
+Source: "{#Root}\LICENSE-APACHE"; DestDir: "{app}"; Flags: ignoreversion
+
+[Icons]
+Name: "{autoprograms}\gitcraft"; Filename: "{app}\gitcraft.exe"
+Name: "{autodesktop}\gitcraft"; Filename: "{app}\gitcraft.exe"; Tasks: desktopicon
+
+[Registry]
+; "Open in gitcraft" on a folder and on a folder's background (HKCU or HKLM, per install mode).
+Root: HKA; Subkey: "Software\Classes\Directory\shell\gitcraft"; ValueType: string; ValueName: ""; ValueData: "Open in gitcraft"; Tasks: foldermenu; Flags: uninsdeletekey
+Root: HKA; Subkey: "Software\Classes\Directory\shell\gitcraft"; ValueType: string; ValueName: "Icon"; ValueData: """{app}\gitcraft.exe"""; Tasks: foldermenu
+Root: HKA; Subkey: "Software\Classes\Directory\shell\gitcraft\command"; ValueType: string; ValueName: ""; ValueData: """{app}\gitcraft.exe"" ""%1"""; Tasks: foldermenu
+Root: HKA; Subkey: "Software\Classes\Directory\Background\shell\gitcraft"; ValueType: string; ValueName: ""; ValueData: "Open in gitcraft"; Tasks: foldermenu; Flags: uninsdeletekey
+Root: HKA; Subkey: "Software\Classes\Directory\Background\shell\gitcraft"; ValueType: string; ValueName: "Icon"; ValueData: """{app}\gitcraft.exe"""; Tasks: foldermenu
+Root: HKA; Subkey: "Software\Classes\Directory\Background\shell\gitcraft\command"; ValueType: string; ValueName: ""; ValueData: """{app}\gitcraft.exe"" ""%V"""; Tasks: foldermenu
+
+[Run]
+Filename: "{app}\gitcraft.exe"; Description: "{cm:LaunchProgram,gitcraft}"; Flags: nowait postinstall skipifsilent
diff --git a/src/app.rs b/src/app.rs
index eb37923..8928acf 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -1,6 +1,7 @@
//! Window shell: git check, browser-like tabs, the start page and cloning.
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, channel};
use egui::{Align2, CornerRadius, Key, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
@@ -11,10 +12,16 @@ use crate::icons;
use crate::repo::RepoTab;
use crate::settings::Settings;
use crate::theme::{self, ThemeKind, Tokens};
+use crate::update;
const MAX_RECENT: usize = 12;
const TAB_H: f32 = 34.0;
+/// Set by `main` when the window was closed maximized: it opens restored and is maximized once
+/// it shows its first frame. Created maximized, winit shows the hidden window for an instant
+/// (`ShowWindow(SW_MAXIMIZE)`) before anything is painted, a white flash on Windows.
+pub static MAXIMIZE_WHEN_SHOWN: AtomicBool = AtomicBool::new(false);
+
/// What survives a restart.
#[derive(Default, Serialize, Deserialize)]
#[serde(default)]
@@ -25,6 +32,10 @@ struct Saved {
theme: ThemeKind,
clone_parent: Option<PathBuf>,
settings: Settings,
+ /// Unix time of the last update check.
+ update_checked: i64,
+ /// A release the user chose to skip.
+ skipped_version: String,
}
enum Tab {
@@ -41,6 +52,10 @@ struct CloneForm {
name_edited: bool,
error: Option<String>,
focus: bool,
+ /// The remote asked for a username and password / token.
+ auth: bool,
+ username: String,
+ password: String,
}
pub struct App {
@@ -55,6 +70,13 @@ pub struct App {
clone_form: Option<CloneForm>,
/// A clone running in the background: (destination, result).
cloning: Option<(PathBuf, Receiver<Result<(), String>>)>,
+ /// The form of the running clone, back on screen if it needs credentials.
+ cloning_form: Option<CloneForm>,
+ /// A newer release than this build.
+ update: Option<update::Release>,
+ update_rx: Option<Receiver<Result<update::Release, String>>>,
+ update_checked: i64,
+ skipped_version: String,
settings: Settings,
settings_open: bool,
palette: Option<Palette>,
@@ -118,7 +140,21 @@ impl App {
was_focused: true,
clone_form: None,
cloning: None,
+ cloning_form: None,
+ update: None,
+ update_rx: None,
+ update_checked: saved.update_checked,
+ skipped_version: saved.skipped_version,
};
+ if saved.settings.check_updates && git::now() - saved.update_checked > update::INTERVAL {
+ let (tx, rx) = channel();
+ let ctx2 = ctx.clone();
+ std::thread::spawn(move || {
+ let _ = tx.send(update::latest());
+ ctx2.request_repaint();
+ });
+ app.update_rx = Some(rx);
+ }
if app.git_version.is_ok() {
for path in saved.open {
if path.is_dir() {
@@ -224,6 +260,9 @@ impl App {
name_edited: false,
error: None,
focus: true,
+ auth: false,
+ username: String::new(),
+ password: String::new(),
});
}
@@ -359,6 +398,34 @@ impl App {
if icons::small_button(ui, "settings", "Settings").clicked() {
self.settings_open = true;
}
+ if let Some(release) = self.update.clone() {
+ let pill = ui.add(
+ egui::Button::new(
+ RichText::new(format!("v{} available", release.version))
+ .color(t.accent_text)
+ .font(theme::medium(11.5)),
+ )
+ .fill(t.accent)
+ .corner_radius(10.0),
+ );
+ egui::Popup::menu(&pill).show(|ui| {
+ ui.label(
+ RichText::new(format!(
+ "gitcraft {} is out (you have {}).",
+ release.version,
+ update::CURRENT
+ ))
+ .color(t.text_dim),
+ );
+ if ui.button("Open the release page").clicked() {
+ let _ = open::that_detached(&release.url);
+ }
+ if ui.button("Skip this version").clicked() {
+ self.skipped_version = release.version.clone();
+ self.update = None;
+ }
+ });
+ }
if icons::small_button(ui, "command", "Command palette (Ctrl+P)").clicked() {
self.open_palette();
}
@@ -548,6 +615,28 @@ impl App {
.color(t.text_faint)
.small(),
);
+ if form.auth {
+ ui.add_space(6.0);
+ ui.label(
+ RichText::new("The remote wants to know who you are. Most hosts take a personal access token as the password.")
+ .color(t.text_dim)
+ .small(),
+ );
+ ui.add_space(4.0);
+ ui.add(
+ egui::TextEdit::singleline(&mut form.username)
+ .hint_text("Username")
+ .desired_width(f32::INFINITY)
+ .margin(egui::Margin::symmetric(8, 6)),
+ );
+ ui.add(
+ egui::TextEdit::singleline(&mut form.password)
+ .password(true)
+ .hint_text("Password or token")
+ .desired_width(f32::INFINITY)
+ .margin(egui::Margin::symmetric(8, 6)),
+ );
+ }
if let Some(err) = &form.error {
ui.colored_label(t.danger, err);
}
@@ -585,22 +674,41 @@ impl App {
return;
}
let url = form.url.trim().to_owned();
+ let creds = (form.auth && !form.username.trim().is_empty()).then(|| git::Credentials {
+ username: form.username.trim().to_owned(),
+ password: form.password.clone(),
+ });
self.clone_parent = Some(PathBuf::from(form.parent.trim()));
let (tx, rx) = channel();
let ctx2 = ctx.clone();
let dest2 = dest.clone();
std::thread::spawn(move || {
- let _ = tx.send(git::clone(&url, &dest2));
+ let _ = tx.send(git::clone(&url, &dest2, creds.as_ref()));
ctx2.request_repaint();
});
self.cloning = Some((dest, rx));
- self.clone_form = None;
+ self.cloning_form = self.clone_form.take();
self.error = None;
} else if cancel {
self.clone_form = None;
}
}
+ fn poll_update(&mut self) {
+ let Some(rx) = &self.update_rx else { return };
+ let Ok(result) = rx.try_recv() else { return };
+ self.update_rx = None;
+ // A failed check (offline…) is tried again next start.
+ if let Ok(release) = result {
+ self.update_checked = git::now();
+ if update::newer(&release.version, update::CURRENT)
+ && release.version != self.skipped_version
+ {
+ self.update = Some(release);
+ }
+ }
+ }
+
fn poll_clone(&mut self, ctx: &egui::Context) {
let Some((dest, rx)) = &self.cloning else {
return;
@@ -612,9 +720,33 @@ impl App {
Ok(()) => {
// Show it in a start page tab if one is active, otherwise in a new tab.
self.open_repo(&dest, ctx);
+ // The credentials that cloned it also fetch and push in its tab.
+ if let Some(form) = self.cloning_form.take().filter(|f| f.auth)
+ && let Some(Tab::Repo(repo)) = self.tabs.get_mut(self.active)
+ {
+ repo.set_credentials(git::Credentials {
+ username: form.username.trim().to_owned(),
+ password: form.password,
+ });
+ }
}
+ // Back to the form, asking for credentials.
+ Err(e) if git::is_auth_error(&e) => match self.cloning_form.take() {
+ Some(mut form) => {
+ form.error = Some(if form.auth {
+ "Those credentials were refused.".to_owned()
+ } else {
+ "This repository needs you to sign in.".to_owned()
+ });
+ form.auth = true;
+ form.password.clear();
+ self.clone_form = Some(form);
+ }
+ None => self.error = Some(format!("Clone failed: {e}")),
+ },
Err(e) => self.error = Some(format!("Clone failed: {e}")),
}
+ self.cloning_form = None;
}
fn git_missing(&mut self, ui: &mut Ui, err: &str) {
@@ -643,6 +775,16 @@ impl eframe::App for App {
let ctx = ui.ctx().clone();
let t = Tokens::get(&ctx);
+ // eframe shows the window after the first frame; maximize it on the next one.
+ if MAXIMIZE_WHEN_SHOWN.load(Ordering::Relaxed) {
+ if ctx.cumulative_frame_nr() >= 1 {
+ MAXIMIZE_WHEN_SHOWN.store(false, Ordering::Relaxed);
+ ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(true));
+ } else {
+ ctx.request_repaint();
+ }
+ }
+
if let Err(err) = self.git_version.clone() {
egui::CentralPanel::default()
.frame(egui::Frame::new().fill(t.dock))
@@ -650,6 +792,7 @@ impl eframe::App for App {
return;
}
self.poll_clone(&ctx);
+ self.poll_update();
// Shortcuts.
// A focused text field or the terminal keeps these keys for itself.
@@ -773,11 +916,19 @@ impl eframe::App for App {
theme: self.theme,
clone_parent: self.clone_parent.clone(),
settings: self.settings.clone(),
+ update_checked: self.update_checked,
+ skipped_version: self.skipped_version.clone(),
};
eframe::set_value(storage, eframe::APP_KEY, &saved);
}
}
+/// The window and taskbar icon (the `.exe` gets the same picture from `build.rs`).
+pub fn window_icon() -> egui::IconData {
+ eframe::icon_data::from_png_bytes(include_bytes!("../assets/app-icon/gitcraft-256.png"))
+ .unwrap_or_default()
+}
+
/// A large clickable card on the start page.
fn action_card(ui: &mut Ui, width: f32, icon: &str, title: &str, subtitle: &str) -> egui::Response {
let t = Tokens::get(ui.ctx());
@@ -1195,7 +1346,17 @@ fn notify(text: &str) {
#[cfg(test)]
mod tests {
- use super::fuzzy;
+ use super::{fuzzy, window_icon};
+
+ #[test]
+ fn window_icon_decodes() {
+ let icon = window_icon();
+ assert_eq!((icon.width, icon.height), (256, 256));
+ assert!(
+ icon.rgba.chunks(4).any(|p| p[3] > 0),
+ "the icon isn't blank"
+ );
+ }
#[test]
fn fuzzy_matching() {
diff --git a/src/avatars.rs b/src/avatars.rs
index 4fe87fb..1c87180 100644
--- a/src/avatars.rs
+++ b/src/avatars.rs
@@ -1,5 +1,7 @@
-//! Author avatars from Gravatar (or GitHub for its noreply addresses), fetched in the
-//! background, cached on disk, painted round. Initials stand in until (or unless) one loads.
+//! Author avatars, fetched in the background, cached on disk, painted round. A repository on
+//! GitHub or GitLab tells us (through [`hint`]) where its authors' account pictures are; other
+//! addresses go to Gravatar (or GitHub for its noreply ones). Initials stand in until (or unless)
+//! one loads.
use std::collections::HashMap;
use std::path::PathBuf;
@@ -24,12 +26,41 @@ struct Avatars {
queue: Mutex<Sender<String>>,
}
+/// Where an address's picture is, when a forge knows better than Gravatar.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Hint {
+ /// The account's avatar URL (GitHub).
+ Url(String),
+ /// Ask this GitLab host's avatar API.
+ GitLab(String),
+}
+
+static AVATARS: OnceLock<Avatars> = OnceLock::new();
+
+fn hints() -> &'static Mutex<HashMap<String, Hint>> {
+ static HINTS: OnceLock<Mutex<HashMap<String, Hint>>> = OnceLock::new();
+ HINTS.get_or_init(Default::default)
+}
+
+/// Records where `email`'s picture is; one already shown from elsewhere is fetched again.
+pub fn hint(email: &str, hint: Hint) {
+ let k = email.trim().to_lowercase();
+ let mut h = lock(hints());
+ if h.get(&k) == Some(&hint) {
+ return;
+ }
+ h.insert(k.clone(), hint);
+ drop(h);
+ if let Some(av) = AVATARS.get() {
+ lock(&av.map).remove(&k);
+ }
+}
+
fn cache_dir() -> Option<PathBuf> {
eframe::storage_dir("gitcraft").map(|d| d.join("avatars"))
}
fn avatars(ctx: &egui::Context) -> &'static Avatars {
- static AVATARS: OnceLock<Avatars> = OnceLock::new();
AVATARS.get_or_init(|| {
let (tx, rx) = channel::<String>();
let ctx = ctx.clone();
@@ -39,7 +70,8 @@ fn avatars(ctx: &egui::Context) -> &'static Avatars {
.user_agent("gitcraft")
.build();
while let Ok(email) = rx.recv() {
- let state = fetch(&agent, &email);
+ let hint = lock(hints()).get(&email).cloned();
+ let state = fetch(&agent, &email, hint.as_ref());
if let Some(map) = AVATARS.get() {
lock(&map.map).insert(email, state);
}
@@ -76,9 +108,55 @@ fn url(email: &str) -> String {
format!("https://www.gravatar.com/avatar/{}?s=80&d=404", key(&email))
}
-fn fetch(agent: &ureq::Agent, email: &str) -> State {
+/// Cache file name: Gravatar's hash, plus where the picture came from when a forge said.
+fn cache_key(email: &str, hint: Option<&Hint>) -> String {
+ match hint {
+ None => key(email),
+ Some(Hint::Url(_)) => format!("{}-gh", key(email)),
+ Some(Hint::GitLab(host)) => format!("{}-gl-{}", key(email), key(host)),
+ }
+}
+
+/// The picture's URL: a forge's, else [`url`].
+fn source(agent: &ureq::Agent, email: &str, hint: Option<&Hint>) -> String {
+ match hint {
+ Some(Hint::Url(u)) => format!("{u}{}s=80", if u.contains('?') { '&' } else { '?' }),
+ Some(Hint::GitLab(host)) => {
+ let api = format!(
+ "https://{host}/api/v4/avatar?email={}&size=80",
+ query_escape(email)
+ );
+ let found = agent
+ .get(&api)
+ .call()
+ .ok()
+ .and_then(|r| r.into_string().ok())
+ .and_then(|body| serde_json::from_str::<serde_json::Value>(&body).ok())
+ .and_then(|v| v.get("avatar_url")?.as_str().map(str::to_owned));
+ match found {
+ // GitLab falls back to a generated Gravatar; initials read better.
+ Some(u) if !u.contains("gravatar.com") => u,
+ _ => url(email),
+ }
+ }
+ None => url(email),
+ }
+}
+
+fn query_escape(s: &str) -> String {
+ s.bytes()
+ .map(|b| match b {
+ b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'-' | b'_' | b'@' => {
+ (b as char).to_string()
+ }
+ _ => format!("%{b:02X}"),
+ })
+ .collect()
+}
+
+fn fetch(agent: &ureq::Agent, email: &str, hint: Option<&Hint>) -> State {
let dir = cache_dir();
- let k = key(email);
+ let k = cache_key(email, hint);
if let Some(dir) = &dir {
if let Ok(bytes) = std::fs::read(dir.join(format!("{k}.img"))) {
return State::Ready(Arc::from(bytes.into_boxed_slice()));
@@ -93,15 +171,19 @@ fn fetch(agent: &ureq::Agent, email: &str) -> State {
return State::Missing;
}
}
- let result = agent.get(&url(email)).call().ok().and_then(|resp| {
- let mut bytes = Vec::new();
- use std::io::Read;
- resp.into_reader()
- .take(512 * 1024)
- .read_to_end(&mut bytes)
- .ok()
- .map(|_| bytes)
- });
+ let result = agent
+ .get(&source(agent, email, hint))
+ .call()
+ .ok()
+ .and_then(|resp| {
+ let mut bytes = Vec::new();
+ use std::io::Read;
+ resp.into_reader()
+ .take(512 * 1024)
+ .read_to_end(&mut bytes)
+ .ok()
+ .map(|_| bytes)
+ });
match result {
Some(bytes) if !bytes.is_empty() => {
if let Some(dir) = &dir {
@@ -155,6 +237,24 @@ pub fn paint(ui: &egui::Ui, rect: Rect, email: &str) -> bool {
mod tests {
use super::*;
+ #[test]
+ fn hinted_sources() {
+ let agent = ureq::AgentBuilder::new().build();
+ assert_eq!(
+ source(
+ &agent,
+ Some(&Hint::Url("https://av/u/1?v=4".into()))
+ ),
+ "https://av/u/1?v=4&s=80"
+ );
+ assert_eq!(query_escape("[email protected]"), "me%[email protected]");
+ assert_ne!(
+ cache_key("[email protected]", None),
+ cache_key("[email protected]", Some(&Hint::Url(String::new())))
+ );
+ }
+
#[test]
fn avatar_urls() {
assert_eq!(
diff --git a/src/forge.rs b/src/forge.rs
index 055d2a5..95c7e75 100644
--- a/src/forge.rs
+++ b/src/forge.rs
@@ -1,6 +1,7 @@
//! Pull requests through the forges' own command-line tools: `gh` for GitHub, `glab` for
//! GitLab. They hold the user's login, so gitcraft never stores a token.
+use std::collections::HashMap;
use std::path::Path;
use std::process::Command;
@@ -174,10 +175,109 @@ pub fn create(
tool(forge, repo, &args).map(|out| out.trim().to_owned())
}
+/// The web host and `owner/repo` path of a remote URL: `https://host/owner/repo.git`,
+/// `git@host:owner/repo.git` or `ssh://git@host[:port]/owner/repo`.
+pub fn location(url: &str) -> Option<(String, String)> {
+ let url = url.trim();
+ let (host, path) = match url.split_once("://") {
+ Some((_, rest)) => {
+ let rest = rest.rsplit_once('@').map_or(rest, |(_, r)| r);
+ let (host, path) = rest.split_once('/')?;
+ (host.split(':').next().unwrap_or(host), path)
+ }
+ None => {
+ let rest = url.rsplit_once('@').map_or(url, |(_, r)| r);
+ rest.split_once(':')?
+ }
+ };
+ let path = path.trim_matches('/');
+ let path = path.strip_suffix(".git").unwrap_or(path);
+ (!host.is_empty() && path.contains('/')).then(|| (host.to_lowercase(), path.to_owned()))
+}
+
+/// GitHub accounts' avatars by commit email, from the repository's latest commits (the API ties
+/// each commit to the account its email belongs to). Through `gh` when it's installed (private
+/// repositories, higher limits), else GitHub's public API.
+pub fn github_avatars(repo: &Path, host: &str, path: &str) -> HashMap<String, String> {
+ let endpoint = format!("repos/{path}/commits?per_page=100");
+ let mut args = vec!["api", endpoint.as_str()];
+ if host != "github.com" {
+ args.extend(["--hostname", host]);
+ }
+ let json = tool(Forge::GitHub, repo, &args).or_else(|e| {
+ if host != "github.com" {
+ return Err(e);
+ }
+ ureq::AgentBuilder::new()
+ .timeout(std::time::Duration::from_secs(10))
+ .user_agent("gitcraft")
+ .build()
+ .get(&format!("https://api.github.com/{endpoint}"))
+ .call()
+ .map_err(|e| e.to_string())?
+ .into_string()
+ .map_err(|e| e.to_string())
+ });
+ json.map(|j| parse_github_avatars(&j)).unwrap_or_default()
+}
+
+fn parse_github_avatars(json: &str) -> HashMap<String, String> {
+ let mut out = HashMap::new();
+ let Ok(serde_json::Value::Array(items)) = serde_json::from_str(json) else {
+ return out;
+ };
+ for item in &items {
+ for (who, account) in [("author", "author"), ("committer", "committer")] {
+ let email = item
+ .pointer(&format!("/commit/{who}/email"))
+ .and_then(|e| e.as_str());
+ let avatar = item
+ .pointer(&format!("/{account}/avatar_url"))
+ .and_then(|a| a.as_str());
+ if let (Some(email), Some(avatar)) = (email, avatar) {
+ out.entry(email.trim().to_lowercase())
+ .or_insert_with(|| avatar.to_owned());
+ }
+ }
+ }
+ out
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn remote_locations() {
+ let gh = Some(("github.com".to_owned(), "owner/repo".to_owned()));
+ assert_eq!(location("https://github.com/owner/repo.git"), gh);
+ assert_eq!(location("https://[email protected]/owner/repo/"), gh);
+ assert_eq!(location("[email protected]:owner/repo.git"), gh);
+ assert_eq!(location("ssh://[email protected]:22/owner/repo"), gh);
+ assert_eq!(
+ location("https://gitlab.example.org/group/sub/proj.git"),
+ Some(("gitlab.example.org".to_owned(), "group/sub/proj".to_owned()))
+ );
+ assert_eq!(location("/srv/git/repo.git"), None);
+ }
+
+ #[test]
+ fn github_avatars_by_email() {
+ let json = r#"[
+ {"commit": {"author": {"email": "[email protected]"}, "committer": {"email": "[email protected]"}},
+ "author": {"avatar_url": "https://a/1?v=4"}, "committer": {"avatar_url": "https://a/web?v=4"}},
+ {"commit": {"author": {"email": "[email protected]"}, "committer": {"email": "[email protected]"}},
+ "author": null, "committer": null}
+ ]"#;
+ let m = parse_github_avatars(json);
+ assert_eq!(
+ m.get("[email protected]").map(String::as_str),
+ Some("https://a/1?v=4")
+ );
+ assert!(m.contains_key("[email protected]"));
+ assert!(!m.contains_key("[email protected]"));
+ }
+
#[test]
fn detects_forge_from_origin() {
let r = |name: &str, url: &str| Remote {
diff --git a/src/git.rs b/src/git.rs
index 37ceccd..67762f2 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -18,6 +18,8 @@ fn git_cmd() -> Command {
cmd.env("GIT_OPTIONAL_LOCKS", "0");
// `rebase --continue`, `merge --continue`… would otherwise open an editor nobody sees.
cmd.env("GIT_EDITOR", "true");
+ // Interactive rebases set `sequence.editor` themselves; an inherited one would win.
+ cmd.env_remove("GIT_SEQUENCE_EDITOR");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
@@ -51,10 +53,62 @@ pub fn run_bytes(dir: Option<&Path>, args: &[&str]) -> Result<Vec<u8>, String> {
/// Like [`run`], but exit codes in `ok` count as success (`diff --no-index` exits 1 on changes).
pub fn run_ok_codes(dir: Option<&Path>, args: &[&str], ok: &[i32]) -> Result<String, String> {
+ run_inner(dir, args, ok, None)
+}
+
+/// A username and password (or token) for an HTTPS remote, typed into gitcraft.
+#[derive(Clone)]
+pub struct Credentials {
+ pub username: String,
+ pub password: String,
+}
+
+/// A credential helper that answers git's `get` from the environment, so the secret never shows
+/// up in a command line. git tries the user's own helpers first and, when the operation works,
+/// asks them to store what this one gave.
+const ENV_HELPER: &str = "credential.helper=!f() { test \"$1\" = get && echo \"username=$GITCRAFT_GIT_USERNAME\" && echo \"password=$GITCRAFT_GIT_PASSWORD\"; }; f";
+
+/// [`run`], answering a credential request with `creds` when given.
+pub fn run_with(
+ dir: Option<&Path>,
+ args: &[&str],
+ creds: Option<&Credentials>,
+) -> Result<String, String> {
+ run_inner(dir, args, &[0], creds)
+}
+
+/// Whether `err` says git needed a username / password it couldn't get or that were refused.
+pub fn is_auth_error(err: &str) -> bool {
+ let e = err.to_lowercase();
+ [
+ "terminal prompts disabled",
+ "could not read username",
+ "could not read password",
+ "authentication failed",
+ "invalid username or password",
+ "http basic: access denied",
+ "the requested url returned error: 401",
+ "the requested url returned error: 403",
+ ]
+ .iter()
+ .any(|s| e.contains(s))
+}
+
+fn run_inner(
+ dir: Option<&Path>,
+ args: &[&str],
+ ok: &[i32],
+ creds: Option<&Credentials>,
+) -> Result<String, String> {
let mut cmd = git_cmd();
if let Some(dir) = dir {
cmd.arg("-C").arg(dir);
}
+ if let Some(c) = creds {
+ cmd.args(["-c", ENV_HELPER]);
+ cmd.env("GITCRAFT_GIT_USERNAME", &c.username);
+ cmd.env("GITCRAFT_GIT_PASSWORD", &c.password);
+ }
cmd.args(args);
let out = cmd
.output()
@@ -76,9 +130,9 @@ pub fn run_ok_codes(dir: Option<&Path>, args: &[&str], ok: &[i32]) -> Result<Str
}
/// `git clone url dest`, run from `dest`'s parent.
-pub fn clone(url: &str, dest: &Path) -> Result<(), String> {
+pub fn clone(url: &str, dest: &Path, creds: Option<&Credentials>) -> Result<(), String> {
let dest = dest.to_string_lossy();
- run(None, &["clone", "--", url, &dest]).map(|_| ())
+ run_with(None, &["clone", "--", url, &dest], creds).map(|_| ())
}
/// The folder name `git clone` would pick for `url`.
@@ -794,6 +848,203 @@ pub fn identity(repo: &Path) -> Identity {
}
}
+/// A commit an interactive rebase would rewrite.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RebaseCommit {
+ pub hash: String,
+ pub author: String,
+ pub email: String,
+ pub summary: String,
+ /// The whole message (summary and body).
+ pub message: String,
+ pub merge: bool,
+}
+
+/// The commits `git rebase -i onto` would list (`onto..HEAD`), oldest first.
+pub fn rebase_commits(repo: &Path, onto: &str) -> Result<Vec<RebaseCommit>, String> {
+ let format = format!("--format={RS}%H{FS}%P{FS}%an{FS}%ae{FS}%s{FS}%B");
+ let range = format!("{onto}..HEAD");
+ let out = run(Some(repo), &["log", "--reverse", &format, &range])?;
+ Ok(parse_rebase_commits(&out))
+}
+
+fn parse_rebase_commits(out: &str) -> Vec<RebaseCommit> {
+ out.split(RS)
+ .filter_map(|record| {
+ let mut f = record.splitn(6, FS);
+ let hash = f.next()?.trim().to_owned();
+ if hash.is_empty() {
+ return None;
+ }
+ Some(RebaseCommit {
+ hash,
+ merge: f.next()?.split_whitespace().count() > 1,
+ author: f.next()?.to_owned(),
+ email: f.next()?.to_owned(),
+ summary: f.next()?.to_owned(),
+ message: f.next()?.trim_end().to_owned(),
+ })
+ })
+ .collect()
+}
+
+/// Adds `pattern` as a line of the repository's top `.gitignore` (created if missing). `false`
+/// when it was already there.
+pub fn add_to_gitignore(repo: &Path, pattern: &str) -> Result<bool, String> {
+ let file = repo.join(".gitignore");
+ let existing = match std::fs::read_to_string(&file) {
+ Ok(s) => s,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
+ Err(e) => return Err(format!("could not read .gitignore: {e}")),
+ };
+ match gitignore_with(&existing, pattern) {
+ Some(updated) => std::fs::write(&file, updated)
+ .map(|_| true)
+ .map_err(|e| format!("could not write .gitignore: {e}")),
+ None => Ok(false),
+ }
+}
+
+/// `existing` with `pattern` appended on a line of its own (keeping its line endings), or `None`
+/// when the line is already there.
+fn gitignore_with(existing: &str, pattern: &str) -> Option<String> {
+ if existing.lines().any(|l| l.trim() == pattern) {
+ return None;
+ }
+ let nl = if existing.contains("\r\n") {
+ "\r\n"
+ } else {
+ "\n"
+ };
+ let mut out = existing.to_owned();
+ if !out.is_empty() && !out.ends_with('\n') {
+ out.push_str(nl);
+ }
+ out.push_str(pattern);
+ out.push_str(nl);
+ Some(out)
+}
+
+/// Whether git tracks `path` (so ignoring it also needs `git rm --cached`).
+pub fn is_tracked(repo: &Path, path: &str) -> bool {
+ run(Some(repo), &["ls-files", "--error-unmatch", "--", path]).is_ok()
+}
+
+/// One commit in a file's history, with the file's path at that commit (renames are followed).
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct FileCommit {
+ pub hash: String,
+ pub author: String,
+ pub email: String,
+ pub time: i64,
+ pub summary: String,
+ pub path: String,
+}
+
+/// Every commit that changed `path` up to `rev` (HEAD when `None`), newest first, following
+/// renames.
+pub fn file_history(repo: &Path, rev: Option<&str>, path: &str) -> Result<Vec<FileCommit>, String> {
+ let format = format!("--format={RS}%H{FS}%an{FS}%ae{FS}%at{FS}%s");
+ let mut args = vec![
+ "-c",
+ "core.quotePath=false",
+ "log",
+ "--follow",
+ "--name-only",
+ &format,
+ ];
+ if let Some(rev) = rev {
+ args.push(rev);
+ }
+ args.extend(["--", path]);
+ let out = run(Some(repo), &args)?;
+ Ok(parse_file_history(&out))
+}
+
+fn parse_file_history(out: &str) -> Vec<FileCommit> {
+ out.split(RS)
+ .filter_map(|record| {
+ let mut lines = record.lines();
+ let mut f = lines.next()?.split(FS);
+ let mut c = FileCommit {
+ hash: f.next()?.to_owned(),
+ author: f.next().unwrap_or_default().to_owned(),
+ email: f.next().unwrap_or_default().to_owned(),
+ time: f.next().and_then(|t| t.parse().ok()).unwrap_or(0),
+ summary: f.next().unwrap_or_default().to_owned(),
+ path: String::new(),
+ };
+ c.path = lines.rfind(|l| !l.trim().is_empty())?.to_owned();
+ Some(c)
+ })
+ .collect()
+}
+
+/// One line of `git blame`: who last changed it, in which commit.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct BlameLine {
+ pub hash: String,
+ pub author: String,
+ pub email: String,
+ pub time: i64,
+ pub summary: String,
+ pub text: String,
+}
+
+impl BlameLine {
+ /// Lines changed in the working tree and not committed yet.
+ pub fn uncommitted(&self) -> bool {
+ self.hash.bytes().all(|b| b == b'0')
+ }
+}
+
+/// `git blame` of `path`, as of `rev` (the working tree when `None`).
+pub fn blame(repo: &Path, rev: Option<&str>, path: &str) -> Result<Vec<BlameLine>, String> {
+ let mut args = vec!["blame", "--porcelain"];
+ if let Some(rev) = rev {
+ args.push(rev);
+ }
+ args.extend(["--", path]);
+ Ok(parse_blame(&run(Some(repo), &args)?))
+}
+
+fn parse_blame(out: &str) -> Vec<BlameLine> {
+ use std::collections::HashMap;
+ // The porcelain format describes each commit once, the first time it shows up.
+ let mut known: HashMap<String, BlameLine> = HashMap::new();
+ let mut lines = Vec::new();
+ let mut current: Option<BlameLine> = None;
+ for line in out.lines() {
+ if let Some(text) = line.strip_prefix('\t') {
+ if let Some(mut c) = current.take() {
+ known.entry(c.hash.clone()).or_insert_with(|| c.clone());
+ c.text = text.to_owned();
+ lines.push(c);
+ }
+ continue;
+ }
+ let Some(c) = current.as_mut() else {
+ let hash = line.split(' ').next().unwrap_or_default();
+ if hash.len() == 40 {
+ current = Some(known.get(hash).cloned().unwrap_or_else(|| BlameLine {
+ hash: hash.to_owned(),
+ ..BlameLine::default()
+ }));
+ }
+ continue;
+ };
+ let (key, value) = line.split_once(' ').unwrap_or((line, ""));
+ match key {
+ "author" => c.author = value.to_owned(),
+ "author-mail" => c.email = value.trim_matches(['<', '>']).to_owned(),
+ "author-time" => c.time = value.parse().unwrap_or(0),
+ "summary" => c.summary = value.to_owned(),
+ _ => {}
+ }
+ }
+ lines
+}
+
/// "3 minutes ago", "2 days ago"… for `time` seen from `now` (both Unix seconds).
pub fn relative_time(time: i64, now: i64) -> String {
let secs = (now - time).max(0);
@@ -820,6 +1071,64 @@ pub fn now() -> i64 {
mod tests {
use super::*;
+ #[test]
+ fn gitignore_lines() {
+ assert_eq!(gitignore_with("", "/a.log").as_deref(), Some("/a.log\n"));
+ assert_eq!(
+ gitignore_with("target\n", "*.log").as_deref(),
+ Some("target\n*.log\n")
+ );
+ // No trailing newline, CRLF kept.
+ assert_eq!(
+ gitignore_with("a\r\nb", "c").as_deref(),
+ Some("a\r\nb\r\nc\r\n")
+ );
+ assert_eq!(gitignore_with("x\n*.log\n", "*.log"), None);
+ }
+
+ #[test]
+ fn file_history_follows_renames() {
+ let out = format!(
+ "{RS}aaa{FS}Ann{FS}ann@x{FS}200{FS}Rename\n\nsrc/new.rs\n{RS}bbb{FS}Bob{FS}bob@x{FS}100{FS}Add\n\nold.rs\n"
+ );
+ let h = parse_file_history(&out);
+ assert_eq!(h.len(), 2);
+ assert_eq!(
+ (h[0].hash.as_str(), h[0].path.as_str()),
+ ("aaa", "src/new.rs")
+ );
+ assert_eq!(
+ (h[1].author.as_str(), h[1].time, h[1].path.as_str()),
+ ("Bob", 100, "old.rs")
+ );
+ }
+
+ #[test]
+ fn blame_reuses_commit_headers() {
+ let a = "a".repeat(40);
+ let z = "0".repeat(40);
+ let out = format!(
+ "{a} 1 1 2\nauthor Ann\nauthor-mail <ann@x>\nauthor-time 100\nsummary First\nfilename f\n\tone\n\
+ {a} 2 2\n\ttwo\n\
+ {z} 3 3 1\nauthor Not Committed Yet\nauthor-mail <not.committed.yet>\nauthor-time 200\nsummary Version of f from f\nfilename f\n\tthree\n"
+ );
+ let b = parse_blame(&out);
+ assert_eq!(b.len(), 3);
+ assert_eq!(
+ (
+ b[0].author.as_str(),
+ b[0].email.as_str(),
+ b[0].text.as_str()
+ ),
+ ("Ann", "ann@x", "one")
+ );
+ assert_eq!(
+ (b[1].summary.as_str(), b[1].time, b[1].text.as_str()),
+ ("First", 100, "two")
+ );
+ assert!(!b[1].uncommitted() && b[2].uncommitted());
+ }
+
#[test]
fn status_sides_renames_and_conflicts() {
let s =
diff --git a/src/icons.rs b/src/icons.rs
index 505a6bc..2bfcf01 100644
--- a/src/icons.rs
+++ b/src/icons.rs
@@ -5,7 +5,7 @@
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
-use egui::{Color32, Rect, Response, RichText, Sense, Ui, Vec2, load::Bytes};
+use egui::{Color32, Rect, Response, Sense, Ui, Vec2, load::Bytes};
use crate::theme::Tokens;
@@ -41,6 +41,7 @@ const SOURCES: &[(&str, &str)] = icons![
"git-branch-plus",
"git-merge",
"git-pull-request",
+ "history",
"laptop",
"log-in",
"minus",
@@ -92,20 +93,52 @@ pub fn paint(ui: &Ui, rect: Rect, name: &str, size: f32, tint: Color32) {
/// A flat toolbar button: icon plus optional label, background only on hover (PhotoCraft's
/// options-bar buttons).
pub fn tool_button(ui: &mut Ui, icon: &str, label: &str, enabled: bool) -> Response {
+ // Painted by hand at a fixed size: egui's button adds its border's width only while the
+ // frame shows, so hovering one pushed the rest of the toolbar sideways.
+ const PAD: f32 = 10.0;
+ const ICON: f32 = 16.0;
+ const GAP: f32 = 6.0;
let t = Tokens::get(ui.ctx());
let tint = if enabled { t.icon } else { t.text_faint };
- let mut button = egui::Button::image_and_text(
- image(icon, 16.0, tint),
- RichText::new(label).color(if enabled { t.text } else { t.text_faint }),
- )
- .frame_when_inactive(false)
- .min_size(egui::vec2(0.0, 28.0));
- if label.is_empty() {
- button = egui::Button::image(image(icon, 16.0, tint))
- .frame_when_inactive(false)
- .min_size(egui::vec2(28.0, 28.0));
- }
- ui.add_enabled(enabled, button)
+ let color = if enabled { t.text } else { t.text_faint };
+ let galley = (!label.is_empty()).then(|| {
+ let font = egui::TextStyle::Button.resolve(ui.style());
+ ui.painter().layout_no_wrap(label.to_owned(), font, color)
+ });
+ let width = match &galley {
+ Some(g) => PAD + ICON + GAP + g.size().x + PAD,
+ None => 28.0,
+ };
+ ui.add_enabled(enabled, |ui: &mut Ui| {
+ let (rect, resp) = ui.allocate_exact_size(Vec2::new(width, 28.0), Sense::click());
+ let r = egui::CornerRadius::same(t.radius_sm as u8);
+ if resp.is_pointer_button_down_on() {
+ ui.painter().rect_filled(rect, r, t.pressed);
+ } else if resp.hovered() || resp.has_focus() {
+ ui.painter().rect_filled(rect, r, t.hover);
+ ui.painter().rect_stroke(
+ rect,
+ r,
+ egui::Stroke::new(1.0, t.field_border),
+ egui::StrokeKind::Inside,
+ );
+ }
+ let icon_left = if galley.is_some() {
+ rect.left() + PAD
+ } else {
+ rect.center().x - ICON / 2.0
+ };
+ let icon_rect = Rect::from_min_size(
+ egui::pos2(icon_left, rect.center().y - ICON / 2.0),
+ Vec2::splat(ICON),
+ );
+ paint(ui, icon_rect, icon, ICON, tint);
+ if let Some(g) = galley {
+ let pos = egui::pos2(icon_rect.right() + GAP, rect.center().y - g.size().y / 2.0);
+ ui.painter().galley(pos, g, color);
+ }
+ resp
+ })
}
/// A small square icon-only button (rows, panel headers).
@@ -115,7 +148,13 @@ pub fn small_button(ui: &mut Ui, icon: &str, tooltip: &str) -> Response {
if resp.hovered() {
ui.painter().rect_filled(rect, t.radius_sm, t.pressed);
}
- let tint = if resp.hovered() { t.text } else { t.icon };
+ let tint = if !ui.is_enabled() {
+ t.text_faint
+ } else if resp.hovered() {
+ t.text
+ } else {
+ t.icon
+ };
paint(ui, rect, icon, 14.0, tint);
resp.on_hover_text(tooltip)
}
diff --git a/src/lib.rs b/src/lib.rs
index 2672c86..2256c8b 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -10,3 +10,4 @@ mod repo;
mod settings;
mod terminal;
mod theme;
+mod update;
diff --git a/src/main.rs b/src/main.rs
index 647a7fc..bbef710 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,6 +1,8 @@
// No console window behind the app on Windows release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+use std::sync::atomic::Ordering;
+
use gitcraft::app;
fn main() -> eframe::Result {
@@ -8,7 +10,17 @@ fn main() -> eframe::Result {
viewport: egui::ViewportBuilder::default()
.with_title("gitcraft")
.with_inner_size([1400.0, 860.0])
- .with_min_inner_size([800.0, 500.0]),
+ .with_min_inner_size([800.0, 500.0])
+ .with_icon(app::window_icon()),
+ // Runs after eframe restored the last session's size and position.
+ window_builder: Some(Box::new(|builder| {
+ if cfg!(windows) && builder.maximized == Some(true) {
+ app::MAXIMIZE_WHEN_SHOWN.store(true, Ordering::Relaxed);
+ builder.with_maximized(false)
+ } else {
+ builder
+ }
+ })),
..Default::default()
};
eframe::run_native(
diff --git a/src/repo/detail.rs b/src/repo/detail.rs
index 78cbbae..0b62b05 100644
--- a/src/repo/detail.rs
+++ b/src/repo/detail.rs
@@ -234,7 +234,7 @@ impl RepoTab {
selected,
RowExtra::Stats(f.added, f.removed),
);
- widgets::file_menu(&r.row, &f.path, acts);
+ widgets::file_menu(&r.row, &f.path, Some(&detail.hash), false, acts);
if r.row.clicked() {
acts.push(Action::OpenDiff(key));
}
@@ -388,7 +388,7 @@ impl RepoTab {
RowExtra::Buttons(buttons),
);
if f.code != 'D' {
- widgets::file_menu(&r.row, &f.path, acts);
+ widgets::file_menu(&r.row, &f.path, None, true, acts);
}
match r.button {
Some(i) => RowClick::Button(i),
diff --git a/src/repo/dialogs.rs b/src/repo/dialogs.rs
index a50af86..a1b33f9 100644
--- a/src/repo/dialogs.rs
+++ b/src/repo/dialogs.rs
@@ -69,6 +69,15 @@ pub enum Dialog {
url: String,
focus: bool,
},
+ /// Username and password / token for an HTTPS remote that asked for them.
+ Credentials {
+ url: String,
+ /// The last ones typed were refused.
+ refused: bool,
+ username: String,
+ password: String,
+ focus: bool,
+ },
CreatePr {
noun: String,
branch: String,
@@ -118,6 +127,16 @@ impl Dialog {
self
}
+ pub fn credentials(url: &str, refused: bool) -> Self {
+ Dialog::Credentials {
+ url: url.to_owned(),
+ refused,
+ username: String::new(),
+ password: String::new(),
+ focus: true,
+ }
+ }
+
pub fn stash() -> Self {
Dialog::Stash {
message: String::new(),
@@ -580,6 +599,42 @@ impl RepoTab {
}
})
}
+ Dialog::Credentials { url, refused, username, password, focus } => {
+ let host = host_of(url);
+ title(
+ ui,
+ &format!("Sign in to {host}"),
+ "git needs a username and password for this remote. Most hosts want a personal access token as the password.",
+ &t,
+ );
+ if *refused {
+ ui.colored_label(t.danger, "Those credentials were refused. Check them and try again.");
+ ui.add_space(6.0);
+ }
+ field(ui, username, "Username", focus);
+ ui.add_space(4.0);
+ ui.add(
+ egui::TextEdit::singleline(password)
+ .password(true)
+ .hint_text("Password or token")
+ .desired_width(f32::INFINITY)
+ .margin(egui::Margin::symmetric(8, 6)),
+ );
+ ui.add_space(4.0);
+ ui.label(
+ RichText::new("Used for this tab until you close it. If git has a credential helper (such as Git Credential Manager), it saves them once they work.")
+ .color(t.text_faint)
+ .small(),
+ );
+ ui.add_space(8.0);
+ let valid = !username.trim().is_empty() && !password.is_empty();
+ buttons(ui, "Sign in", valid, enter, || {
+ Action::SignIn(crate::git::Credentials {
+ username: username.trim().to_owned(),
+ password: password.clone(),
+ })
+ })
+ }
Dialog::CreatePr { noun, branch, base, title: pr_title, body, draft, focus } => {
title(ui, &format!("Create {noun}"), &format!("{branch} → {base} (the branch is pushed first)"), &t);
field(ui, pr_title, "Title", focus);
@@ -678,6 +733,16 @@ impl RepoTab {
}
/// A dialog's heading and one line under it.
+/// `github.com` from `https://[email protected]/owner/repo.git`.
+fn host_of(url: &str) -> &str {
+ let rest = url.split_once("://").map_or(url, |(_, r)| r);
+ let rest = rest.rsplit_once('@').map_or(rest, |(_, r)| r);
+ rest.split(['/', ':'])
+ .next()
+ .filter(|h| !h.is_empty())
+ .unwrap_or("the remote")
+}
+
fn title(ui: &mut egui::Ui, heading: &str, sub: &str, t: &Tokens) {
ui.label(RichText::new(heading).font(theme::semibold(15.0)));
ui.label(RichText::new(sub).color(t.text_dim));
diff --git a/src/repo/diff.rs b/src/repo/diff.rs
index 4b405b8..35cbd74 100644
--- a/src/repo/diff.rs
+++ b/src/repo/diff.rs
@@ -351,7 +351,11 @@ impl RepoTab {
egui::Label::new(egui::RichText::new(&path).font(theme::medium(13.0)))
.sense(Sense::click()),
);
- widgets::file_menu(&title, &path, acts);
+ let (rev, ignorable) = match &view.key {
+ DiffKey::Commit { hash, .. } => (Some(hash.as_str()), false),
+ DiffKey::Work(_) => (None, true),
+ };
+ widgets::file_menu(&title, &path, rev, ignorable, acts);
widgets::chip(ui, &origin, t.text_dim);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if icons::small_button(ui, "x", "Close (Esc)").clicked() {
diff --git a/src/repo/file_view.rs b/src/repo/file_view.rs
new file mode 100644
index 0000000..ecea009
--- /dev/null
+++ b/src/repo/file_view.rs
@@ -0,0 +1,397 @@
+//! Central pane for one file: its history (every commit that changed it, following renames) or
+//! its blame (who last changed each line). Opened from a file's right-click menu.
+
+use std::path::Path;
+
+use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, Ui, pos2, vec2};
+
+use super::highlight::{self, Spans};
+use super::widgets;
+use super::{Action, DiffKey, RepoTab};
+use crate::git::{self, BlameLine, FileCommit};
+use crate::icons;
+use crate::theme::{self, Tokens};
+
+const ROW_H: f32 = 30.0;
+const LINE_H: f32 = 19.0;
+const GUTTER_W: f32 = 270.0;
+const NUM_W: f32 = 46.0;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum FileTab {
+ History,
+ Blame,
+}
+
+pub(crate) struct FileView {
+ pub path: String,
+ /// The commit history and blame start at; HEAD and the working tree when `None`.
+ pub rev: Option<String>,
+ pub tab: FileTab,
+ pub history: Option<Result<Vec<FileCommit>, String>>,
+ pub blame: Option<Result<BlameData, String>>,
+}
+
+pub(crate) struct BlameData {
+ lines: Vec<BlameLine>,
+ spans: Option<Vec<Spans>>,
+ /// Oldest and newest commit time, for the age colour.
+ span: (i64, i64),
+}
+
+impl FileView {
+ pub fn new(path: &str, rev: Option<String>, tab: FileTab) -> Self {
+ Self {
+ path: path.to_owned(),
+ rev,
+ tab,
+ history: None,
+ blame: None,
+ }
+ }
+
+ /// Whether `tab` still has to be loaded.
+ pub fn needs(&self, tab: FileTab) -> bool {
+ match tab {
+ FileTab::History => self.history.is_none(),
+ FileTab::Blame => self.blame.is_none(),
+ }
+ }
+}
+
+/// Runs `git blame` and colours the lines; on a background thread.
+pub(crate) fn load_blame(
+ repo: &Path,
+ rev: Option<&str>,
+ path: &str,
+ dark: bool,
+) -> Result<BlameData, String> {
+ let lines = git::blame(repo, rev, path)?;
+ let spans = highlight::highlight(path, lines.iter().map(|l| l.text.as_str()), dark);
+ let times = lines.iter().filter(|l| !l.uncommitted()).map(|l| l.time);
+ let span = (times.clone().min().unwrap_or(0), times.max().unwrap_or(0));
+ Ok(BlameData { lines, spans, span })
+}
+
+impl RepoTab {
+ pub(super) fn file_view(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {
+ let t = Tokens::get(ui.ctx());
+ let Some(view) = &self.file_view else { return };
+
+ egui::Frame::new()
+ .fill(t.chrome)
+ .inner_margin(egui::Margin::symmetric(10, 6))
+ .stroke(Stroke::new(1.0, t.separator))
+ .show(ui, |ui| {
+ ui.horizontal(|ui| {
+ icons::inline(ui, "history", 16.0, t.icon);
+ ui.label(egui::RichText::new(&view.path).font(theme::medium(13.0)));
+ if let Some(rev) = &view.rev {
+ widgets::chip(
+ ui,
+ &format!("at {}", rev.get(..8).unwrap_or(rev)),
+ t.text_dim,
+ );
+ }
+ ui.add_space(12.0);
+ for (tab, label) in [(FileTab::History, "History"), (FileTab::Blame, "Blame")] {
+ let on = view.tab == tab;
+ let b = ui.add(
+ egui::Button::new(egui::RichText::new(label).color(if on {
+ t.text
+ } else {
+ t.text_dim
+ }))
+ .frame_when_inactive(on),
+ );
+ if on {
+ widgets::active_underline(ui, b.rect, t.accent);
+ }
+ if b.clicked() && !on {
+ acts.push(Action::FileView {
+ path: view.path.clone(),
+ rev: view.rev.clone(),
+ tab,
+ });
+ }
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if icons::small_button(ui, "x", "Close (Esc)").clicked() {
+ acts.push(Action::CloseFileView);
+ }
+ });
+ });
+ });
+
+ match view.tab {
+ FileTab::History => self.history_list(ui, acts),
+ FileTab::Blame => self.blame_lines(ui, acts),
+ }
+ }
+
+ fn history_list(&self, ui: &mut Ui, acts: &mut Vec<Action>) {
+ let t = Tokens::get(ui.ctx());
+ let Some(view) = &self.file_view else { return };
+ let commits = match &view.history {
+ None => {
+ ui.centered_and_justified(|ui| ui.spinner());
+ return;
+ }
+ Some(Err(e)) => {
+ error(ui, e);
+ return;
+ }
+ Some(Ok(c)) => c,
+ };
+ if commits.is_empty() {
+ ui.centered_and_justified(|ui| {
+ ui.label(egui::RichText::new("No commits touch this file yet.").color(t.text_dim));
+ });
+ return;
+ }
+ let now = git::now();
+ let open = match self.diff.as_ref().map(|d| &d.key) {
+ Some(DiffKey::Commit { hash, .. }) => Some(hash.as_str()),
+ _ => None,
+ };
+ ui.spacing_mut().item_spacing.y = 0.0;
+ egui::ScrollArea::vertical()
+ .id_salt(("file_history", &view.path))
+ .auto_shrink(false)
+ .show_rows(ui, ROW_H, commits.len(), |ui, range| {
+ for i in range {
+ let Some(c) = commits.get(i) else { continue };
+ let (rect, resp) =
+ ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());
+ let p = ui.painter_at(rect);
+ if open == Some(c.hash.as_str()) {
+ p.rect_filled(rect, 0.0, t.row_selected);
+ } else if resp.hovered() {
+ p.rect_filled(rect, 0.0, t.hover);
+ }
+ let mid = rect.center().y;
+ widgets::avatar(ui, pos2(rect.left() + 22.0, mid), 10.0, &c.author, &c.email);
+ let right = rect.right() - 12.0;
+ let hash = p.text(
+ pos2(right, mid),
+ Align2::RIGHT_CENTER,
+ c.hash.get(..7).unwrap_or(&c.hash),
+ theme::mono(11.0),
+ t.text_faint,
+ );
+ let when = p.text(
+ pos2(hash.left() - 16.0, mid),
+ Align2::RIGHT_CENTER,
+ git::relative_time(c.time, now),
+ FontId::proportional(11.5),
+ t.text_dim,
+ );
+ let author = p.text(
+ pos2(when.left() - 16.0, mid),
+ Align2::RIGHT_CENTER,
+ &c.author,
+ FontId::proportional(11.5),
+ t.text_dim,
+ );
+ let mut summary = c.summary.clone();
+ if c.path != view.path {
+ summary = format!("{summary} · as {}", c.path);
+ }
+ p.with_clip_rect(Rect::from_min_max(
+ rect.min,
+ pos2(author.left() - 16.0, rect.bottom()),
+ ))
+ .text(
+ pos2(rect.left() + 42.0, mid),
+ Align2::LEFT_CENTER,
+ summary,
+ FontId::proportional(12.5),
+ t.text,
+ );
+ let resp = resp.on_hover_text(
+ "Click: this commit's changes to the file\nDouble-click: show the commit in the graph",
+ );
+ if resp.double_clicked() {
+ acts.push(Action::CloseFileView);
+ acts.push(Action::SelectHash(c.hash.clone()));
+ } else if resp.clicked() {
+ acts.push(Action::OpenDiff(DiffKey::Commit {
+ hash: c.hash.clone(),
+ path: c.path.clone(),
+ }));
+ }
+ }
+ });
+ }
+
+ fn blame_lines(&self, ui: &mut Ui, acts: &mut Vec<Action>) {
+ let t = Tokens::get(ui.ctx());
+ let Some(view) = &self.file_view else { return };
+ let data = match &view.blame {
+ None => {
+ ui.centered_and_justified(|ui| ui.spinner());
+ return;
+ }
+ Some(Err(e)) => {
+ error(ui, e);
+ return;
+ }
+ Some(Ok(d)) => d,
+ };
+ let now = git::now();
+ let font = theme::mono(12.0);
+ let char_w = ui
+ .painter()
+ .layout_no_wrap("M".to_owned(), font.clone(), t.text)
+ .size()
+ .x;
+ let longest = data
+ .lines
+ .iter()
+ .map(|l| l.text.chars().count())
+ .max()
+ .unwrap_or(0) as f32;
+ let width = (GUTTER_W + NUM_W + 16.0 + longest * char_w + 24.0).max(ui.available_width());
+ ui.spacing_mut().item_spacing.y = 0.0;
+ egui::ScrollArea::both()
+ .id_salt(("file_blame", &view.path, &view.rev))
+ .auto_shrink(false)
+ .show_rows(ui, LINE_H, data.lines.len(), |ui, range| {
+ for i in range {
+ let Some(line) = data.lines.get(i) else {
+ continue;
+ };
+ let (rect, _) = ui.allocate_exact_size(vec2(width, LINE_H), Sense::hover());
+ let clip = rect.intersect(ui.clip_rect());
+ let p = ui.painter().with_clip_rect(clip);
+ let first =
+ i == 0 || data.lines.get(i - 1).map(|l| &l.hash) != Some(&line.hash);
+ // Each change starts with a thin rule, so blocks read as one.
+ if first && i > 0 {
+ p.hline(rect.x_range(), rect.top(), Stroke::new(1.0, t.separator));
+ }
+ let gutter = Rect::from_min_size(rect.min, vec2(GUTTER_W, LINE_H));
+ p.rect_filled(gutter, 0.0, t.card);
+ p.rect_filled(
+ Rect::from_min_size(rect.min, vec2(3.0, LINE_H)),
+ 0.0,
+ age_color(&t, line, data.span),
+ );
+ let mid = rect.center().y;
+ let gutter_resp =
+ ui.interact(gutter, ui.id().with(("blame", i)), Sense::click());
+ if first {
+ let small = FontId::proportional(11.5);
+ if line.uncommitted() {
+ p.text(
+ pos2(gutter.left() + 10.0, mid),
+ Align2::LEFT_CENTER,
+ "Not committed yet",
+ small,
+ t.warning,
+ );
+ } else {
+ let hash = p.text(
+ pos2(gutter.left() + 10.0, mid),
+ Align2::LEFT_CENTER,
+ line.hash.get(..7).unwrap_or(&line.hash),
+ theme::mono(11.0),
+ if gutter_resp.hovered() {
+ t.accent
+ } else {
+ t.text_faint
+ },
+ );
+ let when = p.text(
+ pos2(gutter.right() - 8.0, mid),
+ Align2::RIGHT_CENTER,
+ git::relative_time(line.time, now),
+ small.clone(),
+ t.text_faint,
+ );
+ p.with_clip_rect(Rect::from_min_max(
+ pos2(hash.right() + 8.0, rect.top()),
+ pos2(when.left() - 8.0, rect.bottom()),
+ ))
+ .text(
+ pos2(hash.right() + 10.0, mid),
+ Align2::LEFT_CENTER,
+ &line.author,
+ small,
+ t.text_dim,
+ );
+ }
+ }
+ if !line.uncommitted() {
+ let gutter_resp = gutter_resp.on_hover_text(format!(
+ "{} · {}\n{}\nClick to show the commit",
+ line.author,
+ git::relative_time(line.time, now),
+ line.summary
+ ));
+ if gutter_resp.clicked() {
+ acts.push(Action::CloseFileView);
+ acts.push(Action::SelectHash(line.hash.clone()));
+ }
+ }
+ p.text(
+ pos2(gutter.right() + NUM_W - 8.0, mid),
+ Align2::RIGHT_CENTER,
+ (i + 1).to_string(),
+ theme::mono(11.0),
+ t.text_faint,
+ );
+ let x = gutter.right() + NUM_W + 8.0;
+ match data.spans.as_ref().and_then(|s| s.get(i)) {
+ Some(spans) => {
+ let mut job = egui::text::LayoutJob::default();
+ for (color, text) in spans {
+ job.append(
+ text,
+ 0.0,
+ egui::TextFormat {
+ font_id: font.clone(),
+ color: *color,
+ ..Default::default()
+ },
+ );
+ }
+ let galley = ui.painter().layout_job(job);
+ p.galley(pos2(x, mid - galley.size().y / 2.0), galley, t.text);
+ }
+ None => {
+ p.text(
+ pos2(x, mid),
+ Align2::LEFT_CENTER,
+ &line.text,
+ font.clone(),
+ t.text,
+ );
+ }
+ }
+ }
+ });
+ }
+}
+
+/// Newer lines get a stronger accent bar; uncommitted ones the warning colour.
+fn age_color(t: &Tokens, line: &BlameLine, (oldest, newest): (i64, i64)) -> Color32 {
+ if line.uncommitted() {
+ return t.warning;
+ }
+ let f = if newest > oldest {
+ (line.time - oldest) as f32 / (newest - oldest) as f32
+ } else {
+ 1.0
+ };
+ t.accent.gamma_multiply(0.15 + 0.85 * f)
+}
+
+fn error(ui: &mut Ui, e: &str) {
+ let t = Tokens::get(ui.ctx());
+ ui.add_space(12.0);
+ ui.horizontal(|ui| {
+ ui.add_space(12.0);
+ ui.colored_label(t.danger, e);
+ });
+}
diff --git a/src/repo/graph_view.rs b/src/repo/graph_view.rs
index 731b9d7..8fcb88a 100644
--- a/src/repo/graph_view.rs
+++ b/src/repo/graph_view.rs
@@ -7,7 +7,10 @@ use egui::{
};
use super::widgets;
-use super::{Action, Dialog, Refresh, RepoTab, Undo, WIP_HASH, ops};
+use super::{
+ Action, Dialog, Refresh, RepoTab, Undo, WIP_HASH, fast_forward_action, merge_action, ops,
+ rebase_action,
+};
use crate::git::{self, Refs};
use crate::icons;
use crate::settings::Settings;
@@ -168,7 +171,7 @@ impl RepoTab {
);
continue;
}
- let resp = self.commit_row(ui, i, cols, lanes, now);
+ let resp = self.commit_row(ui, i, cols, lanes, now, acts);
if resp.clicked() {
acts.push(Action::Select(i));
}
@@ -218,7 +221,82 @@ impl RepoTab {
.iter()
.filter(|b| b.target == hash)
.collect();
+ // The branch whose pill was right-clicked, else the commit's first branch for copying.
+ let pill: Option<String> = resp
+ .ctx
+ .data(|d| d.get_temp::<Option<String>>(pill_menu_id(&hash)))
+ .flatten();
+ let branch_name = pill.clone().or_else(|| {
+ badges(&commit.refs, &self.refs)
+ .into_iter()
+ .find(|b| b.kind == BadgeKind::Branch)
+ .map(|b| b.git_ref())
+ });
+ let target = self
+ .refs
+ .current
+ .clone()
+ .unwrap_or_else(|| "HEAD".to_owned());
resp.context_menu(|ui| {
+ if let Some(branch) = &pill
+ && self.refs.current.as_deref() != Some(branch.as_str())
+ {
+ if ui
+ .add_enabled(idle, egui::Button::new(format!("Check out {branch}")))
+ .clicked()
+ {
+ let local = self.refs.local.iter().any(|b| &b.name == branch);
+ acts.push(if local {
+ Action::Checkout(branch.clone())
+ } else {
+ Action::CheckoutRemote(branch.clone())
+ });
+ }
+ if let Some(current) = self.refs.current.as_deref() {
+ if ui
+ .add_enabled(
+ idle,
+ egui::Button::new(format!("Fast-forward {current} to {branch}")),
+ )
+ .clicked()
+ {
+ acts.push(fast_forward_action(branch, current));
+ }
+ if ui
+ .add_enabled(
+ idle,
+ egui::Button::new(format!("Merge {branch} into {current}")),
+ )
+ .clicked()
+ {
+ acts.push(merge_action(branch, current));
+ }
+ if ui
+ .add_enabled(
+ idle,
+ egui::Button::new(format!("Rebase {current} onto {branch}")),
+ )
+ .clicked()
+ {
+ acts.push(rebase_action(branch, current));
+ }
+ if ui
+ .add_enabled(
+ idle,
+ egui::Button::new(format!(
+ "Interactive rebase {current} onto {branch}…"
+ )),
+ )
+ .clicked()
+ {
+ acts.push(Action::InteractiveRebase {
+ onto: branch.clone(),
+ label: branch.clone(),
+ });
+ }
+ }
+ ui.separator();
+ }
for b in &here {
ui.menu_button(format!("Branch {}", b.name), |ui| {
self.branch_menu_items(ui, acts, b, idle);
@@ -243,6 +321,19 @@ impl RepoTab {
acts.push(Action::Checkout(hash.clone()));
}
ui.separator();
+ if ui
+ .add_enabled(
+ idle && !is_head,
+ egui::Button::new(format!("Interactive rebase {target} onto this commit…")),
+ )
+ .on_hover_text("Reorder, reword, squash or drop the commits after this one")
+ .clicked()
+ {
+ acts.push(Action::InteractiveRebase {
+ onto: hash.clone(),
+ label: short.clone(),
+ });
+ }
if ui
.add_enabled(
idle && !is_head,
@@ -268,7 +359,6 @@ impl RepoTab {
undo: Undo::HeadMove { mode: "--keep" },
});
}
- let target = self.refs.current.clone().unwrap_or_else(|| "HEAD".to_owned());
ui.add_enabled_ui(idle && !is_head, |ui| {
ui.menu_button(format!("Reset {target} to here"), |ui| {
for (mode, undo_mode, label, explain) in [
@@ -298,9 +388,98 @@ impl RepoTab {
if ui.button("Copy message").clicked() {
ui.ctx().copy_text(summary.clone());
}
+ if let Some(name) = &branch_name
+ && ui.button(format!("Copy branch name ({name})")).clicked()
+ {
+ ui.ctx().copy_text(name.clone());
+ }
});
}
+ /// What double-clicking a pill does: check out that branch (a tracking branch for one only on
+ /// a remote) or tag. Nothing for the checked-out one or while an operation runs.
+ fn pill_checkout(&self, badge: &Badge) -> Option<Action> {
+ if badge.head || self.busy_op.is_some() {
+ return None;
+ }
+ match badge.kind {
+ BadgeKind::Branch if badge.local => Some(Action::Checkout(badge.label.clone())),
+ BadgeKind::Branch => badge
+ .remotes
+ .first()
+ .map(|remote| Action::CheckoutRemote(format!("{remote}/{}", badge.label))),
+ BadgeKind::Tag => Some(Action::Checkout(format!("refs/tags/{}", badge.label))),
+ BadgeKind::DetachedHead => None,
+ }
+ }
+
+ /// While the pointer is on a row's `+N` (or on the list itself), every pill of the commit
+ /// stacked over the row, to pick one to check out. Returns whether it is open.
+ #[allow(clippy::too_many_arguments)]
+ fn ref_stack(
+ &self,
+ ui: &Ui,
+ badges: &[Badge],
+ i: usize,
+ more: Rect,
+ at: Pos2,
+ cols: Cols,
+ lane: Color32,
+ acts: &mut Vec<Action>,
+ ) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let id = ui.id().with(("ref_stack", i));
+ let last: Option<Rect> = ui.data(|d| d.get_temp(id));
+ let open = ui
+ .ctx()
+ .pointer_hover_pos()
+ .is_some_and(|p| more.contains(p) || last.is_some_and(|r| r.expand(2.0).contains(p)));
+ if !open {
+ ui.data_mut(|d| d.remove::<Rect>(id));
+ return false;
+ }
+ let slot_w = (cols.refs - 16.0).max(160.0);
+ let shown = egui::Area::new(id)
+ .order(egui::Order::Foreground)
+ .fixed_pos(at)
+ .show(ui.ctx(), |ui| {
+ egui::Frame::popup(ui.style())
+ .inner_margin(egui::Margin::same(6))
+ .show(ui, |ui| {
+ ui.spacing_mut().item_spacing.y = 4.0;
+ for b in badges {
+ let (slot, resp) =
+ ui.allocate_exact_size(vec2(slot_w, 20.0), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(
+ slot.expand(2.0),
+ CornerRadius::same(t.radius as u8),
+ t.hover,
+ );
+ }
+ let pr = b.kind == BadgeKind::Branch
+ && self.prs.iter().any(|p| p.branch == b.label);
+ ref_pill(ui, ui.painter(), slot.left_center(), b, lane, slot_w, pr);
+ let hint = if b.head {
+ "checked out"
+ } else {
+ "double-click to check out"
+ };
+ let resp = resp.on_hover_text(format!("{} ({hint})", b.describe()));
+ if resp.double_clicked() {
+ if let Some(act) = self.pill_checkout(b) {
+ acts.push(act);
+ }
+ } else if resp.clicked() {
+ acts.push(Action::Select(i));
+ }
+ }
+ });
+ });
+ ui.data_mut(|d| d.insert_temp(id, shown.response.rect));
+ true
+ }
+
fn search_bar(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {
let t = Tokens::get(ui.ctx());
egui::Frame::new()
@@ -363,7 +542,15 @@ impl RepoTab {
});
}
- fn commit_row(&self, ui: &mut Ui, i: usize, cols: Cols, lanes: usize, now: i64) -> Response {
+ fn commit_row(
+ &self,
+ ui: &mut Ui,
+ i: usize,
+ cols: Cols,
+ lanes: usize,
+ now: i64,
+ acts: &mut Vec<Action>,
+ ) -> Response {
let t = Tokens::get(ui.ctx());
let (rect, resp) =
ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());
@@ -424,13 +611,34 @@ impl RepoTab {
max_w.max(40.0),
has_pr,
);
+ // Right-clicking a branch pill puts that branch's actions on top of the menu.
+ if resp.secondary_clicked() {
+ let on_pill = ui
+ .ctx()
+ .pointer_interact_pos()
+ .is_some_and(|p| pill.contains(p));
+ let branch = (on_pill && first.kind == BadgeKind::Branch).then(|| first.git_ref());
+ ui.data_mut(|d| d.insert_temp(pill_menu_id(&commit.hash), branch));
+ }
+ if resp.double_clicked()
+ && ui
+ .ctx()
+ .pointer_interact_pos()
+ .is_some_and(|p| pill.contains(p))
+ && let Some(act) = self.pill_checkout(first)
+ {
+ acts.push(act);
+ }
let mut end = pill.right();
+ let mut more_rect = None;
if more > 0 {
let r = Rect::from_min_size(pos2(end + 3.0, mid - 10.0), vec2(more_w - 3.0, 20.0));
rp.rect_filled(
r,
CornerRadius::same(t.radius as u8),
- row_color.lerp_to_gamma(Color32::BLACK, 0.35),
+ row_color
+ .lerp_to_gamma(Color32::BLACK, 0.35)
+ .gamma_multiply(0.6),
);
rp.text(
r.center(),
@@ -440,6 +648,7 @@ impl RepoTab {
Color32::WHITE,
);
end = r.right();
+ more_rect = Some(r);
}
let avatar = pos2(end + 5.0 + AVATAR_D / 2.0, mid);
let when_rect = Rect::from_min_size(
@@ -464,11 +673,15 @@ impl RepoTab {
when_galley,
t.text_dim,
);
+ let stack_open = more_rect.is_some_and(|more| {
+ let at = pos2(rect.left() + 2.0, mid - 16.0);
+ self.ref_stack(ui, &badges, i, more, at, cols, row_color, acts)
+ });
let refs_cell = Rect::from_min_max(rect.min, pos2(gx, bottom));
- if ui.rect_contains_pointer(refs_cell) {
+ if !stack_open && ui.rect_contains_pointer(refs_cell) {
let lines: Vec<String> = badges.iter().map(Badge::describe).collect();
resp = resp.on_hover_text(format!(
- "{}\nTip commit by {} · {}",
+ "{}\nTip commit by {} · {}\nDouble-click a pill to check it out",
lines.join("\n"),
commit.author,
commit.date
@@ -622,7 +835,20 @@ enum BadgeKind {
DetachedHead,
}
+/// Where a row remembers which branch pill was right-clicked, for its menu.
+fn pill_menu_id(hash: &str) -> egui::Id {
+ egui::Id::new(("pill_menu", hash))
+}
+
impl Badge {
+ /// The name git knows a branch pill by: the local branch, else `remote/branch`.
+ fn git_ref(&self) -> String {
+ match self.remotes.first() {
+ Some(remote) if !self.local => format!("{remote}/{}", self.label),
+ _ => self.label.clone(),
+ }
+ }
+
fn describe(&self) -> String {
match self.kind {
BadgeKind::Tag => format!("tag {}", self.label),
@@ -742,6 +968,12 @@ fn ref_pill(
BadgeKind::Tag => Color32::from_rgb(104, 104, 112),
BadgeKind::DetachedHead => t.warning,
};
+ // Every pill but the checked-out one is a little see-through.
+ let fill = if badge.head {
+ fill
+ } else {
+ fill.gamma_multiply(0.6)
+ };
let mut lead = Vec::new();
let mut trail = Vec::new();
match badge.kind {
diff --git a/src/repo/mod.rs b/src/repo/mod.rs
index 50d51f5..1a3c34b 100644
--- a/src/repo/mod.rs
+++ b/src/repo/mod.rs
@@ -5,8 +5,10 @@ mod conflict;
mod detail;
mod dialogs;
mod diff;
+mod file_view;
mod graph_view;
mod highlight;
+mod rebase;
mod sidebar;
pub(crate) mod widgets;
@@ -45,6 +47,13 @@ enum Msg {
Status(Result<WorkStatus, String>),
Detail(String, Result<CommitDetail, String>),
Diff(DiffKey, Result<diff::DiffData, String>),
+ FileHistory(String, Result<Vec<git::FileCommit>, String>),
+ Blame(String, Option<String>, Result<file_view::BlameData, String>),
+ RebaseCommits {
+ onto: String,
+ label: String,
+ result: Result<Vec<git::RebaseCommit>, String>,
+ },
Search(String, Result<Vec<String>, String>),
Prs(Result<Vec<PullRequest>, String>),
OpDone {
@@ -99,6 +108,15 @@ pub(crate) struct UndoEntry {
redo: Vec<Vec<String>>,
}
+/// An operation as `run_ops_ex` got it, kept to retry it with credentials.
+struct PendingOp {
+ label: String,
+ ops: Vec<Vec<String>>,
+ refresh: Refresh,
+ kind: OpKind,
+ quiet: bool,
+}
+
#[derive(Clone, Debug)]
enum OpKind {
Normal(Undo, String),
@@ -190,6 +208,27 @@ pub(crate) enum Action {
ignore_ws: bool,
},
SaveConflict,
+ /// A file's history or blame in the central pane (`rev`: the commit to blame at).
+ FileView {
+ path: String,
+ rev: Option<String>,
+ tab: file_view::FileTab,
+ },
+ CloseFileView,
+ /// Open the interactive rebase editor for the commits after `onto`.
+ InteractiveRebase {
+ onto: String,
+ label: String,
+ },
+ RunRebase,
+ CloseRebase,
+ /// Remember these HTTPS credentials and run the operation that needed them again.
+ SignIn(git::Credentials),
+ /// Add `pattern` to `.gitignore`; stop tracking `path` if git tracks it.
+ Ignore {
+ pattern: String,
+ path: String,
+ },
}
pub struct RepoTab {
@@ -228,6 +267,14 @@ pub struct RepoTab {
detail: Option<CommitDetail>,
detail_error: Option<String>,
diff: Option<DiffView>,
+ file_view: Option<file_view::FileView>,
+ rebase: Option<rebase::RebaseEditor>,
+ /// HTTPS credentials typed in this session, used for every later git command of the tab.
+ credentials: Option<git::Credentials>,
+ /// The last operation started, to run again after signing in.
+ last_op: Option<PendingOp>,
+ /// The forge has been asked for avatars.
+ avatars_hinted: bool,
diff_split: bool,
diff_ignore_ws: bool,
conflict: Option<conflict::ConflictEditor>,
@@ -311,6 +358,11 @@ impl RepoTab {
detail: None,
detail_error: None,
diff: None,
+ file_view: None,
+ rebase: None,
+ credentials: None,
+ last_op: None,
+ avatars_hinted: false,
diff_split: false,
diff_ignore_ws: false,
conflict: None,
@@ -559,6 +611,7 @@ impl RepoTab {
let hash = commit.hash.clone();
self.selected = Some(row);
self.stash_view = None;
+ self.file_view = None;
if matches!(
self.diff,
Some(DiffView {
@@ -596,6 +649,7 @@ impl RepoTab {
let hash = stash.hash.clone();
self.stash_view = Some(i);
self.selected = None;
+ self.file_view = None;
self.diff = None;
self.conflict = None;
self.load_detail(hash, ctx);
@@ -660,6 +714,44 @@ impl RepoTab {
});
}
+ /// Shows `path`'s history or blame, loading what that tab needs.
+ fn open_file_view(
+ &mut self,
+ path: String,
+ rev: Option<String>,
+ tab: file_view::FileTab,
+ ctx: &egui::Context,
+ ) {
+ self.diff = None;
+ self.conflict = None;
+ let view = match self.file_view.take() {
+ Some(mut v) if v.path == path && v.rev == rev => {
+ v.tab = tab;
+ v
+ }
+ _ => file_view::FileView::new(&path, rev.clone(), tab),
+ };
+ let needs = view.needs(tab);
+ self.file_view = Some(view);
+ if !needs {
+ return;
+ }
+ let repo = self.path.clone();
+ match tab {
+ file_view::FileTab::History => spawn(&self.tx, ctx, move || {
+ let result = git::file_history(&repo, rev.as_deref(), &path);
+ Msg::FileHistory(path, result)
+ }),
+ file_view::FileTab::Blame => {
+ let dark = Tokens::get(ctx).dark();
+ spawn(&self.tx, ctx, move || {
+ let result = file_view::load_blame(&repo, rev.as_deref(), &path, dark);
+ Msg::Blame(path, rev, result)
+ })
+ }
+ }
+ }
+
fn reopen_diff(&mut self, ctx: &egui::Context) {
if let Some(view) = self.diff.take() {
self.conflict = None;
@@ -696,13 +788,21 @@ impl RepoTab {
if !quiet {
self.status = None;
}
+ self.last_op = Some(PendingOp {
+ label: label.to_owned(),
+ ops: ops.clone(),
+ refresh,
+ kind: kind.clone(),
+ quiet,
+ });
let path = self.path.clone();
let label = label.to_owned();
+ let creds = self.credentials.clone();
spawn(&self.tx, ctx, move || {
let mut result = Ok(String::new());
for op in &ops {
let args: Vec<&str> = op.iter().map(String::as_str).collect();
- result = git::run(Some(&path), &args);
+ result = git::run_with(Some(&path), &args, creds.as_ref());
if result.is_err() {
break;
}
@@ -791,6 +891,50 @@ impl RepoTab {
);
}
+ /// Once per tab, on a GitHub / GitLab repository: tells the avatar loader where its authors'
+ /// account pictures are.
+ fn hint_avatars(&mut self, ctx: &egui::Context) {
+ if self.avatars_hinted || !Settings::get(ctx).avatars {
+ return;
+ }
+ let Some(forge) = self.forge else { return };
+ let Some((host, path)) = self
+ .remotes
+ .iter()
+ .find(|r| r.name == "origin")
+ .or_else(|| self.remotes.first())
+ .and_then(|r| forge::location(&r.url))
+ else {
+ return;
+ };
+ self.avatars_hinted = true;
+ let repo = self.path.clone();
+ let mut emails: Vec<String> = self.history.iter().map(|c| c.email.clone()).collect();
+ emails.sort();
+ emails.dedup();
+ let ctx = ctx.clone();
+ std::thread::spawn(move || {
+ match forge {
+ Forge::GitHub => {
+ for (email, url) in forge::github_avatars(&repo, &host, &path) {
+ crate::avatars::hint(&email, crate::avatars::Hint::Url(url));
+ }
+ }
+ Forge::GitLab => {
+ for email in emails {
+ crate::avatars::hint(&email, crate::avatars::Hint::GitLab(host.clone()));
+ }
+ }
+ }
+ ctx.request_repaint();
+ });
+ }
+
+ /// HTTPS credentials for this tab's git commands (from the clone that made it).
+ pub fn set_credentials(&mut self, creds: git::Credentials) {
+ self.credentials = Some(creds);
+ }
+
fn default_remote(&self) -> Option<String> {
self.remotes
.iter()
@@ -1062,6 +1206,7 @@ impl RepoTab {
self.load_prs(ctx);
}
self.rebuild(ctx);
+ self.hint_avatars(ctx);
}
Err(e) => self.load_error = Some(e),
}
@@ -1099,6 +1244,42 @@ impl RepoTab {
}
}
}
+ Msg::RebaseCommits {
+ onto,
+ label,
+ result,
+ } => match result {
+ Ok(commits) if commits.is_empty() => {
+ self.status = Some((
+ format!(
+ "Nothing to rebase: {label} already contains every commit of this branch"
+ ),
+ true,
+ ));
+ }
+ Ok(commits) => {
+ self.diff = None;
+ self.conflict = None;
+ self.file_view = None;
+ self.rebase = Some(rebase::RebaseEditor::new(onto, label, commits));
+ }
+ Err(e) => self.status = Some((format!("Interactive rebase: {e}"), true)),
+ },
+ Msg::FileHistory(path, result) => {
+ if let Some(view) = &mut self.file_view
+ && view.path == path
+ {
+ view.history = Some(result);
+ }
+ }
+ Msg::Blame(path, rev, result) => {
+ if let Some(view) = &mut self.file_view
+ && view.path == path
+ && view.rev == rev
+ {
+ view.blame = Some(result);
+ }
+ }
Msg::Diff(key, result) => {
if let Some(view) = &mut self.diff
&& view.key == key
@@ -1158,6 +1339,17 @@ impl RepoTab {
}
self.record_undo(&label, kind);
}
+ Err(e) if git::is_auth_error(e) && !quiet => {
+ // Typed credentials that were refused are forgotten.
+ let refused = self.credentials.take().is_some();
+ self.status = Some((format!("{label}: sign-in needed"), true));
+ let url = self
+ .default_remote()
+ .and_then(|r| self.remotes.iter().find(|x| x.name == r))
+ .map(|r| r.url.clone())
+ .unwrap_or_default();
+ self.dialog = Some(Dialog::credentials(&url, refused));
+ }
Err(e) => {
self.focus_wip = e.contains("CONFLICT") || e.contains("could not apply");
self.status = Some((format!("{label} failed: {e}"), true));
@@ -1356,6 +1548,68 @@ impl RepoTab {
self.reopen_diff(ctx);
}
}
+ Action::FileView { path, rev, tab } => self.open_file_view(path, rev, tab, ctx),
+ Action::CloseFileView => self.file_view = None,
+ Action::InteractiveRebase { onto, label } => {
+ let path = self.path.clone();
+ spawn(&self.tx, ctx, move || {
+ let result = git::rebase_commits(&path, &onto);
+ Msg::RebaseCommits {
+ onto,
+ label,
+ result,
+ }
+ });
+ }
+ Action::RunRebase => {
+ let Some(editor) = &self.rebase else { return };
+ if editor.problem().is_some() || self.busy_op.is_some() {
+ return;
+ }
+ match editor.command() {
+ Ok(command) => {
+ let label = format!("Interactive rebase onto {}", editor.onto_label);
+ self.rebase = None;
+ self.run_undoable(
+ &label,
+ vec![command],
+ Refresh::All,
+ Undo::HeadMove { mode: "--keep" },
+ ctx,
+ );
+ }
+ Err(e) => self.status = Some((e, true)),
+ }
+ }
+ Action::CloseRebase => self.rebase = None,
+ Action::SignIn(creds) => {
+ self.credentials = Some(creds);
+ if let Some(op) = self.last_op.take() {
+ self.run_ops_ex(&op.label, op.ops, op.refresh, op.kind, op.quiet, ctx);
+ }
+ }
+ Action::Ignore { pattern, path } => match git::add_to_gitignore(&self.path, &pattern) {
+ Err(e) => self.status = Some((e, true)),
+ Ok(added) => {
+ if git::is_tracked(&self.path, &path) {
+ self.run_ops(
+ &format!("Ignore {pattern}"),
+ ops(&[&["rm", "-r", "--cached", "--quiet", "--", &path]]),
+ Refresh::Status,
+ plain,
+ ctx,
+ );
+ } else {
+ let msg = if added {
+ format!("Added {pattern} to .gitignore")
+ } else {
+ format!("{pattern} was already in .gitignore")
+ };
+ self.status = Some((msg, false));
+ self.reload_status(ctx);
+ }
+ }
+ },
Action::SaveConflict => {
if let Some(editor) = &self.conflict {
match editor.save(&self.path) {
@@ -1396,6 +1650,10 @@ impl RepoTab {
});
if esc && self.diff.is_some() {
acts.push(Action::CloseDiff);
+ } else if esc && self.rebase.is_some() {
+ acts.push(Action::CloseRebase);
+ } else if esc && self.file_view.is_some() {
+ acts.push(Action::CloseFileView);
} else if esc && self.search.open {
acts.push(Action::ToggleSearch);
}
@@ -1447,8 +1705,12 @@ impl RepoTab {
.show(ui, |ui| {
if self.conflict.is_some() {
self.conflict_view(ui, &mut acts);
+ } else if self.rebase.is_some() {
+ self.rebase_view(ui, &mut acts);
} else if self.diff.is_some() {
self.diff_view(ui, &mut acts);
+ } else if self.file_view.is_some() {
+ self.file_view(ui, &mut acts);
} else {
self.graph_view(ui, &mut acts);
}
@@ -1771,6 +2033,16 @@ pub(crate) fn merge_action(branch: &str, current: &str) -> Action {
}
}
+/// Moves the current branch forward to `branch`; fails (and says so) if they have diverged.
+pub(crate) fn fast_forward_action(branch: &str, current: &str) -> Action {
+ Action::UndoableOps {
+ label: format!("Fast-forward {current} to {branch}"),
+ ops: ops(&[&["merge", "--ff-only", branch]]),
+ refresh: Refresh::All,
+ undo: Undo::HeadMove { mode: "--keep" },
+ }
+}
+
pub(crate) fn rebase_action(onto: &str, current: &str) -> Action {
Action::UndoableOps {
label: format!("Rebase {current} onto {onto}"),
diff --git a/src/repo/rebase.rs b/src/repo/rebase.rs
new file mode 100644
index 0000000..dac53d5
--- /dev/null
+++ b/src/repo/rebase.rs
@@ -0,0 +1,413 @@
+//! Interactive rebase: the commits after a base, newest on top like the graph, each picked,
+//! reworded, squashed, fixed up or dropped, and reordered. Starting it writes git's todo list
+//! and hands it over as `sequence.editor`; rewords become an `exec git commit --amend -F`.
+
+use std::path::{Path, PathBuf};
+
+use egui::{Stroke, Ui};
+
+use super::widgets;
+use super::{Action, RepoTab};
+use crate::git::RebaseCommit;
+use crate::icons;
+use crate::theme::{self, Tokens};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Step {
+ Pick,
+ Reword,
+ Squash,
+ Fixup,
+ Drop,
+}
+
+impl Step {
+ const ALL: [Step; 5] = [
+ Step::Pick,
+ Step::Reword,
+ Step::Squash,
+ Step::Fixup,
+ Step::Drop,
+ ];
+
+ fn label(self) -> &'static str {
+ match self {
+ Step::Pick => "Pick",
+ Step::Reword => "Reword",
+ Step::Squash => "Squash",
+ Step::Fixup => "Fixup",
+ Step::Drop => "Drop",
+ }
+ }
+
+ fn explain(self) -> &'static str {
+ match self {
+ Step::Pick => "Keep the commit as it is",
+ Step::Reword => "Keep the changes, edit the message",
+ Step::Squash => "Meld into the commit below, keeping both messages",
+ Step::Fixup => "Meld into the commit below, dropping this message",
+ Step::Drop => "Remove the commit and its changes",
+ }
+ }
+}
+
+pub(crate) struct Entry {
+ pub commit: RebaseCommit,
+ pub step: Step,
+ /// The new message, for rewords.
+ pub message: String,
+}
+
+pub(crate) struct RebaseEditor {
+ /// What the commits are replayed onto (a commit or a branch).
+ pub onto: String,
+ pub onto_label: String,
+ /// Oldest first, as git lists them.
+ pub entries: Vec<Entry>,
+}
+
+impl RebaseEditor {
+ pub fn new(onto: String, onto_label: String, commits: Vec<RebaseCommit>) -> Self {
+ let entries = commits
+ .into_iter()
+ .map(|c| Entry {
+ message: c.message.clone(),
+ commit: c,
+ step: Step::Pick,
+ })
+ .collect();
+ Self {
+ onto,
+ onto_label,
+ entries,
+ }
+ }
+
+ /// Why the rebase can't start as set up, if it can't.
+ pub fn problem(&self) -> Option<String> {
+ if self.entries.iter().any(|e| e.commit.merge) {
+ return Some(
+ "These commits include merges, which this editor would flatten. Use git rebase -i --rebase-merges in the terminal."
+ .to_owned(),
+ );
+ }
+ let mut kept = self.entries.iter().filter(|e| e.step != Step::Drop);
+ match kept.next() {
+ None => {
+ return Some("Keep at least one commit (or reset the branch instead).".to_owned());
+ }
+ Some(e) if matches!(e.step, Step::Squash | Step::Fixup) => {
+ return Some(format!(
+ "{} {} has no commit below it to meld into.",
+ e.step.label(),
+ short(&e.commit.hash)
+ ));
+ }
+ _ => {}
+ }
+ if self
+ .entries
+ .iter()
+ .any(|e| e.step == Step::Reword && e.message.trim().is_empty())
+ {
+ return Some("A reworded commit needs a message.".to_owned());
+ }
+ None
+ }
+
+ fn changed(&self, e: &Entry) -> bool {
+ e.step == Step::Reword && e.message.trim_end() != e.commit.message.trim_end()
+ }
+
+ /// Writes the todo list and the new messages to a fresh temporary folder and returns the
+ /// git command that runs the rebase with them.
+ pub fn command(&self) -> Result<Vec<String>, String> {
+ let dir = std::env::temp_dir().join(format!(
+ "gitcraft-rebase-{}-{}",
+ std::process::id(),
+ crate::git::now()
+ ));
+ std::fs::create_dir_all(&dir).map_err(|e| format!("could not prepare the rebase: {e}"))?;
+ let write = |name: &str, text: &str| -> Result<PathBuf, String> {
+ let path = dir.join(name);
+ std::fs::write(&path, text)
+ .map_err(|e| format!("could not prepare the rebase: {e}"))?;
+ Ok(path)
+ };
+ let mut files = Vec::new();
+ for (i, e) in self.entries.iter().enumerate() {
+ files.push(if self.changed(e) {
+ Some(write(&format!("message-{i}.txt"), &e.message)?)
+ } else {
+ None
+ });
+ }
+ let todo = todo(&self.entries, |i| {
+ files.get(i).cloned().flatten().map(|p| sh_path(&p))
+ });
+ let todo_file = write("todo.txt", &todo)?;
+ Ok(vec![
+ "-c".to_owned(),
+ format!("sequence.editor=cp {}", sh_path(&todo_file)),
+ "rebase".to_owned(),
+ "-i".to_owned(),
+ "--autostash".to_owned(),
+ self.onto.clone(),
+ ])
+ }
+}
+
+/// git's todo list for `entries` (oldest first). `message_file(i)` is the quoted path of entry
+/// `i`'s new message when it was reworded.
+fn todo(entries: &[Entry], message_file: impl Fn(usize) -> Option<String>) -> String {
+ let mut out = String::new();
+ for (i, e) in entries.iter().enumerate() {
+ let verb = match e.step {
+ Step::Pick | Step::Reword => "pick",
+ Step::Squash => "squash",
+ Step::Fixup => "fixup",
+ Step::Drop => "drop",
+ };
+ out.push_str(&format!("{verb} {} {}\n", e.commit.hash, e.commit.summary));
+ if let Some(file) = message_file(i) {
+ out.push_str(&format!(
+ "exec git commit --amend --allow-empty --cleanup=strip -F {file}\n"
+ ));
+ }
+ }
+ out
+}
+
+/// `path` for git's shell (`sh`, also on Windows): forward slashes, single-quoted.
+fn sh_path(path: &Path) -> String {
+ let p = path.to_string_lossy().replace('\\', "/");
+ format!("'{}'", p.replace('\'', r"'\''"))
+}
+
+fn short(hash: &str) -> &str {
+ hash.get(..7).unwrap_or(hash)
+}
+
+impl RepoTab {
+ pub(super) fn rebase_view(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {
+ let t = Tokens::get(ui.ctx());
+ let idle = self.busy_op.is_none();
+ let branch = self
+ .refs
+ .current
+ .clone()
+ .unwrap_or_else(|| "HEAD".to_owned());
+ let Some(editor) = &mut self.rebase else {
+ return;
+ };
+
+ egui::Frame::new()
+ .fill(t.chrome)
+ .inner_margin(egui::Margin::symmetric(10, 6))
+ .stroke(Stroke::new(1.0, t.separator))
+ .show(ui, |ui| {
+ ui.horizontal(|ui| {
+ icons::inline(ui, "git-merge", 16.0, t.icon);
+ ui.label(
+ egui::RichText::new(format!(
+ "Interactive rebase · {branch} onto {}",
+ editor.onto_label
+ ))
+ .font(theme::medium(13.0)),
+ );
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if icons::small_button(ui, "x", "Cancel (Esc)").clicked() {
+ acts.push(Action::CloseRebase);
+ }
+ });
+ });
+ });
+
+ let problem = editor.problem();
+ egui::Panel::bottom("rebase_footer")
+ .frame(
+ egui::Frame::new()
+ .fill(t.chrome)
+ .inner_margin(egui::Margin::symmetric(12, 8))
+ .stroke(Stroke::new(1.0, t.separator)),
+ )
+ .show(ui, |ui| {
+ ui.horizontal(|ui| {
+ match &problem {
+ Some(p) => {
+ ui.colored_label(t.danger, p);
+ }
+ None => {
+ let n = editor.entries.len();
+ ui.label(
+ egui::RichText::new(format!(
+ "{n} commit{}, newest on top · Ctrl+Z undoes the rebase",
+ if n == 1 { "" } else { "s" }
+ ))
+ .color(t.text_dim),
+ );
+ }
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if widgets::primary_button(
+ ui,
+ "Start rebase",
+ idle && problem.is_none(),
+ 120.0,
+ )
+ .clicked()
+ {
+ acts.push(Action::RunRebase);
+ }
+ if ui.button("Cancel").clicked() {
+ acts.push(Action::CloseRebase);
+ }
+ });
+ });
+ });
+
+ let n = editor.entries.len();
+ let mut swap: Option<(usize, usize)> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("rebase_list")
+ .auto_shrink(false)
+ .show(ui, |ui| {
+ ui.add_space(6.0);
+ // Newest first, like the graph; `i` indexes git's oldest-first order.
+ for i in (0..n).rev() {
+ let Some(e) = editor.entries.get_mut(i) else {
+ continue;
+ };
+ ui.push_id(&e.commit.hash, |ui| {
+ ui.horizontal(|ui| {
+ ui.add_space(8.0);
+ ui.add_enabled_ui(i + 1 < n, |ui| {
+ if icons::small_button(ui, "chevron-up", "Move up (later)")
+ .clicked()
+ {
+ swap = Some((i, i + 1));
+ }
+ });
+ ui.add_enabled_ui(i > 0, |ui| {
+ if icons::small_button(ui, "chevron-down", "Move down (earlier)")
+ .clicked()
+ {
+ swap = Some((i, i - 1));
+ }
+ });
+ egui::ComboBox::from_id_salt("step")
+ .width(84.0)
+ .selected_text(e.step.label())
+ .show_ui(ui, |ui| {
+ for step in Step::ALL {
+ ui.selectable_value(&mut e.step, step, step.label())
+ .on_hover_text(step.explain());
+ }
+ });
+ let dim = e.step == Step::Drop;
+ ui.label(
+ egui::RichText::new(short(&e.commit.hash))
+ .font(theme::mono(11.5))
+ .color(t.text_faint),
+ );
+ let (rect, _) = ui
+ .allocate_exact_size(egui::vec2(20.0, 20.0), egui::Sense::hover());
+ widgets::avatar(
+ ui,
+ rect.center(),
+ 9.0,
+ &e.commit.author,
+ &e.commit.email,
+ );
+ let mut text = egui::RichText::new(&e.commit.summary).color(if dim {
+ t.text_faint
+ } else {
+ t.text
+ });
+ if dim {
+ text = text.strikethrough();
+ }
+ ui.label(text);
+ if matches!(e.step, Step::Squash | Step::Fixup) {
+ ui.label(
+ egui::RichText::new("↓ into the commit below")
+ .color(t.accent)
+ .small(),
+ );
+ }
+ });
+ if e.step == Step::Reword {
+ ui.horizontal(|ui| {
+ ui.add_space(70.0);
+ ui.add(
+ egui::TextEdit::multiline(&mut e.message)
+ .desired_rows(3)
+ .desired_width(ui.available_width() - 16.0),
+ );
+ });
+ }
+ });
+ ui.add_space(2.0);
+ ui.separator();
+ }
+ });
+ if let Some((a, b)) = swap {
+ editor.entries.swap(a, b);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(hash: &str, step: Step) -> Entry {
+ Entry {
+ commit: RebaseCommit {
+ hash: hash.to_owned(),
+ summary: format!("summary {hash}"),
+ message: format!("summary {hash}"),
+ ..RebaseCommit::default()
+ },
+ step,
+ message: format!("summary {hash}"),
+ }
+ }
+
+ #[test]
+ fn todo_lines() {
+ let entries = vec![
+ entry("a1", Step::Pick),
+ entry("b2", Step::Reword),
+ entry("c3", Step::Squash),
+ entry("d4", Step::Drop),
+ ];
+ let todo = todo(&entries, |i| (i == 1).then(|| "'/tmp/m 1.txt'".to_owned()));
+ assert_eq!(
+ todo,
+ "pick a1 summary a1\npick b2 summary b2\nexec git commit --amend --allow-empty --cleanup=strip -F '/tmp/m 1.txt'\nsquash c3 summary c3\ndrop d4 summary d4\n"
+ );
+ }
+
+ #[test]
+ fn problems() {
+ let mut ed = RebaseEditor::new("x".into(), "x".into(), Vec::new());
+ ed.entries = vec![entry("a1", Step::Drop), entry("b2", Step::Fixup)];
+ assert!(ed.problem().is_some_and(|p| p.contains("below")));
+ ed.entries[1].step = Step::Pick;
+ assert_eq!(ed.problem(), None);
+ ed.entries[1].step = Step::Drop;
+ assert!(ed.problem().is_some());
+ ed.entries[1].step = Step::Reword;
+ ed.entries[1].message = " ".into();
+ assert!(ed.problem().is_some());
+ }
+
+ #[test]
+ fn shell_paths() {
+ assert_eq!(
+ sh_path(Path::new(r"C:\Temp\it's\todo.txt")),
+ r"'C:/Temp/it'\''s/todo.txt'"
+ );
+ }
+}
diff --git a/src/repo/sidebar.rs b/src/repo/sidebar.rs
index 61ca465..82ab8a0 100644
--- a/src/repo/sidebar.rs
+++ b/src/repo/sidebar.rs
@@ -4,7 +4,9 @@
use egui::{Align2, Rect, Response, Sense, Ui, pos2, vec2};
use super::widgets::{self, ROW_H};
-use super::{Action, Dialog, Refresh, RepoTab, Undo, merge_action, ops, rebase_action};
+use super::{
+ Action, Dialog, Refresh, RepoTab, Undo, fast_forward_action, merge_action, ops, rebase_action,
+};
use crate::git::{self, Branch};
use crate::icons;
use crate::theme::{self, Tokens};
@@ -222,6 +224,15 @@ impl RepoTab {
&& !b.is_head
{
ui.separator();
+ if ui
+ .add_enabled(
+ idle,
+ egui::Button::new(format!("Fast-forward {current} to {}", b.name)),
+ )
+ .clicked()
+ {
+ acts.push(fast_forward_action(&b.name, current));
+ }
if ui
.add_enabled(
idle,
@@ -240,6 +251,18 @@ impl RepoTab {
{
acts.push(rebase_action(&b.name, current));
}
+ if ui
+ .add_enabled(
+ idle,
+ egui::Button::new(format!("Interactive rebase {current} onto {}…", b.name)),
+ )
+ .clicked()
+ {
+ acts.push(Action::InteractiveRebase {
+ onto: b.name.clone(),
+ label: b.name.clone(),
+ });
+ }
}
ui.separator();
if let Some(remote) = self.default_remote()
@@ -472,6 +495,15 @@ impl RepoTab {
acts.push(Action::CheckoutRemote(b.name.clone()));
}
if let Some(current) = current.as_deref() {
+ if ui
+ .add_enabled(
+ idle,
+ egui::Button::new(format!("Fast-forward {current} to it")),
+ )
+ .clicked()
+ {
+ acts.push(fast_forward_action(&b.name, current));
+ }
if ui
.add_enabled(idle, egui::Button::new(format!("Merge into {current}")))
.clicked()
diff --git a/src/repo/widgets.rs b/src/repo/widgets.rs
index 1190a20..b8fc4b4 100644
--- a/src/repo/widgets.rs
+++ b/src/repo/widgets.rs
@@ -491,23 +491,77 @@ pub fn terminal_tabs(
}
/// Right-click menu for a file of the working tree or a commit: open it, its folder, copy path.
-pub fn file_menu(resp: &Response, path: &str, acts: &mut Vec<super::Action>) {
+/// Right-click menu of a file. `rev`: the commit it is shown in (history and blame start there);
+/// `ignorable`: a working-tree file that can be added to `.gitignore`.
+pub fn file_menu(
+ resp: &Response,
+ path: &str,
+ rev: Option<&str>,
+ ignorable: bool,
+ acts: &mut Vec<super::Action>,
+) {
+ use super::Action;
+ use super::file_view::FileTab;
resp.context_menu(|ui| {
let rel = std::path::PathBuf::from(path);
if ui.button("Open file").clicked() {
- acts.push(super::Action::OpenPath(rel.clone()));
+ acts.push(Action::OpenPath(rel.clone()));
}
if ui.button("Open in editor").clicked() {
- acts.push(super::Action::OpenInEditor(rel.clone()));
+ acts.push(Action::OpenInEditor(rel.clone()));
}
if ui.button(super::reveal_label()).clicked() {
- acts.push(super::Action::OpenPath(
+ acts.push(Action::OpenPath(
rel.parent().map(|p| p.to_path_buf()).unwrap_or_default(),
));
}
ui.separator();
+ if ui.button("File history").clicked() {
+ acts.push(Action::FileView {
+ path: path.to_owned(),
+ rev: rev.map(str::to_owned),
+ tab: FileTab::History,
+ });
+ }
+ if ui.button("Blame").clicked() {
+ acts.push(Action::FileView {
+ path: path.to_owned(),
+ rev: rev.map(str::to_owned),
+ tab: FileTab::Blame,
+ });
+ }
+ if ignorable {
+ ui.menu_button("Ignore", |ui| {
+ for (label, pattern, untrack) in ignore_patterns(path) {
+ if ui.button(label).clicked() {
+ acts.push(Action::Ignore {
+ pattern,
+ path: untrack,
+ });
+ }
+ }
+ });
+ }
+ ui.separator();
if ui.button("Copy path").clicked() {
ui.ctx().copy_text(path.to_owned());
}
});
}
+
+/// The ways to ignore `path`: (menu label, `.gitignore` line, what to stop tracking).
+fn ignore_patterns(path: &str) -> Vec<(String, String, String)> {
+ let p = std::path::Path::new(path);
+ let mut out = vec![("This file".to_owned(), format!("/{path}"), path.to_owned())];
+ if let Some(ext) = p.extension().and_then(|e| e.to_str()) {
+ out.push((
+ format!("All .{ext} files"),
+ format!("*.{ext}"),
+ path.to_owned(),
+ ));
+ }
+ if let Some(dir) = path.rsplit_once('/').map(|(d, _)| d) {
+ out.push((format!("Folder {dir}/"), format!("/{dir}/"), dir.to_owned()));
+ }
+ out
+}
diff --git a/src/settings.rs b/src/settings.rs
index 98ea6d7..7cb1179 100644
--- a/src/settings.rs
+++ b/src/settings.rs
@@ -30,12 +30,14 @@ pub struct Settings {
pub show_hash: bool,
/// Background fetch interval in minutes; 0 turns it off.
pub auto_fetch_minutes: u32,
- /// Load avatars from Gravatar / GitHub (sends a hash of each author's email).
+ /// Load avatars: GitHub / GitLab accounts on repositories hosted there, Gravatar otherwise.
pub avatars: bool,
/// Command that opens a folder or file in the user's editor.
pub editor: String,
/// Desktop notifications when a long operation ends while the window is in the background.
pub notifications: bool,
+ /// Ask GitHub once a day whether a newer release exists.
+ pub check_updates: bool,
pub profiles: Vec<Profile>,
}
@@ -53,6 +55,7 @@ impl Default for Settings {
avatars: true,
editor: "code".to_owned(),
notifications: true,
+ check_updates: true,
profiles: Vec::new(),
}
}
@@ -103,12 +106,15 @@ impl Settings {
});
ui.end_row();
ui.label("Avatars");
- ui.checkbox(&mut self.avatars, "Load from Gravatar / GitHub")
- .on_hover_text("Sends an MD5 hash of each author's email to gravatar.com, or asks GitHub for noreply addresses. Cached on disk.");
+ ui.checkbox(&mut self.avatars, "Load from GitHub, GitLab or Gravatar")
+ .on_hover_text("On a GitHub repository, its commit list says which account each author is; on GitLab, the host is asked by email. Other authors: an MD5 hash of the email goes to gravatar.com. Cached on disk.");
ui.end_row();
ui.label("Notifications");
ui.checkbox(&mut self.notifications, "When a long operation ends in the background");
ui.end_row();
+ ui.label("Updates");
+ ui.checkbox(&mut self.check_updates, "Check GitHub for a new version once a day");
+ ui.end_row();
});
section(ui, "GIT");
diff --git a/src/update.rs b/src/update.rs
new file mode 100644
index 0000000..4c0c4bc
--- /dev/null
+++ b/src/update.rs
@@ -0,0 +1,98 @@
+//! Asks GitHub whether a newer gitcraft release exists (at most once a day, can be turned off).
+
+use std::time::Duration;
+
+/// This build's version.
+pub const CURRENT: &str = env!("CARGO_PKG_VERSION");
+/// Redirects to the latest release's page, `…/releases/tag/vX.Y.Z`. The web page rather than
+/// the REST API: the API allows 60 anonymous requests an hour per IP, which shared addresses
+/// (VPNs, offices) use up.
+const LATEST: &str = "https://github.com/Vancete/gitcraft/releases/latest";
+/// Seconds between two checks.
+pub const INTERVAL: i64 = 24 * 3600;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Release {
+ /// Without the leading `v`.
+ pub version: String,
+ pub url: String,
+}
+
+/// The latest published release.
+pub fn latest() -> Result<Release, String> {
+ let resp = ureq::AgentBuilder::new()
+ .timeout(Duration::from_secs(10))
+ .user_agent("gitcraft")
+ .build()
+ .head(LATEST)
+ .call()
+ .map_err(|e| e.to_string())?;
+ release_from_url(resp.get_url()).ok_or_else(|| "no release published yet".to_owned())
+}
+
+fn release_from_url(url: &str) -> Option<Release> {
+ let tag = url
+ .split_once("/releases/tag/")?
+ .1
+ .split(['?', '#'])
+ .next()?;
+ (!tag.is_empty()).then(|| Release {
+ version: tag.trim_start_matches('v').to_owned(),
+ url: url.to_owned(),
+ })
+}
+
+/// Whether version `a` comes after `b` (`1.10.0` > `1.9.2`; pre-release suffixes are ignored).
+pub fn newer(a: &str, b: &str) -> bool {
+ let parts = |v: &str| -> Vec<u64> {
+ v.trim_start_matches('v')
+ .split(['-', '+'])
+ .next()
+ .unwrap_or_default()
+ .split('.')
+ .map(|n| n.parse().unwrap_or(0))
+ .collect()
+ };
+ let (a, b) = (parts(a), parts(b));
+ for i in 0..a.len().max(b.len()) {
+ let (x, y) = (
+ a.get(i).copied().unwrap_or(0),
+ b.get(i).copied().unwrap_or(0),
+ );
+ if x != y {
+ return x > y;
+ }
+ }
+ false
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn release_page_urls() {
+ assert_eq!(
+ release_from_url("https://github.com/Vancete/gitcraft/releases/tag/v0.2.0"),
+ Some(Release {
+ version: "0.2.0".into(),
+ url: "https://github.com/Vancete/gitcraft/releases/tag/v0.2.0".into()
+ })
+ );
+ // No release yet: the redirect lands on the list.
+ assert_eq!(
+ release_from_url("https://github.com/Vancete/gitcraft/releases"),
+ None
+ );
+ }
+
+ #[test]
+ fn version_order() {
+ assert!(newer("0.2.0", "0.1.0"));
+ assert!(newer("v1.10.0", "1.9.9"));
+ assert!(newer("1.0", "0.9.9"));
+ assert!(!newer("0.1.0", "0.1.0"));
+ assert!(!newer("0.1.0", "0.1.1"));
+ assert!(!newer("1.0.0-rc1", "1.0.0"));
+ }
+}