Skip to content

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

Rust

feat: gitcraft 0.3.0 - partial staging, compare, code search, macOS builds, manual

Iváne597ea560e0a
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 697ea59..91f3c93 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,4 +1,4 @@
-# Builds gitcraft for Windows and Linux and publishes a GitHub release when a `v*` tag is pushed.
+# Builds gitcraft for Windows, Linux and macOS and publishes a GitHub release when a `v*` tag is pushed.
# Run it by hand (Actions › Release › Run workflow) to only build and download the artifacts.
name: Release
@@ -21,6 +21,9 @@ jobs:
# The oldest supported runner, so the binary runs on older glibc too.
- os: ubuntu-22.04
name: linux-x86_64
+ # Builds for Apple silicon and Intel, joined into one universal app.
+ - os: macos-latest
+ name: macos-universal
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
@@ -38,8 +41,34 @@ jobs:
run: cargo test --locked
- name: Build
+ if: runner.os != 'macOS'
run: cargo build --release --locked
+ - name: Build (macOS)
+ if: runner.os == 'macOS'
+ env:
+ MACOSX_DEPLOYMENT_TARGET: "11.0"
+ run: |
+ rustup target add aarch64-apple-darwin x86_64-apple-darwin
+ cargo build --release --locked --target aarch64-apple-darwin
+ cargo build --release --locked --target x86_64-apple-darwin
+
+ - name: App, dmg and zip (macOS)
+ if: runner.os == 'macOS'
+ run: |
+ name="gitcraft-${{ github.ref_name }}-${{ matrix.name }}"
+ version="$(grep -m 1 '^version = ' Cargo.toml | cut -d '"' -f 2)"
+ sh packaging/macos/build-app.sh "$version" "$name"
+ # Both architectures, signed, and the disk image is sound.
+ mkdir check
+ ditto -x -k "$name.zip" check
+ lipo -archs check/gitcraft.app/Contents/MacOS/gitcraft
+ lipo -archs check/gitcraft.app/Contents/MacOS/gitcraft | grep -q x86_64
+ lipo -archs check/gitcraft.app/Contents/MacOS/gitcraft | grep -q arm64
+ codesign --verify --strict check/gitcraft.app
+ plutil -lint check/gitcraft.app/Contents/Info.plist
+ hdiutil verify "$name.dmg"
+
- name: Package (Windows)
if: runner.os == 'Windows'
shell: pwsh
@@ -106,6 +135,7 @@ jobs:
name: gitcraft-${{ matrix.name }}
path: |
gitcraft-*.zip
+ gitcraft-*.dmg
gitcraft-*.tar.gz
gitcraft-*-setup.exe
gitcraft-*.AppImage
diff --git a/Cargo.lock b/Cargo.lock
index 4507100..f397d02 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1447,7 +1447,7 @@ dependencies = [
[[package]]
name = "gitcraft"
-version = "0.2.2"
+version = "0.3.0"
dependencies = [
"eframe",
"egui",
diff --git a/Cargo.toml b/Cargo.toml
index d752242..3b6839f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "gitcraft"
-version = "0.2.2"
+version = "0.3.0"
edition = "2024"
rust-version = "1.95"
license = "MIT OR Apache-2.0"
diff --git a/README.md b/README.md
index b5c4872..a730b14 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,7 @@
# gitcraft
-A small, personal visual git client: a simplified take on the usual graph-based git GUIs.
-Rust + [egui/eframe](https://github.com/emilk/egui), the same stack and look as WordCraft and
-PhotoCraft, so it builds on Windows, Linux and macOS. It drives the installed `git` command line,
+A visual git client: a simplified take yet powerful on the usual graph-based git GUIs.
+Rust + [egui/eframe](https://github.com/emilk/egui), the same technical stack of the ArtCraft suite, so it builds on Windows, Linux and macOS and stays light and fast. It drives the installed `git` command line,
so your config, credentials and hooks apply as usual.
![gitcraft: branches, remotes and worktrees on the left, the graph with branch pills and relative dates, uncommitted changes on the right and the integrated terminal below](docs/screenshot.png)
@@ -10,6 +9,7 @@ so your config, credentials and hooks apply as usual.
## Features
**Repositories and tabs**
+
- Start page: checks that `git` is installed; open, create (`git init`) or clone a repository;
recent repositories.
- Browser-like tabs, one per repository (Ctrl+T, Ctrl+W, middle-click). Open tabs, recents,
@@ -17,6 +17,7 @@ so your config, credentials and hooks apply as usual.
- Changes made elsewhere (editor, terminal) show up by themselves: the folder is watched.
**Graph**
+
- Every branch, coloured lanes, ↑/↓ to move. History loads 1500 commits at a time as you scroll.
- Branch and tag pills in their own column left of the graph, on each branch's tip only, joined
to their commit: white text, a laptop icon when the branch is local, a cloud when a remote has
@@ -26,18 +27,26 @@ so your config, credentials and hooks apply as usual.
- The checked-out branch's pill is solid, the others a darker shade. 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.
+- Each commit's summary, followed by the rest of its message, faded and cut to fit.
+- An _Uncommitted changes_ row on top while the working tree is dirty.
+- Search (Ctrl+F) through messages, authors and hashes of all history, or switch to _Code_ to
+ find the commits that added or removed a piece of text in a file (`git log -S`); Enter /
+ Shift+Enter jump between results, loading older history when needed.
- 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.
+- Compare: Ctrl+click a second commit (or _Compare with…_ in the commit menu, the changes row
+ standing for the working tree) to list the files that differ between the two and open each
+ diff. On a branch, _Changes x adds to main_ shows only what it changed since the two diverged,
+ as a pull request shows it, and _Compare main with x_ every difference; a checkbox switches
+ between the two. The right pane says how many commits each side has that the other hasn't.
- 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
+ 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), fast-forward,
merge into / (interactively) rebase onto the current branch, push, create a pull request,
rename, delete…
@@ -51,30 +60,36 @@ so your config, credentials and hooks apply as usual.
- Tags: create (light or annotated, optionally pushed), push, delete locally or on the remote.
**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, show it in
+ _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*
+- Part of a file: _Stage hunk_, _Discard hunk_ and _Unstage hunk_ on each hunk of its diff, or
+ click the changed lines you want (Shift+click for a range) and stage, unstage or discard only
+ those. Discarding can be undone with Ctrl+Z.
+- 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.
- Undo / redo (Ctrl+Z / Ctrl+Y) of commits, amends, merges, rebases, pulls, resets,
cherry-picks, reverts, checkouts, branch create / rename / delete, tags and stashes.
**Diffs and conflicts** (centre)
+
- Unified or side by side, syntax colours, the changed part of each line marked, whitespace
changes optional, images shown before / after. Esc closes.
- Code takes the colours of the theme VS Code (or Insiders, VSCodium) is using, read from its
settings and extensions, when it is dark or light like gitcraft's; a setting turns it off.
-- Conflicts open in a three-pane editor: each conflict's two sides with *Ours*, *Theirs* and
- *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).
+- Conflicts open in a three-pane editor: each conflict's two sides with _Ours_, _Theirs_ and
+ _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).
@@ -85,6 +100,7 @@ so your config, credentials and hooks apply as usual.
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.
+- Manual (F1, or the book in the title bar): what each part does and every keyboard shortcut.
- 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.
@@ -98,24 +114,29 @@ so your config, credentials and hooks apply as usual.
## Download
-Ready-made builds for Windows and Linux (x86-64) are on the
+Ready-made builds for Windows, Linux (x86-64) and macOS (Apple silicon and Intel) are on the
[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.
+ 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-….deb` (Debian, Ubuntu, Mint…) and `gitcraft-….rpm` (Fedora, openSUSE…)
install it with its applications menu entry, from the software centre or with
`sudo apt install ./gitcraft-….deb` / `sudo dnf install ./gitcraft-….rpm`.
`gitcraft-….AppImage` runs on any distribution: make it executable (`chmod +x`) and run it;
- *Add gitcraft to the applications menu* on its start page (or in Settings) adds a menu entry,
+ _Add gitcraft to the applications menu_ on its start page (or in Settings) adds a menu entry,
which follows the AppImage when you replace it with a newer one. The `.tar.gz` holds the bare
binary and a `.desktop` file.
+- **macOS** (11 or later): open `gitcraft-…-macos-universal.dmg` and drag gitcraft to
+ Applications; the `.zip` holds the same app. It isn't notarized by Apple, so the first time
+ macOS refuses to open it: go to _System Settings › Privacy & Security_ and click _Open
+ Anyway_, or run `xattr -dr com.apple.quarantine /Applications/gitcraft.app`. git comes with
+ the Xcode command line tools (`xcode-select --install`) or Homebrew.
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, `[package.metadata.deb]` / `[package.metadata.generate-rpm]` in `Cargo.toml` for the
-packages).
+packages, `packaging/macos/build-app.sh` for the universal app, its `.dmg` and `.zip`).
## Build and run
@@ -137,37 +158,40 @@ GitLab CLI (`glab`), logged in.
cargo run --example ui_shot -- path/to/repo /tmp/shot click:500,266 shot key:Escape shot
```
-Steps: `click:x,y`, `dclick:x,y`, `rclick:x,y`, `drag:x1,y1,x2,y2`, `hover:x,y`, `leave`,
+Steps: `click:x,y`, `dclick:x,y`, `rclick:x,y`, `cclick:x,y` (with Ctrl / Cmd), `sclick:x,y`
+(with Shift), `drag:x1,y1,x2,y2`, `hover:x,y`, `wheel:x,y,dy` (negative scrolls down), `leave`,
`key:Name`, `ckey:Name` (with Ctrl / Cmd), `type:text`, `wait:ms`, `shot`. The README screenshot
was made this way, on a demo repository.
## Layout
-| File | Job |
-|---|---|
-| `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 GitHub, GitLab or Gravatar, cached on disk |
-| `src/update.rs` | new-release check |
-| `src/desktop_entry.rs` | applications menu entry for the AppImage |
-| `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 |
-| `src/terminal.rs` | integrated terminal: pty, VT parsing (`vt100`), painting, keys, selection |
-| `src/repo/mod.rs` | one repository tab: state, background git work, undo / redo, toolbar |
-| `src/repo/sidebar.rs` | branches, remotes, worktrees, stashes, pull requests, tags |
-| `src/repo/graph_view.rs` | commit graph, pills, search bar, commit menu |
-| `src/repo/detail.rs` | commit / stash detail, changes and commit box |
-| `src/repo/diff.rs` | diff loading, pairing and the diff view (unified, split, images) |
-| `src/repo/highlight.rs` | syntax colours (syntect) |
-| `src/vscode_theme.rs` | VS Code's current colour theme as a syntect theme |
-| `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 |
+| File | Job |
+| ------------------------ | ---------------------------------------------------------------------------------- |
+| `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 GitHub, GitLab or Gravatar, cached on disk |
+| `src/update.rs` | new-release check |
+| `src/desktop_entry.rs` | applications menu entry for the AppImage |
+| `src/shell_path.rs` | on macOS, the login shell's PATH for the commands gitcraft starts |
+| `src/settings.rs` | user settings and their form |
+| `src/manual.rs` | the manual (F1): features and keyboard shortcuts |
+| `src/theme.rs` | colour tokens, fonts, egui style (PhotoCraft's Pro themes) |
+| `src/icons.rs` | embedded Lucide SVG icons, tinted |
+| `src/terminal.rs` | integrated terminal: pty, VT parsing (`vt100`), painting, keys, selection |
+| `src/repo/mod.rs` | one repository tab: state, background git work, undo / redo, toolbar |
+| `src/repo/sidebar.rs` | branches, remotes, worktrees, stashes, pull requests, tags |
+| `src/repo/graph_view.rs` | commit graph, pills, search bar, commit menu |
+| `src/repo/detail.rs` | commit / stash detail, changes and commit box |
+| `src/repo/diff.rs` | diff loading, pairing and the diff view (unified, split, images) |
+| `src/repo/highlight.rs` | syntax colours (syntect) |
+| `src/vscode_theme.rs` | VS Code's current colour theme as a syntect theme |
+| `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 |
Assets and their licences: [ATTRIBUTION.md](ATTRIBUTION.md).
diff --git a/assets/icons/book-open.svg b/assets/icons/book-open.svg
new file mode 100644
index 0000000..6906352
--- /dev/null
+++ b/assets/icons/book-open.svg
@@ -0,0 +1,14 @@
+<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="M12 7v14" />
+ <path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
+</svg>
diff --git a/examples/ui_shot.rs b/examples/ui_shot.rs
index b6d6d21..2afb889 100644
--- a/examples/ui_shot.rs
+++ b/examples/ui_shot.rs
@@ -33,23 +33,33 @@ fn main() {
for step in steps {
let (cmd, arg) = step.split_once(':').unwrap_or((step.as_str(), ""));
match cmd {
- "click" | "rclick" => {
+ "click" | "rclick" | "cclick" | "sclick" => {
let pos = point(arg);
- let button = if cmd == "click" {
- PointerButton::Primary
- } else {
+ let button = if cmd == "rclick" {
PointerButton::Secondary
+ } else {
+ PointerButton::Primary
+ };
+ let modifiers = match cmd {
+ "cclick" => Modifiers::COMMAND,
+ "sclick" => Modifiers::SHIFT,
+ _ => Modifiers::NONE,
};
harness.event(Event::PointerMoved(pos));
harness.step();
+ // The modifier held down around the click, as the keyboard reports it.
+ harness.event(Event::ModifiersChanged(modifiers));
+ harness.step();
for pressed in [true, false] {
harness.event(Event::PointerButton {
pos,
button,
pressed,
- modifiers: Modifiers::NONE,
+ modifiers,
});
}
+ harness.step();
+ harness.event(Event::ModifiersChanged(Modifiers::NONE));
settle(&mut harness, 400);
}
"dclick" => {
@@ -74,6 +84,29 @@ fn main() {
harness.remove_cursor();
settle(&mut harness, 200);
}
+ // `wheel:x,y,dy`: the mouse wheel over a point; a negative `dy` scrolls down.
+ "wheel" => {
+ let n: Vec<f32> = arg
+ .split(',')
+ .map(|v| v.trim().parse().unwrap_or(0.0))
+ .collect();
+ let (pos, dy) = (
+ Pos2::new(
+ n.first().copied().unwrap_or(0.0),
+ n.get(1).copied().unwrap_or(0.0),
+ ),
+ n.get(2).copied().unwrap_or(0.0),
+ );
+ harness.event(Event::PointerMoved(pos));
+ harness.step();
+ harness.event(Event::MouseWheel {
+ unit: egui::MouseWheelUnit::Point,
+ delta: egui::vec2(0.0, dy),
+ modifiers: Modifiers::NONE,
+ phase: egui::TouchPhase::Move,
+ });
+ settle(&mut harness, 600);
+ }
"drag" => {
let n: Vec<f32> = arg
.split(',')
diff --git a/packaging/macos/Info.plist b/packaging/macos/Info.plist
new file mode 100644
index 0000000..5b0ae35
--- /dev/null
+++ b/packaging/macos/Info.plist
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleName</key>
+ <string>gitcraft</string>
+ <key>CFBundleDisplayName</key>
+ <string>gitcraft</string>
+ <key>CFBundleIdentifier</key>
+ <string>io.github.vancete.gitcraft</string>
+ <key>CFBundleExecutable</key>
+ <string>gitcraft</string>
+ <key>CFBundleIconFile</key>
+ <string>gitcraft</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>@VERSION@</string>
+ <key>CFBundleVersion</key>
+ <string>@VERSION@</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>LSApplicationCategoryType</key>
+ <string>public.app-category.developer-tools</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>11.0</string>
+ <key>NSHighResolutionCapable</key>
+ <true/>
+ <key>NSHumanReadableCopyright</key>
+ <string>MIT OR Apache-2.0</string>
+</dict>
+</plist>
diff --git a/packaging/macos/build-app.sh b/packaging/macos/build-app.sh
new file mode 100644
index 0000000..afad437
--- /dev/null
+++ b/packaging/macos/build-app.sh
@@ -0,0 +1,44 @@
+#!/bin/sh
+# Packs the Apple silicon and Intel builds into one universal gitcraft.app, then a .dmg (drag
+# to Applications) and a .zip of it.
+# Usage: packaging/macos/build-app.sh <version> <output name without extension>
+# Needs both `cargo build --release --target aarch64-apple-darwin` and
+# `--target x86_64-apple-darwin` done first. macOS only (lipo, iconutil, codesign, hdiutil).
+set -eu
+
+version="$1"
+out="$2"
+work="$(mktemp -d)"
+app="$work/gitcraft.app"
+mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"
+
+lipo -create -output "$app/Contents/MacOS/gitcraft" \
+ target/aarch64-apple-darwin/release/gitcraft \
+ target/x86_64-apple-darwin/release/gitcraft
+strip -x "$app/Contents/MacOS/gitcraft"
+sed "s/@VERSION@/$version/g" packaging/macos/Info.plist > "$app/Contents/Info.plist"
+printf 'APPL????' > "$app/Contents/PkgInfo"
+
+# The icon, from the 256 px PNG (the larger sizes are left to macOS to scale).
+iconset="$work/gitcraft.iconset"
+mkdir "$iconset"
+for entry in 16x16:16 16x16@2x:32 32x32:32 32x32@2x:64 128x128:128 128x128@2x:256 256x256:256; do
+ name="${entry%%:*}"
+ px="${entry##*:}"
+ sips -z "$px" "$px" assets/app-icon/gitcraft-256.png --out "$iconset/icon_$name.png" >/dev/null
+done
+iconutil -c icns -o "$app/Contents/Resources/gitcraft.icns" "$iconset"
+
+cp README.md ATTRIBUTION.md LICENSE-MIT LICENSE-APACHE "$app/Contents/Resources/"
+
+# Not notarized: an ad-hoc signature, which Apple silicon needs to run the program at all.
+codesign --force --deep --sign - "$app"
+codesign --verify --strict "$app"
+
+ditto -c -k --keepParent "$app" "$out.zip"
+
+dmg="$work/dmg"
+mkdir "$dmg"
+cp -R "$app" "$dmg/"
+ln -s /Applications "$dmg/Applications"
+hdiutil create -volname gitcraft -srcfolder "$dmg" -ov -format UDZO "$out.dmg"
diff --git a/src/app.rs b/src/app.rs
index faeb80d..e267ced 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -79,6 +79,7 @@ pub struct App {
skipped_version: String,
settings: Settings,
settings_open: bool,
+ manual_open: bool,
palette: Option<Palette>,
toasts: Vec<Toast>,
}
@@ -103,6 +104,7 @@ enum AppCommand {
Create,
Clone,
Settings,
+ Manual,
Theme(ThemeKind),
}
@@ -135,6 +137,7 @@ impl App {
clone_parent: saved.clone_parent,
settings: saved.settings.clone(),
settings_open: false,
+ manual_open: false,
palette: None,
toasts: Vec::new(),
error: None,
@@ -395,8 +398,9 @@ impl App {
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- ui.add_space(6.0);
- if icons::small_button(ui, "settings", "Settings").clicked() {
+ ui.add_space(4.0);
+ ui.spacing_mut().item_spacing.x = 6.0;
+ if icons::bar_button(ui, "settings", "Settings").clicked() {
self.settings_open = true;
}
if let Some(release) = self.update.clone() {
@@ -429,10 +433,10 @@ impl App {
}
});
}
- if icons::small_button(ui, "command", "Command palette (Ctrl+P)").clicked() {
+ if icons::bar_button(ui, "command", "Command palette (Ctrl+P)").clicked() {
self.open_palette();
}
- let resp = icons::small_button(ui, "palette", "Theme");
+ let resp = icons::bar_button(ui, "palette", "Theme");
egui::Popup::menu(&resp)
.style(crate::theme::menu_style)
.show(|ui| {
@@ -447,6 +451,11 @@ impl App {
}
}
});
+ if icons::bar_button(ui, "book-open", "Manual and keyboard shortcuts (F1)")
+ .clicked()
+ {
+ self.manual_open = true;
+ }
});
});
if let Some(i) = select {
@@ -815,16 +824,21 @@ impl eframe::App for App {
let modal_open = self.clone_form.is_some()
|| self.palette.is_some()
|| self.settings_open
+ || self.manual_open
|| ctx.egui_wants_keyboard_input();
- let (new_tab, close, refresh, focused, palette) = ctx.input(|i| {
+ let (new_tab, close, refresh, focused, palette, manual) = ctx.input(|i| {
(
i.modifiers.command && i.key_pressed(Key::T),
i.modifiers.command && i.key_pressed(Key::W),
i.key_pressed(Key::F5),
i.focused,
i.modifiers.command && i.key_pressed(Key::P),
+ i.key_pressed(Key::F1),
)
});
+ if manual && self.clone_form.is_none() && !self.settings_open && self.palette.is_none() {
+ self.manual_open = !self.manual_open;
+ }
if palette && self.clone_form.is_none() && !self.settings_open {
if self.palette.is_some() {
self.palette = None;
@@ -872,8 +886,10 @@ impl eframe::App for App {
let active = self.active;
match self.tabs.get_mut(active) {
Some(Tab::Repo(repo)) => {
- repo.keys_blocked =
- self.palette.is_some() || self.settings_open || self.clone_form.is_some();
+ repo.keys_blocked = self.palette.is_some()
+ || self.settings_open
+ || self.manual_open
+ || self.clone_form.is_some();
repo.ui(ui);
// A worktree asked to be opened in its own tab.
if let Some(path) = repo.open_request.take() {
@@ -889,6 +905,7 @@ impl eframe::App for App {
self.clone_dialog(&ctx);
self.palette_ui(&ctx);
self.settings_ui(&ctx);
+ self.manual_ui(&ctx);
// Long operations that ended: a toast, and a desktop notification when away.
for tab in &mut self.tabs {
@@ -1107,6 +1124,11 @@ impl App {
"app".to_owned(),
Entry::App(AppCommand::Settings),
),
+ (
+ "Manual and keyboard shortcuts".to_owned(),
+ "F1".to_owned(),
+ Entry::App(AppCommand::Manual),
+ ),
];
for kind in ThemeKind::ALL {
list.push((
@@ -1130,6 +1152,7 @@ impl App {
Entry::App(AppCommand::Create) => self.pick_new(ctx),
Entry::App(AppCommand::Clone) => self.start_clone(),
Entry::App(AppCommand::Settings) => self.settings_open = true,
+ Entry::App(AppCommand::Manual) => self.manual_open = true,
Entry::App(AppCommand::Theme(kind)) => self.set_theme(ctx, kind),
Entry::Repo(i) => {
if let Some(Tab::Repo(repo)) = self.tabs.get_mut(self.active)
@@ -1298,6 +1321,45 @@ impl App {
}
}
+ fn manual_ui(&mut self, ctx: &egui::Context) {
+ if !self.manual_open {
+ return;
+ }
+ let t = Tokens::get(ctx);
+ let frame = egui::Frame::new()
+ .fill(t.card)
+ .stroke(Stroke::new(1.0, t.field_border))
+ .corner_radius(t.radius_lg)
+ .inner_margin(egui::Margin::same(18))
+ .shadow(ctx.global_style().visuals.window_shadow);
+ let mut close = false;
+ let resp = egui::Modal::new(egui::Id::new("manual"))
+ .frame(frame)
+ .backdrop_color(egui::Color32::from_black_alpha(110))
+ .show(ctx, |ui| {
+ ui.set_width(640.0);
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Manual").font(theme::semibold(16.0)));
+ ui.label(
+ RichText::new(format!("gitcraft {}", update::CURRENT)).color(t.text_faint),
+ );
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if icons::small_button(ui, "x", "Close (Esc)").clicked() {
+ close = true;
+ }
+ });
+ });
+ let max = (ctx.content_rect().height() - 140.0).max(240.0);
+ egui::ScrollArea::vertical()
+ .max_height(max)
+ .min_scrolled_height(max)
+ .show(ui, crate::manual::ui);
+ });
+ if close || resp.should_close() {
+ self.manual_open = false;
+ }
+ }
+
fn toasts_ui(&mut self, ctx: &egui::Context) {
let now = std::time::Instant::now();
self.toasts.retain(|t| t.until > now);
diff --git a/src/avatars.rs b/src/avatars.rs
index 1c87180..b3472bf 100644
--- a/src/avatars.rs
+++ b/src/avatars.rs
@@ -17,7 +17,8 @@ const RETRY_MISSING: Duration = Duration::from_secs(7 * 24 * 3600);
#[derive(Clone)]
enum State {
Pending,
- Ready(Arc<[u8]>),
+ /// The picture, and its cache key (which says where it came from).
+ Ready(Arc<[u8]>, String),
Missing,
}
@@ -159,7 +160,7 @@ fn fetch(agent: &ureq::Agent, email: &str, hint: Option<&Hint>) -> State {
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()));
+ return State::Ready(Arc::from(bytes.into_boxed_slice()), k);
}
let missing = dir.join(format!("{k}.none"));
let recent = std::fs::metadata(&missing)
@@ -190,7 +191,7 @@ fn fetch(agent: &ureq::Agent, email: &str, hint: Option<&Hint>) -> State {
let _ = std::fs::create_dir_all(dir);
let _ = std::fs::write(dir.join(format!("{k}.img")), &bytes);
}
- State::Ready(Arc::from(bytes.into_boxed_slice()))
+ State::Ready(Arc::from(bytes.into_boxed_slice()), k)
}
_ => {
if let Some(dir) = &dir {
@@ -221,10 +222,11 @@ pub fn paint(ui: &egui::Ui, rect: Rect, email: &str) -> bool {
}
}
};
- let State::Ready(bytes) = state else {
+ let State::Ready(bytes, source) = state else {
return false;
};
- let uri = format!("bytes://avatar/{}.png", key(&k));
+ // egui keeps an image per URI: one per source, so a forge's picture replaces Gravatar's.
+ let uri = format!("bytes://avatar/{source}.png");
egui::Image::from_bytes(uri, Bytes::Shared(bytes))
.fit_to_exact_size(Vec2::splat(rect.width()))
.corner_radius(rect.width() / 2.0)
diff --git a/src/forge.rs b/src/forge.rs
index 95c7e75..93f02a6 100644
--- a/src/forge.rs
+++ b/src/forge.rs
@@ -61,6 +61,7 @@ fn tool(forge: Forge, repo: &Path, args: &[&str]) -> Result<String, String> {
let mut cmd = Command::new(forge.tool());
cmd.current_dir(repo).args(args);
cmd.env("GH_PROMPT_DISABLED", "1").env("NO_PROMPT", "1");
+ crate::shell_path::apply(&mut cmd);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
diff --git a/src/git.rs b/src/git.rs
index 67762f2..a33b710 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -20,6 +20,7 @@ fn git_cmd() -> Command {
cmd.env("GIT_EDITOR", "true");
// Interactive rebases set `sequence.editor` themselves; an inherited one would win.
cmd.env_remove("GIT_SEQUENCE_EDITOR");
+ crate::shell_path::apply(&mut cmd);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
@@ -265,6 +266,8 @@ pub struct Commit {
pub time: i64,
pub date: String,
pub summary: String,
+ /// The rest of the message on one line (paragraphs joined by spaces), possibly empty.
+ pub body: String,
/// Decorations (`HEAD -> main`, `origin/main`, `tag: v1`), as git prints them.
pub refs: Vec<String>,
}
@@ -272,7 +275,7 @@ pub struct Commit {
/// The commits of every branch (stashes aside), newest first, in an order fit for drawing the
/// graph: `limit` of them after the first `skip`.
pub fn log(repo: &Path, skip: usize, limit: usize) -> Result<Vec<Commit>, String> {
- let format = format!("--format=%H{FS}%P{FS}%an{FS}%ae{FS}%at{FS}%ad{FS}%s{FS}%D{RS}");
+ let format = format!("--format=%H{FS}%P{FS}%an{FS}%ae{FS}%at{FS}%ad{FS}%s{FS}%D{FS}%b{RS}");
let limit = format!("--max-count={limit}");
let skip = format!("--skip={skip}");
let out = match run(
@@ -300,7 +303,18 @@ pub fn log(repo: &Path, skip: usize, limit: usize) -> Result<Vec<Commit>, String
continue;
}
let f: Vec<&str> = record.split(FS).collect();
- let [hash, parents, author, email, time, date, summary, decor] = f[..] else {
+ let [
+ hash,
+ parents,
+ author,
+ email,
+ time,
+ date,
+ summary,
+ decor,
+ body,
+ ] = f[..]
+ else {
continue;
};
commits.push(Commit {
@@ -311,6 +325,7 @@ pub fn log(repo: &Path, skip: usize, limit: usize) -> Result<Vec<Commit>, String
time: time.parse().unwrap_or(0),
date: date.to_owned(),
summary: summary.to_owned(),
+ body: one_line(body),
refs: decor
.split(", ")
.filter(|s| !s.is_empty())
@@ -321,6 +336,18 @@ pub fn log(repo: &Path, skip: usize, limit: usize) -> Result<Vec<Commit>, String
Ok(commits)
}
+/// A commit body as one line: whitespace runs (line breaks included) become single spaces. Long
+/// bodies are cut, the graph only shows their start.
+fn one_line(body: &str) -> String {
+ const MAX_CHARS: usize = 400;
+ body.split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+ .chars()
+ .take(MAX_CHARS)
+ .collect()
+}
+
#[derive(Clone, Debug)]
pub struct ChangedFile {
/// `A`, `M`, `D`, `R`, `C`, `T`…
@@ -463,6 +490,95 @@ pub fn file_diff(repo: &Path, hash: &str, path: &str, ignore_ws: bool) -> Result
run(Some(repo), &args)
}
+/// The files that differ from `from` to `to` (a commit, or the working tree when `None`), with
+/// their line counts.
+pub fn diff_files(repo: &Path, from: &str, to: Option<&str>) -> Result<Vec<ChangedFile>, String> {
+ let args = |kind: &'static str| {
+ let mut args = vec!["diff", "-M", kind, "-z", from];
+ args.extend(to);
+ args.push("--");
+ args
+ };
+ let mut files = parse_name_status(&run(Some(repo), &args("--name-status"))?);
+ for (path, added, removed) in parse_numstat(&run(Some(repo), &args("--numstat"))?) {
+ if let Some(file) = files.iter_mut().find(|f| f.path == path) {
+ file.added = added;
+ file.removed = removed;
+ }
+ }
+ Ok(files)
+}
+
+/// The patch of one file from `from` to `to` (the working tree when `None`).
+pub fn range_file_diff(
+ repo: &Path,
+ from: &str,
+ to: Option<&str>,
+ path: &str,
+ ignore_ws: bool,
+) -> Result<String, String> {
+ let mut args = vec!["diff", "-M"];
+ if ignore_ws {
+ args.push("-w");
+ }
+ args.push(from);
+ args.extend(to);
+ args.extend(["--", path]);
+ run(Some(repo), &args)
+}
+
+/// The best common ancestor of two commits.
+pub fn merge_base(repo: &Path, a: &str, b: &str) -> Result<String, String> {
+ run(Some(repo), &["merge-base", a, b]).map(|s| s.trim().to_owned())
+}
+
+/// The full hash of a branch, tag or abbreviated hash.
+pub fn resolve(repo: &Path, rev: &str) -> Result<String, String> {
+ run(
+ Some(repo),
+ &["rev-parse", "--verify", "-q", &format!("{rev}^{{commit}}")],
+ )
+ .map(|s| s.trim().to_owned())
+ .map_err(|_| format!("{rev} is not a commit"))
+}
+
+/// How many commits `a` has that `b` hasn't, and the other way round.
+pub fn count_apart(repo: &Path, a: &str, b: &str) -> Result<(u32, u32), String> {
+ let out = run(
+ Some(repo),
+ &["rev-list", "--left-right", "--count", &format!("{a}...{b}")],
+ )?;
+ let mut n = out.split_whitespace().map(|x| x.parse().unwrap_or(0));
+ Ok((n.next().unwrap_or(0), n.next().unwrap_or(0)))
+}
+
+/// Saves `patch` to a temporary file for `git apply`, which reads it from there (so the
+/// operation is a plain list of git commands, which undo can replay). Patches older than a day
+/// are cleared on the way.
+pub fn save_patch(patch: &str) -> Result<PathBuf, String> {
+ use std::sync::atomic::{AtomicU32, Ordering};
+ static SEQ: AtomicU32 = AtomicU32::new(0);
+ let dir = std::env::temp_dir().join("gitcraft-patches");
+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ if let Ok(entries) = std::fs::read_dir(&dir) {
+ for e in entries.flatten() {
+ let old = e
+ .metadata()
+ .and_then(|m| m.modified())
+ .ok()
+ .and_then(|t| t.elapsed().ok())
+ .is_some_and(|age| age.as_secs() > 24 * 3600);
+ if old {
+ let _ = std::fs::remove_file(e.path());
+ }
+ }
+ }
+ let n = SEQ.fetch_add(1, Ordering::Relaxed);
+ let path = dir.join(format!("{}-{}-{n}.patch", std::process::id(), now()));
+ std::fs::write(&path, patch).map_err(|e| format!("{}: {e}", path.display()))?;
+ Ok(path)
+}
+
/// Which side of the index a working-tree file is listed on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Area {
@@ -830,6 +946,23 @@ pub fn search(repo: &Path, query: &str) -> Result<Vec<String>, String> {
Ok(hashes)
}
+/// Commits that added or removed `query` in a file's contents (`git log -S`), newest first.
+pub fn search_code(repo: &Path, query: &str) -> Result<Vec<String>, String> {
+ let pickaxe = format!("-S{query}");
+ let out = run(
+ Some(repo),
+ &[
+ "log",
+ "--exclude=refs/stash",
+ "--all",
+ "--date-order",
+ "--format=%H",
+ &pickaxe,
+ ],
+ )?;
+ Ok(out.lines().map(str::to_owned).collect())
+}
+
/// The name and email commits are made with here, and whether they're set for this repository
/// only.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -1182,6 +1315,23 @@ mod tests {
assert_eq!(clone_dir_name("git@host:proj"), "proj");
}
+ #[test]
+ fn bodies_fit_on_one_line() {
+ assert_eq!(
+ one_line(
+ "First line
+second.
+
+- a
+- b
+"
+ ),
+ "First line second. - a - b"
+ );
+ assert_eq!(one_line(""), "");
+ assert_eq!(one_line(&"x ".repeat(500)).chars().count(), 400);
+ }
+
#[test]
fn name_status_with_rename() {
let files = parse_name_status("M\0a.txt\0R090\0old.rs\0new.rs\0D\0gone\0");
diff --git a/src/icons.rs b/src/icons.rs
index 8d1bb6a..141bbf8 100644
--- a/src/icons.rs
+++ b/src/icons.rs
@@ -21,6 +21,7 @@ const SOURCES: &[(&str, &str)] = icons![
"arrow-down-to-line",
"arrow-up",
"arrow-up-from-line",
+ "book-open",
"check",
"chevron-down",
"chevron-right",
@@ -196,6 +197,18 @@ pub fn small_button(ui: &mut Ui, icon: &str, tooltip: &str) -> Response {
resp.on_hover_text(tooltip)
}
+/// An icon-only button of the window's title bar, a size up from [`small_button`].
+pub fn bar_button(ui: &mut Ui, icon: &str, tooltip: &str) -> Response {
+ let t = Tokens::get(ui.ctx());
+ let (rect, resp) = ui.allocate_exact_size(Vec2::splat(28.0), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(rect, t.radius, t.pressed);
+ }
+ let tint = if resp.hovered() { t.text } else { t.icon };
+ paint(ui, rect, icon, 17.0, tint);
+ resp.on_hover_text(tooltip)
+}
+
/// An icon laid out inline, like a label.
pub fn inline(ui: &mut Ui, name: &str, size: f32, tint: Color32) {
let (rect, _) = ui.allocate_exact_size(Vec2::splat(size), Sense::hover());
diff --git a/src/lib.rs b/src/lib.rs
index 55d26ef..f96f07c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -7,8 +7,10 @@ mod forge;
mod git;
mod graph;
mod icons;
+mod manual;
mod repo;
mod settings;
+mod shell_path;
mod terminal;
mod theme;
mod update;
diff --git a/src/manual.rs b/src/manual.rs
new file mode 100644
index 0000000..2396d6d
--- /dev/null
+++ b/src/manual.rs
@@ -0,0 +1,176 @@
+//! The manual (F1, or the book in the title bar): what gitcraft does and its keyboard shortcuts.
+
+use egui::{RichText, Ui};
+
+use crate::theme::{self, Tokens};
+
+/// Ctrl, or Cmd on macOS, as the shortcuts are written.
+fn command() -> &'static str {
+ if cfg!(target_os = "macos") {
+ "Cmd"
+ } else {
+ "Ctrl"
+ }
+}
+
+/// What each part of the window does: (title, points).
+const FEATURES: &[(&str, &[&str])] = &[
+ (
+ "Repositories and tabs",
+ &[
+ "Open, create or clone a repository from the start page; recent ones are listed there.",
+ "One tab per repository. Changes made elsewhere (editor, terminal) show up by themselves.",
+ ],
+ ),
+ (
+ "Graph",
+ &[
+ "Every branch with its pill on its latest commit: solid for the checked-out one, a laptop when it is local, a cloud when a remote has it.",
+ "Double-click a pill to check that branch out; hover +N to see every branch of the commit.",
+ "Right-click a commit or a pill for branches, tags, merge, rebase, cherry-pick, revert, reset and more.",
+ "Search messages, authors and hashes, or switch to Code to find the commits that added or removed some text.",
+ "Interactive rebase: reorder, reword, squash, fix up or drop commits, then start it.",
+ ],
+ ),
+ (
+ "Compare",
+ &[
+ "Ctrl+click a second commit to list the files that differ between the two (the changes row is the working tree).",
+ "On a branch's menu, “Changes x adds to main” shows what it changed since they diverged, like a pull request; “Compare main with x” shows every difference.",
+ ],
+ ),
+ (
+ "Changes and commits",
+ &[
+ "Stage, unstage or discard whole files from the right pane.",
+ "In a file's diff, stage, unstage or discard one hunk, or click the lines you want and act on only those.",
+ "Write the summary and description and commit; amend the last commit; pick the identity you commit as.",
+ "Undo and redo commits, merges, rebases, resets, checkouts, branches, tags and stashes.",
+ ],
+ ),
+ (
+ "Branches, remotes and more",
+ &[
+ "Left pane: local branches with ahead / behind counts, remotes, worktrees, stashes, pull requests and tags.",
+ "Conflicts open in a three-pane editor with Ours, Theirs and Both for each conflict.",
+ "Right-click a file for its history and blame.",
+ "A terminal panel with tabs, in the repository's folder.",
+ ],
+ ),
+];
+
+/// Keyboard and mouse shortcuts: (keys, what they do). `Cmd` stands for Ctrl outside macOS.
+const SHORTCUTS: &[(&str, &[(&str, &str)])] = &[
+ (
+ "Window",
+ &[
+ ("Cmd+T", "New tab"),
+ ("Cmd+W", "Close the tab (or middle-click it)"),
+ ("Cmd+P", "Command palette: every action and branch"),
+ ("F5", "Reload the repository"),
+ ("F1", "This manual"),
+ ],
+ ),
+ (
+ "Graph",
+ &[
+ ("↑ / ↓", "Previous / next commit"),
+ ("Cmd+F", "Search commits"),
+ ("Enter / Shift+Enter", "Next / previous search result"),
+ ("Cmd+click", "Compare with the selected commit"),
+ ("Double-click a pill", "Check out that branch or tag"),
+ ("Esc", "Close the diff, comparison or search"),
+ ],
+ ),
+ (
+ "Changes",
+ &[
+ ("Cmd+Enter", "Commit (from the message fields)"),
+ (
+ "Click / Shift+click",
+ "Pick lines in a diff, or a range of them",
+ ),
+ ("Cmd+Z", "Undo"),
+ ("Cmd+Y / Cmd+Shift+Z", "Redo"),
+ ],
+ ),
+ (
+ "Terminal",
+ &[
+ (
+ "Cmd+C",
+ "Copy the selection (without one, it goes to the shell)",
+ ),
+ ("Cmd+Shift+C", "Copy the selection"),
+ ],
+ ),
+];
+
+/// Draws the manual's contents.
+pub fn ui(ui: &mut Ui) {
+ let t = Tokens::get(ui.ctx());
+ let heading = |ui: &mut Ui, text: &str| {
+ ui.add_space(10.0);
+ ui.label(
+ RichText::new(text.to_uppercase())
+ .font(theme::semibold(10.5))
+ .color(t.text_faint),
+ );
+ ui.add_space(2.0);
+ };
+
+ for (title, points) in FEATURES {
+ heading(ui, title);
+ for point in *points {
+ // The bullet on the left, the text wrapping beside it.
+ ui.horizontal_top(|ui| {
+ ui.spacing_mut().item_spacing.x = 6.0;
+ ui.label(RichText::new("•").color(t.text_faint));
+ ui.add(
+ egui::Label::new(
+ RichText::new(point.replace("Ctrl", command())).color(t.text_dim),
+ )
+ .wrap(),
+ );
+ });
+ }
+ }
+
+ ui.add_space(8.0);
+ ui.separator();
+ for (title, keys) in SHORTCUTS {
+ heading(ui, &format!("{title} shortcuts"));
+ egui::Grid::new(("manual_keys", *title))
+ .num_columns(2)
+ .spacing([16.0, 6.0])
+ .min_col_width(170.0)
+ .show(ui, |ui| {
+ for (combo, what) in *keys {
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ for (n, part) in combo.split(" / ").enumerate() {
+ if n > 0 {
+ ui.label(RichText::new("/").color(t.text_faint));
+ }
+ key_chip(ui, &part.replace("Cmd", command()));
+ }
+ });
+ ui.label(RichText::new(*what).color(t.text_dim));
+ ui.end_row();
+ }
+ });
+ }
+}
+
+/// A key combination drawn like a keycap.
+fn key_chip(ui: &mut Ui, keys: &str) {
+ let t = Tokens::get(ui.ctx());
+ egui::Frame::new()
+ .fill(t.field)
+ .stroke(egui::Stroke::new(1.0, t.field_border))
+ .corner_radius(t.radius_sm)
+ .inner_margin(egui::Margin::symmetric(6, 1))
+ .show(ui, |ui| {
+ ui.label(RichText::new(keys).font(theme::mono(11.5)).color(t.text));
+ });
+}
diff --git a/src/repo/detail.rs b/src/repo/detail.rs
index 6a20bb2..9584d1e 100644
--- a/src/repo/detail.rs
+++ b/src/repo/detail.rs
@@ -5,14 +5,16 @@ use egui::{Align2, Key, RichText, Sense, Ui, pos2, vec2};
use super::diff::unstage_args;
use super::widgets::{self, RowExtra};
use super::{Action, Dialog, DiffKey, DiffView, Refresh, RepoTab, abort_action, ops};
-use crate::git::{Area, StatusFile};
+use crate::git::{Area, ChangedFile, StatusFile};
use crate::icons;
use crate::theme::{self, Tokens};
impl RepoTab {
pub(super) fn detail_panel(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {
let wip = self.selected.is_some_and(|r| self.is_wip(r));
- if wip {
+ if self.compare.is_some() {
+ self.compare_panel(ui, acts);
+ } else if wip {
self.changes_panel(ui, acts);
} else {
self.commit_panel(ui, acts);
@@ -178,70 +180,164 @@ impl RepoTab {
});
});
- let (adds, dels) = detail.files.iter().fold((0, 0), |(a, d), f| {
- (a + f.added.unwrap_or(0), d + f.removed.unwrap_or(0))
- });
- let (rect, _) =
- ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::hover());
- let p = ui.painter();
- p.rect_filled(rect, 0.0, t.tab_strip);
- let y = rect.center().y;
- let r = p.text(
- pos2(rect.left() + 14.0, y),
- Align2::LEFT_CENTER,
- format!(
- "{} file{} changed",
- detail.files.len(),
- if detail.files.len() == 1 { "" } else { "s" }
- ),
- theme::semibold(11.5),
- t.text_dim,
- );
- let r = p.text(
- pos2(r.right() + 10.0, y),
- Align2::LEFT_CENTER,
- format!("+{adds}"),
- theme::mono(11.0),
- t.success,
- );
- p.text(
- pos2(r.right() + 6.0, y),
- Align2::LEFT_CENTER,
- format!("−{dels}"),
- theme::mono(11.0),
- t.danger,
- );
- if detail.parents.len() > 1 {
- p.text(
- pos2(rect.right() - 10.0, y),
- Align2::RIGHT_CENTER,
- "vs. first parent",
- egui::FontId::proportional(11.0),
- t.text_faint,
- );
- }
-
+ let note = (detail.parents.len() > 1).then_some("vs. first parent");
+ files_header(ui, &detail.files, note);
ui.spacing_mut().item_spacing.y = 0.0;
- for f in &detail.files {
- let key = DiffKey::Commit {
+ self.file_list(ui, acts, &detail.files, Some(&detail.hash), |path| {
+ DiffKey::Commit {
hash: detail.hash.clone(),
- path: f.path.clone(),
+ path: path.to_owned(),
+ }
+ });
+ });
+ }
+
+ /// Changed files, each opening its diff (`key`) when clicked; `rev`: where the files are,
+ /// for their menu (`None`: the working tree).
+ fn file_list(
+ &self,
+ ui: &mut Ui,
+ acts: &mut Vec<Action>,
+ files: &[ChangedFile],
+ rev: Option<&str>,
+ key: impl Fn(&str) -> DiffKey,
+ ) {
+ for f in files {
+ let key = key(&f.path);
+ let selected = self.open_key() == Some(&key);
+ let r = widgets::file_row(
+ ui,
+ f.status,
+ &f.path,
+ f.old_path.as_deref(),
+ selected,
+ RowExtra::Stats(f.added, f.removed),
+ );
+ widgets::file_menu(&r.row, &f.path, rev, false, acts);
+ if r.row.clicked() {
+ acts.push(Action::OpenDiff(key));
+ }
+ }
+ }
+
+ /// Right pane while comparing: the two ends, how far apart they are, and the files that
+ /// differ.
+ fn compare_panel(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {
+ let t = Tokens::get(ui.ctx());
+ let Some(c) = &self.compare else { return };
+ widgets::panel_header(ui, "Compare", |ui| {
+ if icons::small_button(ui, "x", "Close (Esc)").clicked() {
+ acts.push(Action::CloseCompare);
+ }
+ });
+ let data = c.data.as_ref().and_then(|d| d.as_ref().ok());
+ let target_name = if c.target.is_some() {
+ c.target_label.as_str()
+ } else {
+ "the working tree"
+ };
+ egui::Frame::new()
+ .inner_margin(egui::Margin::symmetric(14, 12))
+ .show(ui, |ui| {
+ ui.set_width(ui.available_width());
+ ui.spacing_mut().item_spacing.y = 6.0;
+ egui::Grid::new("compare_ends")
+ .num_columns(2)
+ .spacing([12.0, 6.0])
+ .show(ui, |ui| {
+ // A name, and the commit it stands for (`note` before the hash).
+ let end = |ui: &mut Ui, label: &str, hash: Option<&str>, note: &str| {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(label).font(theme::medium(12.5)));
+ // The hash, unless the label already is it.
+ if let Some(hash) = hash.filter(|h| super::short(h) != label) {
+ ui.label(
+ RichText::new(format!("{note}{}", super::short(hash)))
+ .font(theme::mono(11.5))
+ .color(t.text_faint),
+ )
+ .on_hover_text(hash);
+ }
+ });
+ };
+ let note = if c.since_fork { "merge base " } else { "" };
+ ui.label(RichText::new("From").color(t.text_faint));
+ end(ui, &c.base_label, data.map(|d| d.from.as_str()), note);
+ ui.end_row();
+ ui.label(RichText::new("To").color(t.text_faint));
+ end(ui, target_name, data.and_then(|d| d.to.as_deref()), "");
+ ui.end_row();
+ });
+ if let Some(d) = data {
+ let (behind, ahead) = d.apart;
+ let commits = |n: u32| format!("{n} commit{}", if n == 1 { "" } else { "s" });
+ let other = if c.target.is_some() {
+ target_name
+ } else {
+ "HEAD"
};
- let selected = self.open_key() == Some(&key);
- let r = widgets::file_row(
- ui,
- f.status,
- &f.path,
- f.old_path.as_deref(),
- selected,
- RowExtra::Stats(f.added, f.removed),
- );
- widgets::file_menu(&r.row, &f.path, Some(&detail.hash), false, acts);
- if r.row.clicked() {
- acts.push(Action::OpenDiff(key));
+ let text = match (ahead, behind) {
+ (0, 0) => "Same history".to_owned(),
+ (a, 0) => format!("{other} is {} ahead", commits(a)),
+ (0, b) => format!("{other} is {} behind", commits(b)),
+ (a, b) => format!("{other} is {} ahead, {b} behind", commits(a)),
+ };
+ ui.label(RichText::new(text).color(t.text_dim).small());
+ }
+ ui.horizontal(|ui| {
+ let mut since = c.since_fork;
+ let label = format!("Only what {target_name} changed since they diverged");
+ if ui
+ .checkbox(&mut since, label)
+ .on_hover_text(
+ "Diff from the merge base, as a pull request shows it, instead of \
+ every difference between the two",
+ )
+ .changed()
+ {
+ acts.push(Action::CompareSinceFork(since));
}
+ });
+ if c.target.is_some() && ui.button("Swap").clicked() {
+ acts.push(Action::SwapCompare);
}
});
+
+ match &c.data {
+ None => {
+ ui.add_space(20.0);
+ ui.vertical_centered(|ui| ui.spinner());
+ }
+ Some(Err(e)) => {
+ ui.horizontal(|ui| {
+ ui.add_space(14.0);
+ ui.colored_label(t.danger, e);
+ });
+ }
+ Some(Ok(d)) => {
+ files_header(ui, &d.files, None);
+ if d.files.is_empty() {
+ ui.add_space(10.0);
+ ui.vertical_centered(|ui| {
+ ui.label(RichText::new("No differences").color(t.text_dim));
+ });
+ return;
+ }
+ egui::ScrollArea::vertical()
+ .id_salt("compare_scroll")
+ .auto_shrink(false)
+ .show(ui, |ui| {
+ ui.spacing_mut().item_spacing.y = 0.0;
+ self.file_list(ui, acts, &d.files, d.to.as_deref(), |path| {
+ DiffKey::Range {
+ from: d.from.clone(),
+ to: d.to.clone(),
+ path: path.to_owned(),
+ }
+ });
+ });
+ }
+ }
}
fn changes_panel(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {
@@ -575,6 +671,52 @@ fn discard_dialog(f: &StatusFile) -> Dialog {
}
}
+/// "N files changed +a −d", and an optional note on the right.
+fn files_header(ui: &mut Ui, files: &[ChangedFile], note: Option<&str>) {
+ let t = Tokens::get(ui.ctx());
+ let (adds, dels) = files.iter().fold((0, 0), |(a, d), f| {
+ (a + f.added.unwrap_or(0), d + f.removed.unwrap_or(0))
+ });
+ let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::hover());
+ let p = ui.painter();
+ p.rect_filled(rect, 0.0, t.tab_strip);
+ let y = rect.center().y;
+ let r = p.text(
+ pos2(rect.left() + 14.0, y),
+ Align2::LEFT_CENTER,
+ format!(
+ "{} file{} changed",
+ files.len(),
+ if files.len() == 1 { "" } else { "s" }
+ ),
+ theme::semibold(11.5),
+ t.text_dim,
+ );
+ let r = p.text(
+ pos2(r.right() + 10.0, y),
+ Align2::LEFT_CENTER,
+ format!("+{adds}"),
+ theme::mono(11.0),
+ t.success,
+ );
+ p.text(
+ pos2(r.right() + 6.0, y),
+ Align2::LEFT_CENTER,
+ format!("−{dels}"),
+ theme::mono(11.0),
+ t.danger,
+ );
+ if let Some(note) = note {
+ p.text(
+ pos2(rect.right() - 10.0, y),
+ Align2::RIGHT_CENTER,
+ note,
+ egui::FontId::proportional(11.0),
+ t.text_faint,
+ );
+ }
+}
+
/// A list title with a count and an optional text button on the right. Returns the click.
fn list_header(ui: &mut Ui, title: &str, count: usize, button: Option<&str>) -> bool {
let t = Tokens::get(ui.ctx());
diff --git a/src/repo/diff.rs b/src/repo/diff.rs
index 35cbd74..f56babe 100644
--- a/src/repo/diff.rs
+++ b/src/repo/diff.rs
@@ -1,6 +1,8 @@
//! Central pane while a file is open: its diff, unified or side by side, with syntax colours,
-//! the changed part of each line marked, and images shown before / after.
+//! the changed part of each line marked, and images shown before / after. Uncommitted changes
+//! can be staged, unstaged or discarded a hunk or a few lines at a time.
+use std::collections::BTreeSet;
use std::path::Path;
use std::sync::Arc;
@@ -11,7 +13,7 @@ use egui::{
use super::highlight::{self, Spans};
use super::widgets;
-use super::{Action, DiffKey, Refresh, RepoTab, ops};
+use super::{Action, DiffKey, Refresh, RepoTab, ops, short};
use crate::git::{self, Area};
use crate::icons;
use crate::theme::{self, Tokens};
@@ -37,7 +39,10 @@ pub struct DiffLine {
pub kind: Kind,
pub old: Option<u32>,
pub new: Option<u32>,
+ /// What is shown: the line without its `+`/`-` column, tabs expanded.
pub text: String,
+ /// The line exactly as git printed it, to build patches from.
+ pub raw: String,
}
/// Everything the view needs, prepared on a background thread.
@@ -50,6 +55,45 @@ pub struct DiffData {
/// Side-by-side rows: (left line, right line).
pub split: Vec<(Option<usize>, Option<usize>)>,
pub image: Option<ImagePair>,
+ /// The patch's file header (`diff --git`, `index`, `---`, `+++`), for partial patches.
+ pub header: String,
+ /// Hunks and lines can be staged, unstaged or discarded on their own.
+ pub partial: bool,
+}
+
+/// What to do with some hunks or lines of an uncommitted file's diff.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Pick {
+ /// Unstaged lines into the index.
+ Stage,
+ /// Staged lines out of the index.
+ Unstage,
+ /// Unstaged lines out of the working tree.
+ Discard,
+}
+
+impl Pick {
+ /// The patch is applied with `--reverse`.
+ fn reverse(self) -> bool {
+ self != Pick::Stage
+ }
+
+ /// `git apply` arguments before the patch file.
+ pub fn args(self) -> &'static [&'static str] {
+ match self {
+ Pick::Stage => &["apply", "--cached"],
+ Pick::Unstage => &["apply", "--cached", "--reverse"],
+ Pick::Discard => &["apply", "--reverse"],
+ }
+ }
+
+ pub fn verb(self) -> &'static str {
+ match self {
+ Pick::Stage => "Stage",
+ Pick::Unstage => "Unstage",
+ Pick::Discard => "Discard",
+ }
+ }
}
pub struct ImagePair {
@@ -66,8 +110,30 @@ pub fn load(repo: &Path, key: &DiffKey, ignore_ws: bool, dark: bool) -> Result<D
(git::file_diff(repo, hash, path, ignore_ws)?, path.clone())
}
DiffKey::Work(file) => (git::work_diff(repo, file, ignore_ws)?, file.path.clone()),
+ DiffKey::Range { from, to, path } => (
+ git::range_file_diff(repo, from, to.as_deref(), path, ignore_ws)?,
+ path.clone(),
+ ),
};
let lines = parse(&text);
+ let header = patch_header(&text);
+ // A patch made from a `-w` diff wouldn't apply; new, deleted, renamed and binary files, and
+ // truncated diffs, only go whole.
+ let partial = matches!(key, DiffKey::Work(f) if matches!(f.area, Area::Staged | Area::Unstaged))
+ && !ignore_ws
+ && !header.is_empty()
+ && ![
+ "new file mode",
+ "deleted file mode",
+ "rename from",
+ "copy from",
+ "Binary files",
+ ]
+ .iter()
+ .any(|h| header.contains(h))
+ && lines
+ .iter()
+ .all(|l| l.kind != Kind::Meta || l.raw.starts_with('\\'));
let image = if is_image(&path) {
Some(load_images(repo, key, &path))
} else {
@@ -110,6 +176,8 @@ pub fn load(repo: &Path, key: &DiffKey, ignore_ws: bool, dark: bool) -> Result<D
changed,
split,
image,
+ header,
+ partial,
})
}
@@ -138,6 +206,11 @@ fn load_images(repo: &Path, key: &DiffKey, path: &str) -> ImagePair {
Area::Untracked => (None, get(None), "untracked".to_owned()),
Area::Conflicted => (None, get(None), "conflicted".to_owned()),
},
+ DiffKey::Range { from, to, .. } => (
+ get(Some(from)),
+ get(to.as_deref()),
+ format!("{from}-{}", to.as_deref().unwrap_or("work")),
+ ),
};
ImagePair {
old,
@@ -215,7 +288,8 @@ pub fn parse(text: &str) -> Vec<DiffLine> {
let mut in_hunk = false;
// Combined diffs (`@@@`) prefix every line with one column per parent.
let mut prefix = 1;
- for line in text.lines() {
+ // Not `lines()`: a `\r` before the newline belongs to the file's line.
+ for line in text.split_terminator('\n') {
if out.len() >= MAX_LINES {
out.push(meta("… diff truncated"));
break;
@@ -229,7 +303,8 @@ pub fn parse(text: &str) -> Vec<DiffLine> {
kind: Kind::Hunk,
old: None,
new: None,
- text: line.to_owned(),
+ text: line.trim_end_matches('\r').to_owned(),
+ raw: line.to_owned(),
});
continue;
}
@@ -281,7 +356,8 @@ pub fn parse(text: &str) -> Vec<DiffLine> {
kind,
old: if combined { None } else { o },
new: if combined { None } else { n },
- text: body.replace('\t', " "),
+ text: body.trim_end_matches('\r').replace('\t', " "),
+ raw: line.to_owned(),
});
}
out
@@ -292,10 +368,177 @@ fn meta(text: &str) -> DiffLine {
kind: Kind::Meta,
old: None,
new: None,
- text: text.to_owned(),
+ text: text.trim_end_matches('\r').to_owned(),
+ raw: text.to_owned(),
+ }
+}
+
+/// Everything before the first hunk of a one-file patch, each line ending in `\n`.
+fn patch_header(text: &str) -> String {
+ let mut header = String::new();
+ for line in text.split_terminator('\n') {
+ if line.starts_with("@@") {
+ return header;
+ }
+ header.push_str(line);
+ header.push('\n');
+ }
+ // No hunk at all (binary, mode change only): nothing to pick from.
+ String::new()
+}
+
+/// The lines of the hunk whose header is at `h`: up to the next hunk.
+fn hunk_body(lines: &[DiffLine], h: usize) -> std::ops::Range<usize> {
+ let end = lines[h + 1..]
+ .iter()
+ .position(|l| l.kind == Kind::Hunk)
+ .map_or(lines.len(), |n| h + 1 + n);
+ h + 1..end
+}
+
+/// The added and removed lines of the hunk whose header is at `h`.
+pub fn hunk_changes(lines: &[DiffLine], h: usize) -> BTreeSet<usize> {
+ hunk_body(lines, h)
+ .filter(|&i| matches!(lines[i].kind, Kind::Add | Kind::Del))
+ .collect()
+}
+
+/// `@@ -12,5 +14,7 @@ fn x` → (12, 14, " fn x").
+fn hunk_numbers(header: &str) -> Option<(u32, u32, &str)> {
+ let rest = header.strip_prefix("@@ -")?;
+ let (ranges, tail) = rest.split_once(" @@")?;
+ let (old, new) = ranges.split_once(" +")?;
+ let start = |r: &str| r.split(',').next()?.parse::<u32>().ok();
+ Some((start(old)?, start(new)?, tail))
+}
+
+/// One hunk of a partial patch being written.
+#[derive(Default)]
+struct HunkOut {
+ body: String,
+ old_n: i64,
+ new_n: i64,
+ changed: bool,
+}
+
+impl HunkOut {
+ /// Writes line `i` as the patch needs it (or not at all), and the "\ No newline at end of
+ /// file" note right after it if it has one.
+ fn line(&mut self, lines: &[DiffLine], i: usize, picked: bool, reverse: bool) {
+ let line = &lines[i];
+ let as_context = match line.kind {
+ Kind::Context => true,
+ Kind::Add | Kind::Del if picked => false,
+ // Left out: an addition only exists on the new side, a removal on the old one, so
+ // each stays as context on its side and goes from the other.
+ Kind::Add if reverse => true,
+ Kind::Del if !reverse => true,
+ _ => return,
+ };
+ if as_context {
+ self.body.push(' ');
+ self.body.push_str(line.raw.get(1..).unwrap_or_default());
+ self.old_n += 1;
+ self.new_n += 1;
+ } else {
+ self.body.push_str(&line.raw);
+ self.changed = true;
+ if line.kind == Kind::Add {
+ self.new_n += 1;
+ } else {
+ self.old_n += 1;
+ }
+ }
+ self.body.push('\n');
+ if let Some(note) = lines.get(i + 1).filter(|l| l.kind == Kind::Meta) {
+ self.body.push_str(&note.raw);
+ self.body.push('\n');
+ }
}
}
+/// A patch of `header` with only the `chosen` added / removed lines (indices into `lines`), for
+/// `git apply` as `pick` runs it. What isn't chosen stays as it is: a removal left out becomes
+/// context where the patch is checked against the old side, an addition left out where it is
+/// checked against the new side (applied in reverse). `None` when no change is chosen.
+pub fn partial_patch(
+ header: &str,
+ lines: &[DiffLine],
+ chosen: &BTreeSet<usize>,
+ pick: Pick,
+) -> Option<String> {
+ let reverse = pick.reverse();
+ let mut patch = header.to_owned();
+ // How far the hunks written so far moved the other side's line numbers.
+ let mut shift: i64 = 0;
+ let mut any = false;
+ for h in (0..lines.len()).filter(|&i| lines[i].kind == Kind::Hunk) {
+ let (old_start, new_start, tail) = hunk_numbers(&lines[h].raw)?;
+ let mut out = HunkOut::default();
+ let body = hunk_body(lines, h);
+ let mut i = body.start;
+ while i < body.end {
+ match lines[i].kind {
+ Kind::Del | Kind::Add => {
+ // A run of removals and the additions after it, written in pairs (like the
+ // side-by-side view pairs them): replacing the 2nd line of three keeps its
+ // place even when the others are left out.
+ let mut run = |kind: Kind| {
+ let mut found = Vec::new();
+ while i < body.end
+ && matches!(lines[i].kind, k if k == kind || k == Kind::Meta)
+ {
+ if lines[i].kind == kind {
+ found.push(i);
+ }
+ i += 1;
+ }
+ found
+ };
+ let dels = run(Kind::Del);
+ let adds = run(Kind::Add);
+ for k in 0..dels.len().max(adds.len()) {
+ for &j in dels.get(k).into_iter().chain(adds.get(k)) {
+ out.line(lines, j, chosen.contains(&j), reverse);
+ }
+ }
+ }
+ Kind::Context => {
+ out.line(lines, i, false, reverse);
+ i += 1;
+ }
+ // Notes go with their line.
+ _ => i += 1,
+ }
+ }
+ let HunkOut {
+ body,
+ old_n,
+ new_n,
+ changed,
+ } = out;
+ if !changed {
+ continue;
+ }
+ any = true;
+ // `git apply` places a hunk by the side it checks: the old one, the new one in reverse.
+ let (old_start, new_start) = (i64::from(old_start), i64::from(new_start));
+ let (o, n) = if reverse {
+ (new_start - shift, new_start)
+ } else {
+ (old_start, old_start + shift)
+ };
+ shift += new_n - old_n;
+ patch.push_str(&format!(
+ "@@ -{},{old_n} +{},{new_n} @@{tail}\n",
+ o.max(0),
+ n.max(0)
+ ));
+ patch.push_str(&body);
+ }
+ any.then_some(patch)
+}
+
/// `@@ -12,5 +14,7 @@` → (11, 13): the numbers before the first line of the hunk.
fn hunk_start(header: &str) -> (u32, u32) {
let mut old = 0;
@@ -338,8 +581,12 @@ impl RepoTab {
Area::Conflicted => "Conflicted".to_owned(),
},
),
+ DiffKey::Range { from, to, path } => (path.clone(), self.range_label(from, to)),
};
+ let partial = matches!(&view.data, Some(Ok(d)) if d.partial) && idle;
+ let chosen = view.chosen.len();
let (split, ignore_ws) = (self.diff_split, self.diff_ignore_ws);
+ let mut clear = false;
egui::Frame::new()
.fill(t.chrome)
.inner_margin(egui::Margin::symmetric(10, 6))
@@ -353,6 +600,8 @@ impl RepoTab {
);
let (rev, ignorable) = match &view.key {
DiffKey::Commit { hash, .. } => (Some(hash.as_str()), false),
+ DiffKey::Range { to: Some(to), .. } => (Some(to.as_str()), false),
+ DiffKey::Range { to: None, .. } => (None, false),
DiffKey::Work(_) => (None, true),
};
widgets::file_menu(&title, &path, rev, ignorable, acts);
@@ -378,6 +627,35 @@ impl RepoTab {
refresh: Refresh::Status,
});
}
+ // The lines clicked in the diff.
+ if partial && chosen > 0 {
+ ui.add_space(8.0);
+ let lines = if chosen == 1 { "line" } else { "lines" };
+ let picks: &[Pick] = if file.area == Area::Staged {
+ &[Pick::Unstage]
+ } else {
+ &[Pick::Stage, Pick::Discard]
+ };
+ for &pick in picks {
+ let b = egui::Button::new(format!(
+ "{} {chosen} {lines}",
+ pick.verb()
+ ));
+ if ui.add(b).clicked() {
+ acts.push(Action::PickLines {
+ pick,
+ lines: view.chosen.clone(),
+ });
+ }
+ }
+ if ui
+ .button("Clear")
+ .on_hover_text("Unselect the lines")
+ .clicked()
+ {
+ clear = true;
+ }
+ }
}
ui.add_space(8.0);
let ws = icons::small_button(
@@ -472,6 +750,42 @@ impl RepoTab {
} else {
data.lines.len()
};
+ // Which hunk actions the headers offer.
+ let hunk_picks: &[Pick] = match &view.key {
+ DiffKey::Work(f) if partial && f.area == Area::Staged => &[Pick::Unstage],
+ DiffKey::Work(_) if partial => &[Pick::Stage, Pick::Discard],
+ _ => &[],
+ };
+ let shift = ui.input(|i| i.modifiers.shift);
+ // A changed line clicked: (line, extend the selection).
+ let mut clicked: Option<usize> = None;
+ let mut paint = |ui: &mut Ui, rect: Rect, i: usize, side: Side| {
+ let kind = data.lines.get(i).map(|l| l.kind);
+ let pickable = partial && matches!(kind, Some(Kind::Add | Kind::Del));
+ paint_line(ui, rect, data, i, side, &font, &t, view.chosen.contains(&i));
+ if pickable {
+ let resp = ui
+ .interact(rect, ui.id().with(("diff_line", i)), Sense::click())
+ .on_hover_cursor(egui::CursorIcon::PointingHand);
+ if resp.clicked() {
+ clicked = Some(i);
+ }
+ }
+ if kind == Some(Kind::Hunk) && !hunk_picks.is_empty() {
+ // At the visible right end, however wide the line is.
+ let mut right = rect.right().min(ui.clip_rect().right()) - 6.0;
+ for &pick in hunk_picks.iter().rev() {
+ let (resp, left) = hunk_button(ui, right, rect.center().y, pick, i);
+ if resp.clicked() {
+ acts.push(Action::PickLines {
+ pick,
+ lines: hunk_changes(&data.lines, i),
+ });
+ }
+ right = left - 4.0;
+ }
+ }
+ };
egui::ScrollArea::both()
.id_salt(("diff_scroll", &path, split))
.auto_shrink(false)
@@ -498,15 +812,15 @@ impl RepoTab {
Some(Kind::Hunk | Kind::Meta)
)
{
- paint_line(ui, rect, data, i, Side::Both, &font, &t);
+ paint(ui, rect, i, Side::Both);
continue;
}
match l {
- Some(i) => paint_line(ui, left, data, i, Side::Old, &font, &t),
+ Some(i) => paint(ui, left, i, Side::Old),
None => filler(ui, left, &t),
}
match r {
- Some(i) => paint_line(ui, right, data, i, Side::New, &font, &t),
+ Some(i) => paint(ui, right, i, Side::New),
None => filler(ui, right, &t),
}
ui.painter().line_segment(
@@ -519,13 +833,105 @@ impl RepoTab {
(NUM_W * 2.0 + 24.0 + longest * char_w + 24.0).max(ui.available_width());
for i in range {
let (rect, _) = ui.allocate_exact_size(vec2(width, LINE_H), Sense::hover());
- paint_line(ui, rect, data, i, Side::Unified, &font, &t);
+ paint(ui, rect, i, Side::Unified);
}
}
});
+
+ if let Some(view) = &mut self.diff {
+ if clear {
+ view.chosen.clear();
+ view.anchor = None;
+ }
+ if let Some(i) = clicked {
+ view.pick_line(i, shift);
+ }
+ }
+ }
+
+ /// "abc1234 → def5678" for a diff between two commits, with the names of the comparison.
+ fn range_label(&self, from: &str, to: &Option<String>) -> String {
+ let name = |rev: &str| {
+ self.compare
+ .as_ref()
+ .and_then(|c| c.name_of(rev))
+ .unwrap_or_else(|| short(rev).to_owned())
+ };
+ match to {
+ Some(to) => format!("{} → {}", name(from), name(to)),
+ None => format!("{} → working tree", name(from)),
+ }
+ }
+}
+
+impl super::DiffView {
+ /// Click on a changed line: toggles it, or with Shift selects every changed line from the
+ /// last one clicked.
+ fn pick_line(&mut self, i: usize, extend: bool) {
+ let Some(Ok(data)) = &self.data else { return };
+ match self.anchor {
+ Some(a) if extend => {
+ let (lo, hi) = (a.min(i), a.max(i));
+ self.chosen.extend(
+ (lo..=hi).filter(|&k| matches!(data.lines[k].kind, Kind::Add | Kind::Del)),
+ );
+ }
+ _ => {
+ if !self.chosen.remove(&i) {
+ self.chosen.insert(i);
+ }
+ self.anchor = Some(i);
+ }
+ }
}
}
+/// A small text button in a hunk header, its right edge at `right`; returns it and its left edge.
+fn hunk_button(ui: &mut Ui, right: f32, y: f32, pick: Pick, hunk: usize) -> (egui::Response, f32) {
+ let t = Tokens::get(ui.ctx());
+ let label = format!("{} hunk", pick.verb());
+ let color = if pick == Pick::Discard {
+ t.text_dim
+ } else {
+ t.accent
+ };
+ let galley = ui
+ .painter()
+ .layout_no_wrap(label, theme::medium(11.0), color);
+ let r = Rect::from_min_max(
+ pos2(right - galley.size().x - 14.0, y - 9.0),
+ pos2(right, y + 9.0),
+ );
+ let resp = ui.interact(
+ r,
+ ui.id().with(("hunk_btn", hunk, pick.verb())),
+ Sense::click(),
+ );
+ let fill = if resp.hovered() { t.hover } else { t.dock };
+ ui.painter().rect_filled(r, t.radius_sm, fill);
+ ui.painter().rect_stroke(
+ r,
+ t.radius_sm,
+ Stroke::new(1.0, t.separator),
+ egui::StrokeKind::Inside,
+ );
+ ui.painter().galley(
+ pos2(r.left() + 7.0, y - galley.size().y / 2.0),
+ galley,
+ color,
+ );
+ let tip = match pick {
+ Pick::Stage => {
+ "Stage this hunk. Click lines to stage only some of them (Shift+click for a range)."
+ }
+ Pick::Unstage => {
+ "Unstage this hunk. Click lines to unstage only some of them (Shift+click for a range)."
+ }
+ Pick::Discard => "Throw away this hunk's changes (Ctrl+Z brings them back).",
+ };
+ (resp.on_hover_text(tip), r.left())
+}
+
#[derive(Clone, Copy, PartialEq, Eq)]
enum Side {
Unified,
@@ -540,6 +946,7 @@ fn filler(ui: &Ui, rect: Rect, t: &Tokens) {
.rect_filled(rect, 0.0, t.card.gamma_multiply(0.35));
}
+#[allow(clippy::too_many_arguments)]
fn paint_line(
ui: &Ui,
rect: Rect,
@@ -548,6 +955,7 @@ fn paint_line(
side: Side,
font: &egui::FontId,
t: &Tokens,
+ selected: bool,
) {
let Some(line) = data.lines.get(i) else {
return;
@@ -563,6 +971,10 @@ fn paint_line(
if let Some(bg) = bg {
p.rect_filled(rect, 0.0, bg);
}
+ // Picked to stage / unstage / discard: tinted, with a bar on the left.
+ if selected {
+ p.rect_filled(rect, 0.0, t.accent.gamma_multiply(0.22));
+ }
let y = rect.center().y;
let numbers: &[(Option<u32>, f32)] = match side {
Side::Unified => &[(line.old, NUM_W - 8.0), (line.new, NUM_W * 2.0 - 8.0)],
@@ -582,6 +994,13 @@ fn paint_line(
t.card.gamma_multiply(0.6),
);
}
+ if selected {
+ p.rect_filled(
+ Rect::from_min_size(rect.min, vec2(3.0, LINE_H)),
+ 0.0,
+ t.accent,
+ );
+ }
for &(n, x) in numbers {
if let Some(n) = n {
p.text(
@@ -791,6 +1210,135 @@ mod tests {
assert_eq!(changed_ranges("abc", "abXc"), Some(((2, 2), (2, 3))));
}
+ const PATCH: &str = "diff --git a/f b/f\nindex 1..2 100644\n--- a/f\n+++ b/f\n\
+ @@ -1,4 +1,4 @@ top\n a\n-b\n-c\n+B\n+C\n d\n\
+ @@ -10,2 +10,3 @@\n x\n+y\n z\n";
+
+ /// The hunks of a partial patch, without the file header.
+ fn hunks(lines: &[DiffLine], chosen: &[usize], pick: Pick) -> Option<String> {
+ let header = patch_header(PATCH);
+ let chosen: BTreeSet<usize> = chosen.iter().copied().collect();
+ partial_patch(&header, lines, &chosen, pick)
+ .and_then(|p| p.strip_prefix(&header).map(str::to_owned))
+ }
+
+ #[test]
+ fn partial_patch_keeps_only_the_chosen_lines() {
+ let lines = parse(PATCH);
+ assert_eq!(patch_header(PATCH).lines().count(), 4);
+ // Indices: 0 hunk, 1 a, 2 -b, 3 -c, 4 +B, 5 +C, 6 d, 7 hunk, 8 x, 9 +y, 10 z.
+ // b → B only: c stays where it was, after B.
+ assert_eq!(
+ hunks(&lines, &[2, 4], Pick::Stage).as_deref(),
+ Some("@@ -1,4 +1,4 @@ top\n a\n-b\n+B\n c\n d\n")
+ );
+ // In reverse an addition left out stays as context and a removal left out goes.
+ assert_eq!(
+ hunks(&lines, &[2, 4], Pick::Discard).as_deref(),
+ Some("@@ -1,4 +1,4 @@ top\n a\n-b\n+B\n C\n d\n")
+ );
+ // The second hunk alone, after the first moved nothing.
+ let second: Vec<usize> = hunk_changes(&lines, 7).into_iter().collect();
+ assert_eq!(
+ hunks(&lines, &second, Pick::Stage).as_deref(),
+ Some("@@ -10,2 +10,3 @@\n x\n+y\n z\n")
+ );
+ assert_eq!(hunks(&lines, &[], Pick::Stage), None);
+ }
+
+ #[test]
+ fn later_hunks_follow_the_lines_earlier_ones_add() {
+ let lines = parse(PATCH);
+ // Only the additions of the first hunk (+2 lines), and the second hunk.
+ let patch = hunks(&lines, &[4, 5, 9], Pick::Stage).unwrap_or_default();
+ assert!(patch.starts_with("@@ -1,4 +1,6 @@ top\n a\n b\n+B\n c\n+C\n d\n"));
+ assert!(patch.contains("@@ -10,2 +12,3 @@\n"));
+ }
+
+ #[test]
+ fn no_newline_note_follows_its_line() {
+ let text = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n";
+ let lines = parse(text);
+ let header = patch_header(text);
+ // Only the removal of the last line: its note goes with it, the addition is left out.
+ let chosen: BTreeSet<usize> = [2].into();
+ let patch = partial_patch(&header, &lines, &chosen, Pick::Stage).unwrap_or_default();
+ assert!(patch.ends_with("@@ -1,2 +1,1 @@\n a\n-b\n\\ No newline at end of file\n"));
+ }
+
+ #[test]
+ fn crlf_lines_keep_their_carriage_return() {
+ let lines = parse("@@ -1 +1 @@\n-a\r\n+b\r\n");
+ assert_eq!(lines[1].text, "a");
+ assert_eq!(lines[2].raw, "+b\r");
+ }
+
+ /// Stages, unstages and discards a few lines in a real repository.
+ #[test]
+ fn partial_patches_apply_with_git() {
+ let dir = std::env::temp_dir().join(format!("gitcraft-partial-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let _ = std::fs::create_dir_all(&dir);
+ let git = |args: &[&str]| git::run(Some(&dir), args);
+ for args in [
+ &["init", "-q"][..],
+ &["config", "user.name", "t"],
+ &["config", "user.email", "t@t"],
+ &["config", "core.autocrlf", "false"],
+ ] {
+ assert!(git(args).is_ok());
+ }
+ let file = dir.join("f.txt");
+ let base: String = (1..=20).map(|n| format!("line {n}\n")).collect();
+ let _ = std::fs::write(&file, &base);
+ assert!(git(&["add", "."]).is_ok());
+ assert!(git(&["commit", "-q", "-m", "base"]).is_ok());
+ let edited = base
+ .replace("line 2\n", "line two\n")
+ .replace("line 3\n", "line three\n")
+ .replace("line 18\n", "line 18\nline 18b\n");
+ let _ = std::fs::write(&file, &edited);
+
+ let work = |area| git::StatusFile {
+ path: "f.txt".to_owned(),
+ old_path: None,
+ code: 'M',
+ area,
+ };
+ let pick = |area, which: &dyn Fn(&DiffLine) -> bool, how: Pick| -> Result<(), String> {
+ let data = load(&dir, &DiffKey::Work(work(area)), false, true)?;
+ assert!(data.partial);
+ let chosen = (0..data.lines.len())
+ .filter(|&i| which(&data.lines[i]))
+ .collect();
+ let patch =
+ partial_patch(&data.header, &data.lines, &chosen, how).ok_or("nothing picked")?;
+ let path = git::save_patch(&patch)?.to_string_lossy().into_owned();
+ let mut args = how.args().to_vec();
+ args.push(&path);
+ git(&args).map(|_| ())
+ };
+ let index = || git(&["show", ":f.txt"]).unwrap_or_default();
+ // Stage line 2 → "line two" only.
+ let second = |l: &DiffLine| l.text == "line 2" || l.text == "line two";
+ assert_eq!(pick(Area::Unstaged, &second, Pick::Stage), Ok(()));
+ assert_eq!(index(), base.replace("line 2\n", "line two\n"));
+ // Discard the line added near the end.
+ let added = |l: &DiffLine| l.text == "line 18b";
+ assert_eq!(pick(Area::Unstaged, &added, Pick::Discard), Ok(()));
+ let on_disk = std::fs::read_to_string(&file).unwrap_or_default();
+ assert_eq!(
+ on_disk,
+ base.replace("line 2\n", "line two\n")
+ .replace("line 3\n", "line three\n")
+ );
+ // Unstage the addition but keep the removal staged.
+ let two = |l: &DiffLine| l.text == "line two";
+ assert_eq!(pick(Area::Staged, &two, Pick::Unstage), Ok(()));
+ assert_eq!(index(), base.replace("line 2\n", ""));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn changed_part_gets_its_own_section() {
let font = theme::mono(12.0);
diff --git a/src/repo/graph_view.rs b/src/repo/graph_view.rs
index bfe6c47..9c8ea14 100644
--- a/src/repo/graph_view.rs
+++ b/src/repo/graph_view.rs
@@ -8,8 +8,8 @@ use egui::{
use super::widgets;
use super::{
- Action, Dialog, Refresh, RepoTab, Undo, WIP_HASH, fast_forward_action, merge_action, ops,
- rebase_action,
+ Action, Dialog, Refresh, RepoTab, Undo, WIP_HASH, compare_action, fast_forward_action,
+ merge_action, ops, rebase_action,
};
use crate::git::{self, Refs};
use crate::icons;
@@ -175,7 +175,12 @@ impl RepoTab {
}
let resp = self.commit_row(ui, i, cols, lanes, now, acts);
if resp.clicked() {
- acts.push(Action::Select(i));
+ // Ctrl+click: compare the selected commit with this one.
+ let compare = ui
+ .input(|inp| inp.modifiers.command)
+ .then(|| self.compare_rows(self.selected?, i))
+ .flatten();
+ acts.push(compare.unwrap_or(Action::Select(i)));
}
let Some(commit) = self.commits.get(i) else {
continue;
@@ -209,6 +214,39 @@ impl RepoTab {
ui.data_mut(|d| d.insert_temp(offset_id, out.state.offset.y));
}
+ /// Compares two rows of the graph, the older one first; the changes row stands for the
+ /// working tree. `None` for the same row twice.
+ fn compare_rows(&self, a: usize, b: usize) -> Option<Action> {
+ if a == b {
+ return None;
+ }
+ // Rows go newest first.
+ let (old, new) = (a.max(b), a.min(b));
+ let end = |row: usize| {
+ let c = self.commits.get(row)?;
+ let label = badges(&c.refs, &self.refs)
+ .into_iter()
+ .find(|b| b.kind != BadgeKind::DetachedHead)
+ .map(|b| b.label)
+ .unwrap_or_else(|| super::short(&c.hash).to_owned());
+ Some((c.hash.clone(), label))
+ };
+ let (base, base_label) = end(old)?;
+ let (target, target_label) = if self.is_wip(new) {
+ (None, "working tree".to_owned())
+ } else {
+ let (hash, label) = end(new)?;
+ (Some(hash), label)
+ };
+ Some(Action::Compare {
+ base,
+ base_label,
+ target,
+ target_label,
+ since_fork: false,
+ })
+ }
+
/// Right-click menu of a commit row.
fn commit_menu(&self, resp: &Response, i: usize, idle: bool, acts: &mut Vec<Action>) {
let Some(commit) = self.commits.get(i) else {
@@ -298,6 +336,8 @@ impl RepoTab {
label: branch.clone(),
});
}
+ ui.separator();
+ compare_items(ui, acts, branch, current);
}
ui.separator();
}
@@ -325,6 +365,40 @@ impl RepoTab {
acts.push(Action::Checkout(hash.clone()));
}
ui.separator();
+ if let Some(compare) = self
+ .selected
+ .filter(|&s| s != i)
+ .and_then(|s| self.compare_rows(s, i))
+ {
+ let other = self
+ .selected
+ .and_then(|s| self.commits.get(s))
+ .map(|c| {
+ if c.hash == WIP_HASH {
+ "the working tree".to_owned()
+ } else {
+ super::short(&c.hash).to_owned()
+ }
+ })
+ .unwrap_or_default();
+ if ui
+ .button(format!("Compare with {other}"))
+ .on_hover_text("Also Ctrl+click on a commit")
+ .clicked()
+ {
+ acts.push(compare);
+ }
+ }
+ if ui.button("Compare with the working tree").clicked() {
+ acts.push(Action::Compare {
+ base: hash.clone(),
+ base_label: short.clone(),
+ target: None,
+ target_label: "working tree".to_owned(),
+ since_fork: false,
+ });
+ }
+ ui.separator();
if ui
.add_enabled(
idle && !is_head,
@@ -493,12 +567,39 @@ impl RepoTab {
.show(ui, |ui| {
ui.horizontal(|ui| {
icons::inline(ui, "search", 15.0, t.text_faint);
+ let code = self.search.code;
let edit = ui.add(
egui::TextEdit::singleline(&mut self.search.query)
- .hint_text("Search messages, authors and hashes in all history")
- .desired_width(ui.available_width() - 190.0)
+ .hint_text(if code {
+ "Search code added or removed by a commit, in all history"
+ } else {
+ "Search messages, authors and hashes in all history"
+ })
+ .desired_width(ui.available_width() - 290.0)
.margin(egui::Margin::symmetric(8, 4)),
);
+ // Where to look: commit messages or the code they changed.
+ for (label, on, tip) in [
+ (
+ "Messages",
+ false,
+ "Search commit messages, authors and hashes",
+ ),
+ (
+ "Code",
+ true,
+ "Search the commits that added or removed this text in a file \
+ (git log -S)",
+ ),
+ ] {
+ if ui
+ .selectable_label(code == on, label)
+ .on_hover_text(tip)
+ .clicked()
+ {
+ acts.push(Action::SearchCode(on));
+ }
+ }
if std::mem::take(&mut self.search.focus) {
edit.request_focus();
}
@@ -579,6 +680,24 @@ impl RepoTab {
t.warning,
);
}
+ // An end of the comparison shown on the right (the changes row for the working tree).
+ let compared = self
+ .compare
+ .as_ref()
+ .and_then(|c| c.data.as_ref()?.as_ref().ok())
+ .is_some_and(|d| {
+ d.from == commit.hash
+ || d.to.as_deref() == Some(commit.hash.as_str())
+ || (is_wip && d.to.is_none())
+ });
+ if compared {
+ painter.rect_stroke(
+ rect.shrink(1.0),
+ 0.0,
+ Stroke::new(1.0, t.accent),
+ egui::StrokeKind::Inside,
+ );
+ }
let (top, mid, bottom) = (rect.top(), rect.center().y, rect.bottom());
let gx = rect.left() + cols.refs;
@@ -770,18 +889,32 @@ impl RepoTab {
} else {
FontId::proportional(12.5)
};
- painter
- .with_clip_rect(Rect::from_min_max(
- pos2(x, rect.top()),
- pos2(text_right, rect.bottom()),
- ))
- .text(
- pos2(x + 2.0, mid),
- Align2::LEFT_CENTER,
- &commit.summary,
- font,
+ // The summary, then the rest of the message faded, cut with an ellipsis.
+ let text_clip = painter.with_clip_rect(Rect::from_min_max(
+ pos2(x, rect.top()),
+ pos2(text_right, rect.bottom()),
+ ));
+ let summary = text_clip.text(
+ pos2(x + 2.0, mid),
+ Align2::LEFT_CENTER,
+ &commit.summary,
+ font.clone(),
+ t.text,
+ );
+ let room = text_right - summary.right() - 12.0;
+ if !commit.body.is_empty() && room > 24.0 {
+ let mut job = egui::text::LayoutJob::single_section(
+ commit.body.clone(),
+ egui::TextFormat::simple(FontId::proportional(12.5), t.text.gamma_multiply(0.5)),
+ );
+ job.wrap = egui::text::TextWrapping::truncate_at_width(room);
+ let galley = ui.fonts_mut(|f| f.layout_job(job));
+ text_clip.galley(
+ pos2(summary.right() + 10.0, mid - galley.size().y / 2.0),
+ galley,
t.text,
);
+ }
let small = FontId::proportional(11.5);
if cols.hash > 0.0 {
@@ -819,6 +952,25 @@ impl RepoTab {
}
}
+/// Menu entries comparing `branch` with `current`: what it would bring in (since they
+/// diverged, as a pull request shows it), and every difference.
+pub(super) fn compare_items(ui: &mut Ui, acts: &mut Vec<Action>, branch: &str, current: &str) {
+ if ui
+ .button(format!("Changes {branch} adds to {current}"))
+ .on_hover_text("What it changed since the two diverged, as a pull request shows it")
+ .clicked()
+ {
+ acts.push(compare_action(current, branch, true));
+ }
+ if ui
+ .button(format!("Compare {current} with {branch}"))
+ .on_hover_text("Every difference between the two")
+ .clicked()
+ {
+ acts.push(compare_action(current, branch, false));
+ }
+}
+
/// One pill in the refs column: a branch (local, remote or both), a tag or a detached HEAD.
#[derive(Debug)]
struct Badge {
diff --git a/src/repo/mod.rs b/src/repo/mod.rs
index 9533aec..c44001c 100644
--- a/src/repo/mod.rs
+++ b/src/repo/mod.rs
@@ -55,6 +55,8 @@ enum Msg {
result: Result<Vec<git::RebaseCommit>, String>,
},
Search(String, Result<Vec<String>, String>),
+ /// A comparison's files, for the request numbered so.
+ Compare(u64, Result<CompareData, String>),
Prs(Result<Vec<PullRequest>, String>),
OpDone {
label: String,
@@ -127,19 +129,87 @@ enum OpKind {
/// Which diff the central area shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum DiffKey {
- Commit { hash: String, path: String },
+ Commit {
+ hash: String,
+ path: String,
+ },
Work(StatusFile),
+ /// A file from one commit to another, or to the working tree (`to: None`).
+ Range {
+ from: String,
+ to: Option<String>,
+ path: String,
+ },
}
pub(crate) struct DiffView {
key: DiffKey,
data: Option<Result<diff::DiffData, String>>,
+ /// Changed lines clicked, to stage, unstage or discard only those.
+ chosen: std::collections::BTreeSet<usize>,
+ /// The last line clicked, where a Shift+click range starts.
+ anchor: Option<usize>,
+}
+
+impl DiffView {
+ fn new(key: DiffKey) -> Self {
+ Self {
+ key,
+ data: None,
+ chosen: Default::default(),
+ anchor: None,
+ }
+ }
+}
+
+/// Two points of history side by side in the right pane: a branch against another, a commit
+/// against the working tree…
+pub(crate) struct Compare {
+ base: String,
+ base_label: String,
+ /// `None`: the working tree.
+ target: Option<String>,
+ target_label: String,
+ /// Only what the target changed since the two diverged (from their merge base), like a pull
+ /// request shows it.
+ since_fork: bool,
+ data: Option<Result<CompareData, String>>,
+ /// Numbers the requests, so an older answer doesn't replace a newer one.
+ request: u64,
+}
+
+pub(crate) struct CompareData {
+ /// Where the diff starts: the base's commit, or the merge base.
+ from: String,
+ /// The target's commit (`None`: the working tree).
+ to: Option<String>,
+ files: Vec<git::ChangedFile>,
+ /// Commits only the base has, and only the target (HEAD for the working tree) has.
+ apart: (u32, u32),
+}
+
+impl Compare {
+ /// How the comparison calls one of its two ends.
+ fn name_of(&self, rev: &str) -> Option<String> {
+ let data = self.data.as_ref()?.as_ref().ok()?;
+ if data.to.as_deref() == Some(rev) {
+ Some(self.target_label.clone())
+ } else if data.from == rev && self.since_fork {
+ Some(format!("merge base {}", short(rev)))
+ } else if data.from == rev {
+ Some(self.base_label.clone())
+ } else {
+ None
+ }
+ }
}
#[derive(Default)]
struct Search {
open: bool,
focus: bool,
+ /// Search what commits added or removed in files (`git log -S`), not their messages.
+ code: bool,
query: String,
/// The query the results are for.
searched: String,
@@ -229,6 +299,25 @@ pub(crate) enum Action {
pattern: String,
path: String,
},
+ /// Stage, unstage or discard these changed lines of the open diff.
+ PickLines {
+ pick: diff::Pick,
+ lines: std::collections::BTreeSet<usize>,
+ },
+ /// Compare `base` with `target` (the working tree when `None`) in the right pane.
+ Compare {
+ base: String,
+ base_label: String,
+ target: Option<String>,
+ target_label: String,
+ since_fork: bool,
+ },
+ /// Show only the target's changes since the two diverged, or every difference.
+ CompareSinceFork(bool),
+ SwapCompare,
+ CloseCompare,
+ /// Search commit messages, or what commits changed in files.
+ SearchCode(bool),
}
pub struct RepoTab {
@@ -267,6 +356,8 @@ pub struct RepoTab {
detail: Option<CommitDetail>,
detail_error: Option<String>,
diff: Option<DiffView>,
+ compare: Option<Compare>,
+ compare_requests: u64,
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.
@@ -358,6 +449,8 @@ impl RepoTab {
detail: None,
detail_error: None,
diff: None,
+ compare: None,
+ compare_requests: 0,
file_view: None,
rebase: None,
credentials: None,
@@ -589,10 +682,15 @@ impl RepoTab {
.chain(&self.work.conflicted)
.any(|f| f == file);
let key = DiffKey::Work(file.clone());
- self.diff = None;
- self.conflict = None;
- if still {
- self.open_diff(key, ctx);
+ if still && file.area != git::Area::Conflicted {
+ // Shown as it was until the new diff is read (no flicker after staging lines).
+ self.refresh_diff(ctx);
+ } else {
+ self.diff = None;
+ self.conflict = None;
+ if still {
+ self.open_diff(key, ctx);
+ }
}
}
@@ -612,10 +710,11 @@ impl RepoTab {
self.selected = Some(row);
self.stash_view = None;
self.file_view = None;
+ self.compare = None;
if matches!(
self.diff,
Some(DiffView {
- key: DiffKey::Commit { .. },
+ key: DiffKey::Commit { .. } | DiffKey::Range { .. },
..
})
) || hash != WIP_HASH
@@ -650,6 +749,7 @@ impl RepoTab {
self.stash_view = Some(i);
self.selected = None;
self.file_view = None;
+ self.compare = None;
self.diff = None;
self.conflict = None;
self.load_detail(hash, ctx);
@@ -701,10 +801,14 @@ impl RepoTab {
}
_ => None,
};
- self.diff = Some(DiffView {
- key: key.clone(),
- data: None,
- });
+ self.diff = Some(DiffView::new(key));
+ self.refresh_diff(ctx);
+ }
+
+ /// Reads the open diff again, showing the old one meanwhile.
+ fn refresh_diff(&mut self, ctx: &egui::Context) {
+ let Some(view) = &self.diff else { return };
+ let key = view.key.clone();
let path = self.path.clone();
let ignore_ws = self.diff_ignore_ws;
let dark = Tokens::get(ctx).dark();
@@ -714,6 +818,59 @@ impl RepoTab {
});
}
+ /// Starts comparing two points of history (replacing the comparison shown).
+ fn compare(&mut self, compare: Compare, ctx: &egui::Context) {
+ if matches!(
+ self.diff,
+ Some(DiffView {
+ key: DiffKey::Range { .. },
+ ..
+ })
+ ) {
+ self.diff = None;
+ }
+ self.file_view = None;
+ self.compare = Some(compare);
+ self.reload_compare(ctx);
+ }
+
+ /// Reads the comparison's files again (the working tree or a branch moved).
+ fn reload_compare(&mut self, ctx: &egui::Context) {
+ self.compare_requests += 1;
+ let request = self.compare_requests;
+ let Some(c) = &mut self.compare else { return };
+ c.request = request;
+ let (path, base, target, since_fork) = (
+ self.path.clone(),
+ c.base.clone(),
+ c.target.clone(),
+ c.since_fork,
+ );
+ spawn(&self.tx, ctx, move || {
+ let result = (|| {
+ let base = git::resolve(&path, &base)?;
+ let to = target.map(|t| git::resolve(&path, &t)).transpose()?;
+ // The working tree goes with HEAD's history.
+ let other = match &to {
+ Some(to) => to.clone(),
+ None => git::resolve(&path, "HEAD")?,
+ };
+ let from = if since_fork {
+ git::merge_base(&path, &base, &other)?
+ } else {
+ base.clone()
+ };
+ Ok(CompareData {
+ files: git::diff_files(&path, &from, to.as_deref())?,
+ apart: git::count_apart(&path, &base, &other)?,
+ from,
+ to,
+ })
+ })();
+ Msg::Compare(request, result)
+ });
+ }
+
/// Shows `path`'s history or blame, loading what that tab needs.
fn open_file_view(
&mut self,
@@ -1078,8 +1235,13 @@ impl RepoTab {
}
self.search.running = true;
let path = self.path.clone();
+ let code = self.search.code;
spawn(&self.tx, ctx, move || {
- let result = git::search(&path, &query);
+ let result = if code {
+ git::search_code(&path, &query)
+ } else {
+ git::search(&path, &query)
+ };
Msg::Search(query, result)
});
}
@@ -1207,6 +1369,7 @@ impl RepoTab {
}
self.rebuild(ctx);
self.hint_avatars(ctx);
+ self.reload_compare(ctx);
}
Err(e) => self.load_error = Some(e),
}
@@ -1233,6 +1396,9 @@ impl RepoTab {
Ok(work) => {
self.work = work;
self.rebuild(ctx);
+ if self.compare.as_ref().is_some_and(|c| c.target.is_none()) {
+ self.reload_compare(ctx);
+ }
}
Err(e) => self.status = Some((e, true)),
},
@@ -1285,6 +1451,16 @@ impl RepoTab {
&& view.key == key
{
view.data = Some(result);
+ // The lines may have moved.
+ view.chosen.clear();
+ view.anchor = None;
+ }
+ }
+ Msg::Compare(request, result) => {
+ if let Some(c) = &mut self.compare
+ && c.request == request
+ {
+ c.data = Some(result);
}
}
Msg::Search(query, result) => {
@@ -1610,6 +1786,107 @@ impl RepoTab {
}
}
},
+ Action::PickLines { pick, lines } => {
+ let Some(DiffView {
+ key: DiffKey::Work(file),
+ data: Some(Ok(data)),
+ ..
+ }) = &self.diff
+ else {
+ return;
+ };
+ let Some(patch) = diff::partial_patch(&data.header, &data.lines, &lines, pick)
+ else {
+ return;
+ };
+ let patch = match git::save_patch(&patch) {
+ Ok(p) => p.to_string_lossy().into_owned(),
+ Err(e) => {
+ self.status = Some((e, true));
+ return;
+ }
+ };
+ let n = lines.len();
+ let label = format!(
+ "{} {n} line{} of {}",
+ pick.verb(),
+ if n == 1 { "" } else { "s" },
+ file.path
+ );
+ let mut args = pick.args().to_vec();
+ args.push(&patch);
+ if pick == diff::Pick::Discard {
+ // Applying the same patch forward brings the lines back.
+ let undo = Undo::Custom {
+ undo: ops(&[&["apply", &patch]]),
+ redo: ops(&[&args]),
+ };
+ self.run_undoable(&label, ops(&[&args]), Refresh::Status, undo, ctx);
+ } else {
+ self.run_ops(&label, ops(&[&args]), Refresh::Status, plain, ctx);
+ }
+ }
+ Action::Compare {
+ base,
+ base_label,
+ target,
+ target_label,
+ since_fork,
+ } => self.compare(
+ Compare {
+ base,
+ base_label,
+ target,
+ target_label,
+ since_fork,
+ data: None,
+ request: 0,
+ },
+ ctx,
+ ),
+ Action::CompareSinceFork(on) => {
+ if let Some(c) = &mut self.compare {
+ c.since_fork = on;
+ self.reload_compare(ctx);
+ }
+ }
+ Action::SwapCompare => {
+ // The working tree stays the newer end.
+ if let Some(c) = self.compare.take_if(|c| c.target.is_some())
+ && let Some(target) = c.target
+ {
+ self.compare(
+ Compare {
+ base: target,
+ base_label: c.target_label,
+ target: Some(c.base),
+ target_label: c.base_label,
+ data: None,
+ ..c
+ },
+ ctx,
+ );
+ }
+ }
+ Action::CloseCompare => {
+ self.compare = None;
+ if matches!(
+ self.diff,
+ Some(DiffView {
+ key: DiffKey::Range { .. },
+ ..
+ })
+ ) {
+ self.diff = None;
+ }
+ }
+ Action::SearchCode(on) => {
+ if self.search.code != on {
+ self.search.code = on;
+ self.run_search(ctx);
+ }
+ self.search.focus = true;
+ }
Action::SaveConflict => {
if let Some(editor) = &self.conflict {
match editor.save(&self.path) {
@@ -1654,6 +1931,8 @@ impl RepoTab {
acts.push(Action::CloseRebase);
} else if esc && self.file_view.is_some() {
acts.push(Action::CloseFileView);
+ } else if esc && self.compare.is_some() {
+ acts.push(Action::CloseCompare);
} else if esc && self.search.open {
acts.push(Action::ToggleSearch);
}
@@ -1993,6 +2272,16 @@ impl RepoTab {
if let Some(current) = &self.refs.current {
for b in &self.refs.local {
if !b.is_head {
+ items.push((
+ format!("Changes {} adds to {current}", b.name),
+ "compare".into(),
+ compare_action(current, &b.name, true),
+ ));
+ items.push((
+ format!("Compare {current} with {}", b.name),
+ "compare".into(),
+ compare_action(current, &b.name, false),
+ ));
items.push((
format!("Merge {} into {current}", b.name),
"merge".into(),
@@ -2019,6 +2308,18 @@ impl RepoTab {
}
}
+/// Compares branch (or commit) `base` with `target`; `since_fork`: only what `target` changed
+/// since they diverged.
+pub(crate) fn compare_action(base: &str, target: &str, since_fork: bool) -> Action {
+ Action::Compare {
+ base: base.to_owned(),
+ base_label: base.to_owned(),
+ target: Some(target.to_owned()),
+ target_label: target.to_owned(),
+ since_fork,
+ }
+}
+
pub(crate) fn merge_action(branch: &str, current: &str) -> Action {
Action::UndoableOps {
label: format!("Merge {branch} into {current}"),
@@ -2080,6 +2381,7 @@ pub(crate) fn open_in_editor(editor: &str, path: &Path) -> Result<(), String> {
} else {
let mut c = std::process::Command::new(editor);
c.arg(path);
+ crate::shell_path::apply(&mut c);
c
};
#[cfg(windows)]
@@ -2122,6 +2424,11 @@ fn headline(msg: &str) -> String {
}
}
+/// A hash as the UI shows it: its first 8 characters.
+pub(crate) fn short(hash: &str) -> &str {
+ hash.get(..8).unwrap_or(hash)
+}
+
/// `&[&["checkout", "main"]]` → owned argument lists.
pub(crate) fn ops(list: &[&[&str]]) -> Vec<Vec<String>> {
list.iter()
diff --git a/src/repo/sidebar.rs b/src/repo/sidebar.rs
index 1ba4a07..d0213a2 100644
--- a/src/repo/sidebar.rs
+++ b/src/repo/sidebar.rs
@@ -5,7 +5,8 @@ use egui::{Align2, Rect, Response, Sense, Ui, pos2, vec2};
use super::widgets::{self, ROW_H};
use super::{
- Action, Dialog, Refresh, RepoTab, Undo, fast_forward_action, merge_action, ops, rebase_action,
+ Action, Dialog, Refresh, RepoTab, Undo, compare_action, fast_forward_action, merge_action, ops,
+ rebase_action,
};
use crate::git::{self, Branch};
use crate::icons;
@@ -271,6 +272,22 @@ impl RepoTab {
label: b.name.clone(),
});
}
+ ui.separator();
+ super::graph_view::compare_items(ui, acts, &b.name, current);
+ }
+ // The checked-out branch against the one pull requests usually go to.
+ if b.is_head
+ && let Some(base) = self.base_ref()
+ && base != b.name
+ {
+ ui.separator();
+ if ui
+ .button(format!("Changes {} adds to {base}", b.name))
+ .on_hover_text("What it changed since the two diverged, as a pull request shows it")
+ .clicked()
+ {
+ acts.push(compare_action(&base, &b.name, true));
+ }
}
ui.separator();
if let Some(remote) = self.default_remote()
@@ -360,6 +377,21 @@ impl RepoTab {
}
/// The branch pull requests go into by default: the remote's HEAD, else main / master.
+ /// The branch to compare the current one with: the local default base, or its remote one.
+ fn base_ref(&self) -> Option<String> {
+ let base = self.default_base();
+ if self.refs.local.iter().any(|b| b.name == base) {
+ return Some(base);
+ }
+ let remote = format!("{}/{base}", self.default_remote()?);
+ self.refs
+ .remotes
+ .iter()
+ .flat_map(|(_, list)| list)
+ .any(|b| b.name == remote)
+ .then_some(remote)
+ }
+
fn default_base(&self) -> String {
let remote = self.default_remote().unwrap_or_else(|| "origin".to_owned());
let names: Vec<&str> = self
@@ -532,6 +564,9 @@ impl RepoTab {
{
acts.push(rebase_action(&b.name, current));
}
+ ui.separator();
+ super::graph_view::compare_items(ui, acts, &b.name, current);
+ ui.separator();
}
if ui.button("Create branch here…").clicked() {
acts.push(Action::Dialog(Dialog::create_branch(&b.target, &b.name)));
diff --git a/src/shell_path.rs b/src/shell_path.rs
new file mode 100644
index 0000000..23b051f
--- /dev/null
+++ b/src/shell_path.rs
@@ -0,0 +1,98 @@
+//! macOS apps opened from the Finder or the Dock get a bare PATH (`/usr/bin:/bin:/usr/sbin:/sbin`),
+//! without Homebrew's folders, where git, gh, glab and editors' commands usually are. The
+//! commands gitcraft starts get the PATH of the user's login shell instead.
+
+use std::ffi::OsString;
+use std::io::Read;
+use std::path::PathBuf;
+use std::process::{Command, Stdio};
+use std::sync::OnceLock;
+use std::time::{Duration, Instant};
+
+/// Folders added in any case (Homebrew on Apple silicon, then on Intel).
+const FALLBACK: &[&str] = &["/opt/homebrew/bin", "/usr/local/bin"];
+
+/// The PATH for commands gitcraft runs, when it differs from its own (macOS only).
+pub fn path() -> Option<&'static OsString> {
+ static PATH: OnceLock<Option<OsString>> = OnceLock::new();
+ PATH.get_or_init(|| {
+ if cfg!(target_os = "macos") {
+ login_path()
+ } else {
+ None
+ }
+ })
+ .as_ref()
+}
+
+/// Gives `cmd` that PATH.
+pub fn apply(cmd: &mut Command) {
+ if let Some(path) = path() {
+ cmd.env("PATH", path);
+ }
+}
+
+fn login_path() -> Option<OsString> {
+ let own = std::env::var_os("PATH").unwrap_or_default();
+ let shell = shell_path().unwrap_or_default();
+ let joined = merge([&shell, &own]);
+ (joined != own).then_some(joined)
+}
+
+/// Every folder of `paths` once, in order, then the fallbacks.
+fn merge<const N: usize>(paths: [&OsString; N]) -> OsString {
+ let mut dirs: Vec<PathBuf> = Vec::new();
+ let candidates = paths
+ .iter()
+ .flat_map(|p| std::env::split_paths(p).collect::<Vec<_>>())
+ .chain(FALLBACK.iter().map(PathBuf::from));
+ for dir in candidates {
+ if !dir.as_os_str().is_empty() && !dirs.contains(&dir) {
+ dirs.push(dir);
+ }
+ }
+ std::env::join_paths(dirs).unwrap_or_default()
+}
+
+/// `$PATH` as the user's login shell sets it, if it answers within a few seconds.
+fn shell_path() -> Option<OsString> {
+ let shell = std::env::var_os("SHELL").unwrap_or_else(|| "/bin/zsh".into());
+ let mut child = Command::new(shell)
+ .args(["-l", "-c", "printf %s \"$PATH\""])
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .ok()?;
+ let deadline = Instant::now() + Duration::from_secs(3);
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => break,
+ Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)),
+ _ => {
+ let _ = child.kill();
+ return None;
+ }
+ }
+ }
+ let mut out = String::new();
+ child.stdout.take()?.read_to_string(&mut out).ok()?;
+ let out = out.trim();
+ (!out.is_empty()).then(|| out.into())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn folders_are_kept_once_in_order() {
+ let shell = std::env::join_paths(["/opt/homebrew/bin", "/usr/bin"]).unwrap_or_default();
+ let own = std::env::join_paths(["/usr/bin", "/bin"]).unwrap_or_default();
+ let merged: Vec<PathBuf> = std::env::split_paths(&merge([&shell, &own])).collect();
+ assert_eq!(
+ merged,
+ ["/opt/homebrew/bin", "/usr/bin", "/bin", "/usr/local/bin"].map(PathBuf::from)
+ );
+ }
+}
diff --git a/src/terminal.rs b/src/terminal.rs
index 9636dfa..f11a034 100644
--- a/src/terminal.rs
+++ b/src/terminal.rs
@@ -136,6 +136,9 @@ impl Terminal {
cmd.cwd(cwd);
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
+ if let Some(path) = crate::shell_path::path() {
+ cmd.env("PATH", path);
+ }
let child = pair
.slave
.spawn_command(cmd)
diff --git a/src/theme.rs b/src/theme.rs
index ad37307..d94f472 100644
--- a/src/theme.rs
+++ b/src/theme.rs
@@ -336,7 +336,8 @@ pub fn apply(ctx: &egui::Context, kind: ThemeKind) {
s.spacing.item_spacing = egui::vec2(8.0, 6.0);
s.spacing.button_padding = egui::vec2(10.0, 4.0);
s.spacing.interact_size = egui::vec2(24.0, 24.0);
- s.spacing.menu_margin = egui::Margin::same(6);
+ // Tooltips and other popups (menus set their own, see `menu_style`).
+ s.spacing.menu_margin = egui::Margin::symmetric(12, 7);
s.spacing.window_margin = egui::Margin::same(16);
s.spacing.icon_width = 14.0;
s.visuals.indent_has_left_vline = false;