Compare commits

..
10 Commits
Author SHA1 Message Date
reya 5e6156066a feat: detect local grasp repositories (#21)
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
Reviewed-on: #21
2026-09-14 04:06:10 +00:00
reya a74c166391 chore: remove unnecessary optimization (#20)
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
Reviewed-on: #20
2026-09-13 14:48:50 +00:00
reya f6b8a5e133 chore: clean up codebase (#19)
Rust / build (macos-latest, stable) (push) Waiting to run
Rust / build (ubuntu-latest, stable) (push) Waiting to run
Rust / build (windows-latest, stable) (push) Waiting to run
Reviewed-on: #19
2026-09-13 09:42:08 +00:00
reya 40deb9db66 feat: add inbox panel (#18)
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s
Reviewed-on: #18
2026-09-12 03:34:51 +00:00
reya 38e8b2b933 chore: refactor the backend (#17)
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s
Reviewed-on: #17
2026-09-10 09:43:35 +00:00
reya a8e19e5fcd chore: migrate from git command to gix (#16)
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s
Reviewed-on: https://git.reya.su/reya/signed/pulls/16
2026-09-08 04:01:13 +00:00
reya 1af4c66566 chore: add release infrastructure and packaging support
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s
Add GitHub Actions workflows for CI and release builds, packaging
scripts for Windows, macOS, Linux, and Flatpak/Snap distribution,
application icons, desktop files, and release metadata resources.
2026-09-07 12:44:35 +07:00
reya 02a0134164 chore: clean up 2026-09-07 09:24:10 +07:00
reya cf1c9e2162 fix: push failing in some cases (#15)
Reviewed-on: https://git.reya.su/reya/signed/pulls/15
2026-09-07 01:13:21 +00:00
reya 00167c6a8d feat: push checkout (#14)
Reviewed-on: https://git.reya.su/reya/signed/pulls/14
2026-09-06 13:14:11 +00:00
128 changed files with 14341 additions and 10258 deletions
Vendored
BIN
View File
Binary file not shown.
+173
View File
@@ -0,0 +1,173 @@
name: Build and Release
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
build:
name: Build ${{ matrix.platform }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- platform: windows-x64
os: windows-latest
target: x86_64-pc-windows-msvc
- platform: windows-arm64
os: windows-11-arm
target: aarch64-pc-windows-msvc
- platform: macos-x64
os: macos-15-intel
target: x86_64-apple-darwin
- platform: macos-arm64
os: macos-latest
target: aarch64-apple-darwin
- platform: linux-x64
os: ubuntu-latest
target: x86_64-unknown-linux-gnu
- platform: linux-arm64
os: ubuntu-24.04-arm
target: aarch64-unknown-linux-gnu
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
# Windows and macOS builds using cargo-packager
- name: Build with cargo-packager (Windows/macOS)
if: runner.os != 'Linux'
working-directory: desktop
run: |
cargo install cargo-packager --locked
cargo packager --release
- name: Upload Windows/macOS artifacts
if: runner.os != 'Linux'
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.platform }}-artifacts
path: |
dist/*.dmg
dist/*.msi
dist/*.exe
if-no-files-found: error
# Linux builds using custom scripts
- name: Install Linux build dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y flatpak flatpak-builder snapd squashfs-tools jq gettext-base
- name: Install Snapcraft
if: runner.os == 'Linux'
run: sudo snap install snapcraft --classic
- name: Make scripts executable
if: runner.os == 'Linux'
run: |
chmod +x script/get-crate-version
chmod +x script/linux
chmod +x script/bundle-snap
chmod +x script/bundle-linux
chmod +x script/flatpak/deps
chmod +x script/flatpak/bundle-flatpak
- name: Install required dependencies
if: runner.os == 'Linux'
run: ./script/linux
# Build the release tarball on every Linux architecture
- name: Build release tarball
if: runner.os == 'Linux'
run: ./script/bundle-linux
# Only build Flatpak and Snap for x86_64 (most common use case)
- name: Build Flatpak
if: runner.os == 'Linux' && matrix.target == 'x86_64-unknown-linux-gnu'
run: |
./script/flatpak/deps
./script/flatpak/bundle-flatpak
- name: Build Snap
if: runner.os == 'Linux' && matrix.target == 'x86_64-unknown-linux-gnu'
run: |
VERSION=$(script/get-crate-version signed)
./script/bundle-snap $VERSION
- name: Collect Linux artifacts
if: runner.os == 'Linux'
working-directory: ${{ github.workspace }}
run: |
mkdir -p linux-artifacts
# Copy the tarball created by bundle-linux
find target/release -name "*.tar.gz" -exec cp {} linux-artifacts/ \;
# Find and copy flatpak files (if they exist)
find . -name "*.flatpak" -exec cp {} linux-artifacts/ \; || true
# Find and copy snap files (if they exist)
find . -name "*.snap" -exec cp {} linux-artifacts/ \; || true
ls -la linux-artifacts/
- name: Upload Linux artifacts
if: runner.os == 'Linux'
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.platform }}-artifacts
path: linux-artifacts/**/*
if-no-files-found: error
release:
name: Create Release
needs: build
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Make get-crate-version executable
run: chmod +x script/get-crate-version
- name: Get version
id: version
run: |
VERSION=$(script/get-crate-version signed)
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "tag=v$VERSION" >> $GITHUB_OUTPUT
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Display artifacts structure
run: |
echo "Artifacts structure:"
find artifacts -type f -exec ls -la {} \;
- name: Create draft release
id: create_release
uses: akkuman/gitea-release-action@v1
with:
server_url: "https://git.reya.su/"
repository: "reya/signed"
token: ${{ secrets.GITEA_TOKEN }}
draft: true
prerelease: false
files: |
artifacts/**/*
- name: Output release info
run: |
echo "Created draft release: ${{ steps.create_release.outputs.url }}"
echo "Release ID: ${{ steps.create_release.outputs.id }}"
+32
View File
@@ -0,0 +1,32 @@
name: Rust
on:
push:
branches: ["**"]
pull_request:
branches: ["m**"]
env:
CARGO_TERM_COLOR: always
jobs:
build:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
rustup: [stable]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install Linux build dependencies
run: chmod +x ./script/linux && ./script/linux
if: matrix.os == 'ubuntu-latest'
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose
+20 -1
View File
@@ -1 +1,20 @@
/target
# Generated by Cargo
# will have compiled files and executables
debug/
target/
dist/
# Snap and Flatpak local build output
/snap
/su.reya.signed.json
/linux-artifacts
# Vendored dependencies + cargo config generated by script/prepare-flathub
.cargo/
vendor/
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# macOS
.DS_Store
+174
View File
@@ -0,0 +1,174 @@
# Rust coding guidelines
* Prioritize code correctness and clarity. Speed and efficiency are secondary priorities unless otherwise specified.
* Do not write organizational or comments that summarize the code. Comments should only be written in order to explain "why" the code is written in some way in the case there is a reason that is tricky / non-obvious.
* Prefer implementing functionality in existing files unless it is a new logical component. Avoid creating many small files.
* Avoid using functions that panic like `unwrap()`, instead use mechanisms like `?` to propagate errors.
* Be careful with operations like indexing which may panic if the indexes are out of bounds.
* Never silently discard errors with `let _ =` on fallible operations. Always handle errors appropriately:
- Propagate errors with `?` when the calling function should handle them
- Use `.log_err()` or similar when you need to ignore errors but want visibility
- Use explicit error handling with `match` or `if let Err(...)` when you need custom logic
- Example: avoid `let _ = client.request(...).await?;` - use `client.request(...).await?;` instead
* When implementing async operations that may fail, ensure errors propagate to the UI layer so users get meaningful feedback.
* Avoid creative additions unless explicitly requested
* Use full words for variable names (no abbreviations like "q" for "queue")
* Use variable shadowing to scope clones in async contexts for clarity, minimizing the lifetime of borrowed references.
Example:
```rust
executor.spawn({
let task_ran = task_ran.clone();
async move {
*task_ran.borrow_mut() = true;
}
});
```
# Timers in tests
* In GPUI tests, prefer GPUI executor timers over `smol::Timer::after(...)` when you need timeouts, delays, or to drive `run_until_parked()`:
- Use `cx.background_executor().timer(duration).await` (or `cx.background_executor.timer(duration).await` in `TestAppContext`) so the work is scheduled on GPUI's dispatcher.
- Avoid `smol::Timer::after(...)` for test timeouts when you rely on `run_until_parked()`, because it may not be tracked by GPUI's scheduler and can lead to "nothing left to run" when pumping.
# GPUI
GPUI is a UI framework which also provides primitives for state and concurrency management.
## Context
Context types allow interaction with global state, windows, entities, and system services. They are typically passed to functions as the argument named `cx`. When a function takes callbacks they come after the `cx` parameter.
* `App` is the root context type, providing access to global state and read and update of entities.
* `Context<T>` is provided when updating an `Entity<T>`. This context dereferences into `App`, so functions which take `&App` can also take `&Context<T>`.
* `AsyncApp` and `AsyncWindowContext` are provided by `cx.spawn` and `cx.spawn_in`. These can be held across await points.
## `Window`
`Window` provides access to the state of an application window. It is passed to functions as an argument named `window` and comes before `cx` when present. It is used for managing focus, dispatching actions, directly drawing, getting user input state, etc.
## Entities
An `Entity<T>` is a handle to state of type `T`. With `thing: Entity<T>`:
* `thing.entity_id()` returns `EntityId`
* `thing.downgrade()` returns `WeakEntity<T>`
* `thing.read(cx: &App)` returns `&T`.
* `thing.read_with(cx, |thing: &T, cx: &App| ...)` returns the closure's return value.
* `thing.update(cx, |thing: &mut T, cx: &mut Context<T>| ...)` allows the closure to mutate the state, and provides a `Context<T>` for interacting with the entity. It returns the closure's return value.
* `thing.update_in(cx, |thing: &mut T, window: &mut Window, cx: &mut Context<T>| ...)` takes a `AsyncWindowContext` or `VisualTestContext`. It's the same as `update` while also providing the `Window`.
Within the closures, the inner `cx` provided to the closure must be used instead of the outer `cx` to avoid issues with multiple borrows.
Trying to update an entity while it's already being updated must be avoided as this will cause a panic.
`WeakEntity<T>` is a weak handle. It has `read_with`, `update`, and `update_in` methods that work the same, but always return an `anyhow::Result` so that they can fail if the entity no longer exists. This can be useful to avoid memory leaks - if entities have mutually recursive handles to each other they will never be dropped.
## Concurrency
All use of entities and UI rendering occurs on a single foreground thread.
`cx.spawn(async move |cx| ...)` runs an async closure on the foreground thread. Within the closure, `cx` is `&mut AsyncApp`.
When the outer cx is a `Context<T>`, the use of `spawn` instead looks like `cx.spawn(async move |this, cx| ...)`, where `this: WeakEntity<T>` and `cx: &mut AsyncApp`.
To do work on other threads, `cx.background_spawn(async move { ... })` is used. Often this background task is awaited on by a foreground task which uses the results to update state.
Both `cx.spawn` and `cx.background_spawn` return a `Task<R>`, which is a future that can be awaited upon. If this task is dropped, then its work is cancelled. To prevent this one of the following must be done:
* Awaiting the task in some other async context.
* Detaching the task via `task.detach()` or `task.detach_and_log_err(cx)`, allowing it to run indefinitely.
* Storing the task in a field, if the work should be halted when the struct is dropped.
A task which doesn't do anything but provide a value can be created with `Task::ready(value)`.
## Elements
The `Render` trait is used to render some state into an element tree that is laid out using flexbox layout. An `Entity<T>` where `T` implements `Render` is sometimes called a "view".
Example:
```
struct TextWithBorder(SharedString);
impl Render for TextWithBorder {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().border_1().child(self.0.clone())
}
}
```
Since `impl IntoElement for SharedString` exists, it can be used as an argument to `child`. `SharedString` is used to avoid copying strings, and is either an `&'static str` or `Arc<str>`.
UI components that are constructed just to be turned into elements can instead implement the `RenderOnce` trait, which is similar to `Render`, but its `render` method takes ownership of `self` and receives `&mut App` instead of `&mut Context<Self>`. Types that implement this trait can use `#[derive(IntoElement)]` to use them directly as children.
The style methods on elements are similar to those used by Tailwind CSS.
If some attributes or children of an element tree are conditional, `.when(condition, |this| ...)` can be used to run the closure only when `condition` is true. Similarly, `.when_some(option, |this, value| ...)` runs the closure when the `Option` has a value.
## Input events
Input event handlers can be registered on an element via methods like `.on_click(|event, window, cx: &mut App| ...)`.
Often event handlers will want to update the entity that's in the current `Context<T>`. The `cx.listener` method provides this - its use looks like `.on_click(cx.listener(|this: &mut T, event, window, cx: &mut Context<T>| ...)`.
## Actions
Actions are dispatched via user keyboard interaction or in code via `window.dispatch_action(SomeAction.boxed_clone(), cx)` or `focus_handle.dispatch_action(&SomeAction, window, cx)`.
Actions with no data are defined with the `actions!(some_namespace, [SomeAction, AnotherAction])` macro call. Otherwise the `Action` derive macro is used. Doc comments on actions are displayed to the user.
Action handlers can be registered on an element via the event handler `.on_action(|action, window, cx| ...)`. Like other event handlers, this is often used with `cx.listener`.
## Notify
When a view's state has changed in a way that may affect its rendering, it should call `cx.notify()`. This will cause the view to be rerendered. It will also cause any observe callbacks registered for the entity with `cx.observe` to be called.
## Entity events
While updating an entity (`cx: Context<T>`), it can emit an event using `cx.emit(event)`. Entities register which events they can emit by declaring `impl EventEmitter<EventType> for EntityType {}`.
Other entities can then register a callback to handle these events by doing `cx.subscribe(other_entity, |this, other_entity, event, cx| ...)`. This will return a `Subscription` which deregisters the callback when dropped. Typically `cx.subscribe` happens when creating a new entity and the subscriptions are stored in a `_subscriptions: Vec<Subscription>` field.
# Pull request hygiene
When an agent opens or updates a pull request, it must:
- Use a clear, correctly capitalized, imperative PR title (for example, `Fix crash in project panel`).
- Avoid conventional commit prefixes in PR titles (`fix:`, `feat:`, `docs:`, etc.).
- Avoid trailing punctuation in PR titles.
- Optionally prefix the title with a crate name when one crate is the clear scope (for example, `git_ui: Add history view`).
- Include a `Release Notes:` section as the final section in the PR body.
- Use one bullet under `Release Notes:`:
- `- Added ...`, `- Fixed ...`, or `- Improved ...` for user-facing changes, or
- `- N/A` for docs-only and other non-user-facing changes.
- Format release notes exactly with a blank line after the heading, for example:
```
Release Notes:
- N/A
```
# Rules Hygiene
These `.rules` files are read by every agent session. Keep them high-signal.
## After any agentic session
If you discover a non-obvious pattern that would help future sessions, include a **"Suggested .rules additions"** heading in your PR description with the proposed text. Do **not** edit `.rules` inline during normal feature/fix work. Reviewers decide what gets merged.
## High bar for new rules
Editing or clarifying existing rules is always welcome. New rules must meet **all three** criteria:
1. **Non-obvious** — someone familiar with the codebase would still get it wrong without the rule.
2. **Repeatedly encountered** — it came up more than once (multiple hits in one session counts).
3. **Specific enough to act on** — a concrete instruction, not a vague principle.
Rules that apply to a single crate belong in that crate's own `.rules` file, not the repo root.
## What NOT to put in `.rules`
Avoid architectural descriptions of a crate (module layout, data flow, key types). These go stale fast and the agent can gather them by reading the code. Rules should be **traps to avoid**, not **maps to follow**.
## No drive-by additions
Rules emerge from validated patterns, not one-off observations. The workflow is:
1. Agent notes a pattern during a session.
2. Team validates the pattern in code review.
3. A dedicated commit adds the rule with context on *why* it exists.
+1
View File
@@ -0,0 +1 @@
.rules
Generated
+383 -314
View File
File diff suppressed because it is too large Load Diff
+6 -8
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "desktop"]
default-members = ["desktop"]
[workspace.package]
version = "1.0.0"
version = "0.1.0-alpha"
edition = "2024"
publish = false
@@ -15,11 +15,9 @@ gpui_platform = { git = "https://github.com/zed-industries/zed", features = ["fo
gpui_tokio = { git = "https://github.com/zed-industries/zed" }
reqwest_client = { git = "https://github.com/zed-industries/zed" }
# `tree-sitter-languages` enables syntax highlighting for the TextView
# code preview (fenced code blocks are highlighted with tree-sitter).
gpui-component = { git = "https://github.com/longbridge/gpui-component", features = ["tree-sitter-languages"] }
gpui-base = { git = "https://github.com/longbridge/gpui-component" }
gpui-fps = { git = "https://github.com/longbridge/gpui-component" }
# GPUI Kit
gpui-component = { git = "https://github.com/longbridge/gpui-component", rev = "39c2c86dbee7ad445591462f8675f74082e10828", features = ["tree-sitter-languages"], }
gpui-base = { git = "https://github.com/longbridge/gpui-component", rev = "39c2c86dbee7ad445591462f8675f74082e10828" }
dock = { path = "crates/dock" }
settings = { path = "crates/settings" }
@@ -32,7 +30,7 @@ nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" }
nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
gix = { version = "0.87.1", default-features = false, features = ["sha1", "blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation"] }
gix = { version = "0.87.1", default-features = false, features = ["sha1", "blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation", "status"] }
smol = "2"
futures = "0.3"
@@ -58,7 +56,7 @@ strip = true
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
panic = "unwind"
[profile.profiling]
inherits = "release"
+1 -64
View File
@@ -39,12 +39,7 @@ impl Assets {
.filter_map(|path| {
let data = Self::get(path.as_ref())?;
let name = path.strip_prefix("themes/").unwrap_or(path.as_ref());
let content = match data.data {
std::borrow::Cow::Borrowed(bytes) => {
std::str::from_utf8(bytes).ok()?.to_owned()
}
std::borrow::Cow::Owned(bytes) => String::from_utf8(bytes).ok()?,
};
let content = std::str::from_utf8(data.data.as_ref()).ok()?.to_owned();
Some((name.to_owned(), content))
})
.collect()
@@ -111,61 +106,3 @@ impl IconNamed for CustomIconName {
.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn signed_theme_set() -> gpui_component::ThemeSet {
let themes = Assets.themes();
assert_eq!(themes.len(), 1, "expected exactly one embedded theme file");
let (name, content) = &themes[0];
assert_eq!(name, "signed.json");
serde_json::from_str(content).expect("theme file must be a valid ThemeSet")
}
#[test]
fn signed_theme_set_parses() {
let set = signed_theme_set();
let names: Vec<&str> = set.themes.iter().map(|t| t.name.as_ref()).collect();
assert_eq!(names, vec!["Signed Light", "Signed Dark"]);
}
#[test]
fn signed_theme_palette_applies() {
let set = signed_theme_set();
let parse = |hex: &str| gpui_component::try_parse_color(hex).unwrap();
for config in &set.themes {
let mut theme = gpui_component::Theme::default();
theme.apply_config(&std::rc::Rc::new(config.clone()));
assert_eq!(theme.mode, config.mode);
// The resolved colors must match the brand palette.
assert_eq!(theme.primary, parse("#C6FF4D")); // nostr-lime
assert_eq!(theme.success, parse("#2FBF71")); // merge
assert_eq!(theme.primary_active, parse("#65A30D")); // lime-600
if config.mode.is_dark() {
// Dark theme chrome is neutral, mirroring the light theme.
assert_eq!(theme.background, parse("#0A0A0A")); // neutral-950
assert_eq!(theme.border, parse("#27272A")); // neutral-800
assert_eq!(theme.green, parse("#22C55E")); // green-500
} else {
// Light theme chrome is neutral, lime is a brand accent only.
assert_eq!(theme.background, parse("#FFFFFF"));
assert_eq!(theme.foreground, parse("#18181B"));
assert_eq!(theme.border, parse("#E4E4E7"));
assert_eq!(theme.green, parse("#16A34A"));
}
// Active tab, a paler lime on light and a dim moss on dark.
// Each is paired with readable contrasting text.
if config.mode.is_dark() {
assert_eq!(theme.tab_active, parse("#19200A")); // dim lime
assert_eq!(theme.tab_active_foreground, parse("#C6FF4D")); // nostr-lime
} else {
assert_eq!(theme.tab_active, parse("#EBFFC1")); // pale nostr-lime
assert_eq!(theme.tab_active_foreground, parse("#3F6212")); // deep-lime
}
}
}
}
+5 -18
View File
@@ -15,7 +15,7 @@ use gpui_base::dock::{
};
use gpui_base::resize_handle;
use gpui_component::scroll::ScrollbarMode;
use gpui_component::{ActiveTheme as _, Side, StyledExt as _};
use gpui_component::{ActiveTheme as _, Side};
use crate::invalid_panel::InvalidPanel;
use crate::tab_panel::SignedTabGroupSkin;
@@ -105,6 +105,7 @@ impl SignedDockSkin {
}
/// Payload a dock's resize handle drags.
///
/// It draws nothing, the handle element is the visible affordance.
#[derive(Clone)]
struct ResizePanel;
@@ -154,27 +155,13 @@ impl DockAreaRenderer for SignedDockSkin {
cx: &mut App,
) -> AnyElement {
let placement = dock.placement();
let open = dock.is_open();
// A closed left or right dock takes no space.
// A closed bottom dock keeps a strip so its tab bar stays clickable.
if !open && !placement.is_bottom() {
return div().into_any_element();
}
div()
.flex()
.flex_none()
.size_full()
.relative()
.overflow_hidden()
.map(|this| match placement {
DockPlacement::Left | DockPlacement::Right => this.h_flex().h_full().w(dock.size()),
DockPlacement::Bottom => this.w_full().h(dock.size()),
// Base never builds a dock for the centre.
DockPlacement::Center => this,
})
// The closed bottom dock's strip is the tab bar itself, a full tab bar tall.
.when(!open && placement.is_bottom(), |this| {
// A closed bottom dock keeps a strip, and that strip is the tab bar.
.when(!dock.is_open() && placement.is_bottom(), |this| {
this.h(TAB_BAR_HEIGHT)
})
.child(content)
+13
View File
@@ -26,6 +26,19 @@ pub fn add_center_panel(
area.add_panel_view(panel, DockPlacement::Center, None, window, cx);
}
/// Add an already-wrapped panel handle to the bottom dock of `area`.
///
/// Used for sub-views that hang under the center, such as the inbox's Unread
/// and Archived lists.
pub fn add_bottom_panel(
area: &mut DockArea,
panel: Arc<dyn PanelView>,
window: &mut Window,
cx: &mut Context<DockArea>,
) {
area.add_panel_view(panel, DockPlacement::Bottom, None, window, cx);
}
/// The fixed height of the tab bar, which doubles as the window title bar.
pub const TAB_BAR_HEIGHT: Pixels = px(44.);
+1 -1
View File
@@ -198,7 +198,7 @@ impl SignedTabGroupSkin {
DockPlacement::Bottom => area
.layout(DockPlacement::Bottom)
.and_then(|tree| left_top_group(tree.root())),
DockPlacement::Center => None,
DockPlacement::Center => return None,
};
if designated != Some(group.node()) {
return None;
-1
View File
@@ -59,7 +59,6 @@ impl SignedTilesSkin {
}
}
/// One edge or corner handle.
fn resize_handle(
&self,
tile: &TileContext,
-1
View File
@@ -7,7 +7,6 @@ use gpui_component::{ActiveTheme, Icon, IconName, Sizable as _, h_flex};
use crate::TAB_BAR_HEIGHT;
/// The standard width of a window control button.
const CONTROL_WIDTH: f32 = 34.;
#[derive(IntoElement, Clone)]
+9 -5
View File
@@ -2,10 +2,12 @@ use std::path::PathBuf;
use std::sync::OnceLock;
/// The application name.
///
/// It derives the platform-specific data, config and cache directory paths.
pub const APP_NAME: &str = "Signed";
/// Lowercased form of [`APP_NAME`].
///
/// Used in XDG-style paths on Linux and FreeBSD, and the macOS `~/.config` fallback.
pub const APP_NAME_LOWERCASE: &str = "signed";
@@ -21,24 +23,24 @@ static CURRENT_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();
/// On Windows, this is `%APPDATA%\Signed`.
static CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
/// Returns the current user's home directory.
pub fn home_dir() -> PathBuf {
dirs::home_dir().expect("failed to determine home directory")
}
/// Returns the current user's Desktop folder.
///
/// Falls back to the home directory or an empty path when it cannot be determined.
pub fn desktop_dir() -> PathBuf {
dirs::desktop_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_default())
}
/// Returns the current user's Documents folder.
///
/// Falls back to the home directory or an empty path when it cannot be determined.
pub fn documents_dir() -> PathBuf {
dirs::document_dir().unwrap_or_else(|| dirs::home_dir().unwrap_or_default())
}
/// Returns the path to the configuration directory.
pub fn config_dir() -> &'static PathBuf {
CONFIG_DIR.get_or_init(|| {
if cfg!(target_os = "windows") {
@@ -58,7 +60,6 @@ pub fn config_dir() -> &'static PathBuf {
})
}
/// Returns the path to the data directory.
pub fn data_dir() -> &'static PathBuf {
CURRENT_DATA_DIR.get_or_init(|| {
if cfg!(target_os = "macos") {
@@ -89,12 +90,15 @@ pub fn nostr_dir() -> &'static PathBuf {
}
/// Returns the path to the local git clone cache, the grasp mirrors.
///
/// The mirrors are disposable and re-cloned from their grasp server on
/// demand, so the cache lives in the OS temp directory for the system to
/// reclaim.
pub fn repos_dir() -> &'static PathBuf {
static REPOS_DIR: OnceLock<PathBuf> = OnceLock::new();
REPOS_DIR.get_or_init(|| data_dir().join("repos"))
REPOS_DIR.get_or_init(|| std::env::temp_dir().join(APP_NAME_LOWERCASE).join("repos"))
}
/// Returns the path to the `settings.json` file.
pub fn settings_file() -> &'static PathBuf {
static SETTINGS_FILE: OnceLock<PathBuf> = OnceLock::new();
SETTINGS_FILE.get_or_init(|| config_dir().join("settings.json"))
+2 -67
View File
@@ -2,29 +2,23 @@ use std::path::PathBuf;
use serde::{Deserialize, Serialize};
/// The default grasp servers,
/// offered while the user has not published a grasp list.
/// The default grasp servers, offered while the user has not published a grasp list.
pub const DEFAULT_GRASP_SERVERS: [&str; 3] = [
"wss://relay.ngit.dev",
"wss://gitnostr.com",
"wss://git.shakespeare.diy",
];
/// How the application picks its appearance.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AppearanceMode {
/// Follow the system appearance, light or dark, at runtime.
#[default]
System,
/// Always use the light theme.
Light,
/// Always use the dark theme.
Dark,
}
/// Theme configuration,
/// fields mirror the gpui-component `Theme` surface customized at startup.
/// Fields mirror the gpui-component `Theme` surface customized at startup.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ThemeSettings {
@@ -42,7 +36,6 @@ pub struct ThemeSettings {
pub radius_lg: f32,
/// Whether focused controls draw a ring outside their border.
pub focus_ring: bool,
/// Whether to render shadows.
pub shadow: bool,
}
@@ -61,7 +54,6 @@ impl Default for ThemeSettings {
}
}
/// Default grasp server settings.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GraspServersSettings {
@@ -80,7 +72,6 @@ impl Default for GraspServersSettings {
}
}
/// Local repository scanning.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct LocalReposSettings {
@@ -108,7 +99,6 @@ impl Default for LocalReposSettings {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct CheckoutRecord {
/// Local folder of the checkout.
pub path: PathBuf,
/// Repository address as a string, `30617:<pubkey>:<id>`.
pub addr: String,
@@ -116,16 +106,13 @@ pub struct CheckoutRecord {
pub last_used: u64,
}
/// Remembered local checkouts, see [`CheckoutRecord`].
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CheckoutsSettings {
/// The remembered records.
/// The latest use of a path and repo pair replaces the older record.
pub records: Vec<CheckoutRecord>,
}
/// The create-repository dialog.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CreateRepositorySettings {
@@ -137,17 +124,11 @@ pub struct CreateRepositorySettings {
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
/// How the application picks its appearance.
pub appearance: AppearanceMode,
/// Theme configuration.
pub theme: ThemeSettings,
/// Default grasp servers.
pub grasp_servers: GraspServersSettings,
/// Local repository scanning.
pub local_repos: LocalReposSettings,
/// Remembered local checkouts.
pub checkouts: CheckoutsSettings,
/// The create-repository dialog.
pub create_repository: CreateRepositorySettings,
}
@@ -155,30 +136,6 @@ pub struct Settings {
mod tests {
use super::*;
#[test]
fn defaults_match_the_app_conventions() {
let settings = Settings::default();
assert_eq!(settings.appearance, AppearanceMode::System);
assert_eq!(settings.theme.light_theme, "Signed Light");
assert_eq!(settings.theme.dark_theme, "Signed Dark");
assert_eq!(settings.theme.font_size, 16.0);
assert_eq!(settings.theme.mono_font_size, 13.0);
assert_eq!(settings.theme.radius, 2.0);
assert_eq!(settings.theme.radius_lg, 6.0);
assert!(!settings.theme.focus_ring);
assert!(!settings.theme.shadow);
assert_eq!(
settings.grasp_servers.default_servers,
DEFAULT_GRASP_SERVERS.map(String::from).to_vec()
);
assert_eq!(settings.local_repos.scan_paths.len(), 2);
assert_eq!(
settings.local_repos.scan_paths,
vec![paths::desktop_dir(), paths::documents_dir()]
);
assert_eq!(settings.create_repository.default_folder, None);
}
#[test]
fn json_roundtrip_preserves_everything() {
let settings = Settings {
@@ -198,12 +155,6 @@ mod tests {
assert_eq!(parsed, settings);
}
#[test]
fn missing_keys_fall_back_to_defaults() {
let settings: Settings = serde_json::from_str("{}").unwrap();
assert_eq!(settings, Settings::default());
}
#[test]
fn partial_json_merges_with_defaults() {
let settings: Settings =
@@ -215,20 +166,4 @@ mod tests {
assert_eq!(settings.grasp_servers, GraspServersSettings::default());
assert_eq!(settings.create_repository.default_folder, None);
}
#[test]
fn appearance_serializes_to_snake_case_names() {
assert_eq!(
serde_json::to_string(&AppearanceMode::System).unwrap(),
"\"system\""
);
assert_eq!(
serde_json::to_string(&AppearanceMode::Light).unwrap(),
"\"light\""
);
assert_eq!(
serde_json::to_string(&AppearanceMode::Dark).unwrap(),
"\"dark\""
);
}
}
-30
View File
@@ -24,7 +24,6 @@ impl SettingsStore {
cx.global::<GlobalSettingsStore>().0.clone()
}
/// Install the store as a global.
pub fn set_global(entity: Entity<Self>, cx: &mut App) {
cx.set_global(GlobalSettingsStore(entity));
}
@@ -103,8 +102,6 @@ impl SettingsStore {
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use gpui::{AppContext, TestAppContext};
use super::*;
static TEST_FILE_COUNTER: AtomicUsize = AtomicUsize::new(0);
@@ -133,16 +130,6 @@ mod tests {
cleanup(&path);
}
#[test]
fn corrupt_file_loads_defaults() {
let path = temp_settings_path();
std::fs::write(&path, "{ not json").unwrap();
let settings = SettingsStore::load(&path);
assert_eq!(settings, Settings::default());
cleanup(&path);
}
#[test]
fn save_and_load_roundtrip() {
let path = temp_settings_path();
@@ -160,21 +147,4 @@ mod tests {
assert_eq!(SettingsStore::load(&path), expected);
cleanup(&path);
}
#[gpui::test]
fn edit_mutates_and_persists(cx: &mut TestAppContext) {
let path = temp_settings_path();
cleanup(&path);
let store = cx.update(|cx| cx.new(|cx| SettingsStore::new(path.clone(), cx)));
cx.read(|cx| assert_eq!(store.read(cx).settings(), &Settings::default()));
store.update(cx, |store, cx| {
store.edit(|settings| settings.theme.radius = 12.0, cx);
});
cx.read(|cx| assert_eq!(store.read(cx).settings().theme.radius, 12.0));
assert_eq!(SettingsStore::load(&path).theme.radius, 12.0);
cleanup(&path);
}
}
+1 -1
View File
@@ -5,5 +5,5 @@ edition.workspace = true
publish.workspace = true
[dependencies]
gpui.workspace = true
nostr.workspace = true
serde.workspace = true
-16
View File
@@ -6,12 +6,10 @@ use nostr::prelude::*;
/// the alias reuses the SDK type while keeping repository-specific vocabulary.
pub type RepoAddr = Coordinate;
/// Build the address of a NIP-34 repository announcement.
pub fn repo_addr(owner: PublicKey, id: impl Into<String>) -> RepoAddr {
Coordinate::new(Kind::GitRepoAnnouncement, owner).identifier(id)
}
/// Derive a repository identifier from a display name
pub fn identifier_from_name(name: &str) -> String {
name.chars()
.map(|c| {
@@ -23,17 +21,3 @@ pub fn identifier_from_name(name: &str) -> String {
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identifier_from_name_slugs_like_gitworkshop() {
assert_eq!(identifier_from_name("My Repo"), "My-Repo");
assert_eq!(identifier_from_name("my-repo"), "my-repo");
assert_eq!(identifier_from_name("Foo_Bar!"), "Foo-Bar-");
assert_eq!(identifier_from_name("a/b"), "a/b");
assert_eq!(identifier_from_name("Café"), "Caf-");
}
}
-303
View File
@@ -5,306 +5,3 @@ use nostr::prelude::*;
/// A markdown note attached to an issue, patch or PR by its author or a maintainer,
/// not part of the NIP-34 draft, read support for interop.
pub const COVER_NOTE_KIND: Kind = Kind::Custom(1624);
/// Whether a kind-1985 label event is a valid annotation of `root`.
///
/// The event references the root with a lowercase `e` tag,
/// its author must be the root author or a maintainer.
fn label_targets_root(event: &Event, root: &Event, maintainers: &[PublicKey]) -> bool {
if event.kind != Kind::Label {
return false;
}
if event.pubkey != root.pubkey && !maintainers.contains(&event.pubkey) {
return false;
}
let root_id = root.id.to_hex();
event
.tags
.iter()
.any(|tag| tag.kind() == "e" && tag.content().is_some_and(|content| content == root_id))
}
/// Whether a kind-1985 label event declares the `#t` namespace,
/// it must also carry at least one `["l", "<value>", "#t"]` label.
fn has_hashtag_labels(event: &Event) -> bool {
event.tags.iter().any(|tag| tag.as_slice() == ["L", "#t"])
&& event.tags.iter().any(|tag| {
let slice = tag.as_slice();
slice.len() >= 3 && slice[0] == "l" && slice[2] == "#t" && !slice[1].is_empty()
})
}
/// Effective hashtag labels of `root`,
/// the `t` tags on the event itself, self-reported by its author,
/// authorized NIP-32 kind-1985 events in the `#t` namespace add more.
///
/// Labels are additive, so all valid label events contribute,
/// there is no latest-wins semantics.
pub fn labels(root: &Event, label_events: &[Event], maintainers: &[PublicKey]) -> Vec<String> {
let mut labels: Vec<String> = root
.tags
.hashtags()
.map(|hashtag| hashtag.to_string())
.collect();
for event in label_events {
if !label_targets_root(event, root, maintainers) || !has_hashtag_labels(event) {
continue;
}
for tag in event.tags.iter() {
let slice = tag.as_slice();
if slice.len() >= 3 && slice[0] == "l" && slice[2] == "#t" && !slice[1].is_empty() {
let label = &slice[1];
if !labels.contains(label) {
labels.push(label.clone());
}
}
}
}
labels
}
/// Subject or title override of `root` from authorized kind-1985 label events,
/// only label events in the `#subject` namespace count.
///
/// Returns `None` when no valid override exists.
pub fn subject_override(
root: &Event,
label_events: &[Event],
maintainers: &[PublicKey],
) -> Option<String> {
label_events
.iter()
.filter(|event| label_targets_root(event, root, maintainers))
.filter(|event| {
event
.tags
.iter()
.any(|tag| tag.as_slice() == ["L", "#subject"])
&& event.tags.iter().any(|tag| {
let slice = tag.as_slice();
slice.len() >= 3
&& slice[0] == "l"
&& slice[2] == "#subject"
&& !slice[1].is_empty()
})
})
.max_by(|a, b| {
a.created_at
.cmp(&b.created_at)
.then_with(|| a.id.to_string().cmp(&b.id.to_string()))
})
.and_then(|event| {
event.tags.iter().find_map(|tag| {
let slice = tag.as_slice();
(slice.len() >= 3
&& slice[0] == "l"
&& slice[2] == "#subject"
&& !slice[1].is_empty())
.then(|| slice[1].clone())
})
})
}
/// Effective hashtag labels and subject override of `root` in one pass,
/// mirrors ngit's `get_labels_and_subject`.
pub fn labels_and_subject(
root: &Event,
label_events: &[Event],
maintainers: &[PublicKey],
) -> (Vec<String>, Option<String>) {
(
labels(root, label_events, maintainers),
subject_override(root, label_events, maintainers),
)
}
/// Effective cover note of `root`.
///
/// Returns `None` when no valid cover note exists.
pub fn cover_note<'a>(
root: &Event,
cover_notes: &'a [Event],
maintainers: &[PublicKey],
) -> Option<&'a Event> {
let root_id = root.id.to_hex();
cover_notes
.iter()
.filter(|event| {
event.kind == COVER_NOTE_KIND
&& (event.pubkey == root.pubkey || maintainers.contains(&event.pubkey))
&& event.tags.iter().any(|tag| {
tag.kind() == "e" && tag.content().is_some_and(|content| content == root_id)
})
})
.max_by(|a, b| {
a.created_at
.cmp(&b.created_at)
.then_with(|| a.id.to_string().cmp(&b.id.to_string()))
})
}
#[cfg(test)]
mod tests {
use super::*;
fn keys_from_hex(hex: &str) -> Keys {
Keys::new(SecretKey::from_hex(hex).expect("valid secret key"))
}
fn signed(author: &Keys, kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
EventBuilder::new(kind, "")
.tags(tags)
.custom_created_at(Timestamp::from(created_at))
.finalize(author)
.expect("signed event")
}
fn root_event() -> Event {
signed(
&keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001"),
Kind::GitIssue,
vec![Tag::hashtag("bug")],
100,
)
}
fn e_tag(event: &Event) -> Tag {
Tag::parse(["e", &event.id.to_hex()]).expect("valid e tag")
}
#[test]
fn labels_take_inline_hashtags_and_external_label_events() {
let root = root_event();
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let labels_event = signed(
&maintainer,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["L", "#t"]).expect("valid L tag"),
Tag::parse(["l", "help-wanted", "#t"]).expect("valid l tag"),
],
200,
);
let labels = labels(&root, &[labels_event], &[maintainer.public_key()]);
assert_eq!(labels, vec!["bug", "help-wanted"]);
}
#[test]
fn labels_ignore_unauthorized_and_misnamed_events() {
let root = root_event();
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let stranger =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000003");
// A stranger's label event is not authorized.
let stranger_labels = signed(
&stranger,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["L", "#t"]).expect("valid L tag"),
Tag::parse(["l", "nope", "#t"]).expect("valid l tag"),
],
200,
);
// A valid author referencing a different event.
let other_labels = signed(
&maintainer,
Kind::Label,
vec![
Tag::parse([
"e",
"2222222222222222222222222222222222222222222222222222222222222222",
])
.expect("valid e tag"),
Tag::parse(["L", "#t"]).expect("valid L tag"),
Tag::parse(["l", "nope", "#t"]).expect("valid l tag"),
],
200,
);
// A valid author without the namespace declaration.
let missing_namespace = signed(
&maintainer,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["l", "nope", "#t"]).expect("valid l tag"),
],
200,
);
assert_eq!(
labels(
&root,
&[stranger_labels, other_labels, missing_namespace],
&[maintainer.public_key()]
),
vec!["bug"]
);
}
#[test]
fn subject_override_latest_authorized_event_wins() {
let root = root_event();
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let older = signed(
&maintainer,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["L", "#subject"]).expect("valid L tag"),
Tag::parse(["l", "Old title", "#subject"]).expect("valid l tag"),
],
200,
);
let newer = signed(
&maintainer,
Kind::Label,
vec![
e_tag(&root),
Tag::parse(["L", "#subject"]).expect("valid L tag"),
Tag::parse(["l", "New title", "#subject"]).expect("valid l tag"),
],
300,
);
assert_eq!(
subject_override(&root, &[newer, older], &[maintainer.public_key()]),
Some("New title".to_owned())
);
}
#[test]
fn cover_note_latest_authorized_event_wins() {
let root = root_event();
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let stranger =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000003");
let older = signed(&maintainer, COVER_NOTE_KIND, vec![e_tag(&root)], 200);
let newer = signed(&maintainer, COVER_NOTE_KIND, vec![e_tag(&root)], 300);
let unauthorized = signed(&stranger, COVER_NOTE_KIND, vec![e_tag(&root)], 400);
let newer_id = newer.id;
let events = [older, unauthorized, newer];
let maintainers = [maintainer.public_key()];
let note = cover_note(&root, &events, &maintainers);
assert_eq!(note.map(|event| event.id), Some(newer_id));
}
#[test]
fn cover_note_none_without_valid_events() {
let root = root_event();
assert_eq!(cover_note(&root, &[], &[]), None);
}
}
-116
View File
@@ -1,116 +0,0 @@
use nostr::prelude::*;
use crate::RepoAddr;
/// Target of a `nostr://` clone URL, as defined by NIP-34.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CloneTarget {
/// `nostr://<naddr1...>` encodes a direct repository address.
Addr(RepoAddr),
/// `nostr://<npub|nip05>/[relay-hint/]<identifier>`
UserRepo {
/// `npub1...` or a NIP-05 identifier.
user: String,
relay_hint: Option<RelayUrl>,
/// `d` tag identifier of the repository.
identifier: String,
},
}
/// Parse a `nostr://` clone URL. Returns `None` for other URL schemes.
pub fn parse_clone_url(url: &str) -> Option<CloneTarget> {
let rest = url.strip_prefix("nostr://")?;
let mut parts = rest.split('/');
let first = parts.next()?;
let second = parts.next()?;
let third = parts.next();
if first.starts_with("naddr1") {
let coordinate = Nip19Coordinate::from_bech32(first).ok()?;
return Some(CloneTarget::Addr(coordinate.coordinate));
}
let (relay_hint, identifier) = match third {
Some(id) => (
RelayUrl::parse(&percent_decode(second)).ok(),
percent_decode(id),
),
None => (None, percent_decode(second)),
};
Some(CloneTarget::UserRepo {
user: first.to_owned(),
relay_hint,
identifier,
})
}
fn percent_decode(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hex = &input[i + 1..i + 3];
if let Ok(v) = u8::from_str_radix(hex, 16) {
out.push(v);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_user_repo_without_relay() {
let target = parse_clone_url(
"nostr://npub15qydau2hjma6ngxkl2cyar74wzyjshvl65za5k5rl69264ar2exs5cyejr/ngit",
)
.unwrap();
assert_eq!(
target,
CloneTarget::UserRepo {
user: "npub15qydau2hjma6ngxkl2cyar74wzyjshvl65za5k5rl69264ar2exs5cyejr".to_owned(),
relay_hint: None,
identifier: "ngit".to_owned(),
}
);
}
#[test]
fn parses_user_repo_with_relay_hint() {
let target = parse_clone_url("nostr://danconwaydev.com/relay.ngit.dev/ngit").unwrap();
assert_eq!(
target,
CloneTarget::UserRepo {
user: "danconwaydev.com".to_owned(),
relay_hint: RelayUrl::parse("relay.ngit.dev").ok(),
identifier: "ngit".to_owned(),
}
);
}
#[test]
fn decodes_percent_encoded_parts() {
let target = parse_clone_url(
"nostr://danconwaydev.com/ws%3A%2F%2Flocalhost%3A7334/my-local-only-repo",
)
.unwrap();
assert_eq!(
target,
CloneTarget::UserRepo {
user: "danconwaydev.com".to_owned(),
relay_hint: RelayUrl::parse("ws://localhost:7334").ok(),
identifier: "my-local-only-repo".to_owned(),
}
);
}
}
+165 -17
View File
@@ -2,7 +2,7 @@ use std::time::Duration;
use nostr::prelude::*;
use crate::RepoAddr;
use crate::{COVER_NOTE_KIND, RepoAddr};
/// Kinds that make up the activity of a repository.
pub const ACTIVITY_KINDS: [Kind; 9] = [
@@ -17,6 +17,41 @@ pub const ACTIVITY_KINDS: [Kind; 9] = [
Kind::GitStatusDraft,
];
/// Kinds that notify a user when they tag them via their `p` tag.
pub const NOTIFICATION_KINDS: [Kind; 9] = [
Kind::GitIssue,
Kind::GitPullRequest,
Kind::GitPatch,
Kind::GitPullRequestUpdate,
COVER_NOTE_KIND,
Kind::GitStatusOpen,
Kind::GitStatusApplied,
Kind::GitStatusClosed,
Kind::GitStatusDraft,
];
/// Git root kinds that make a comment or cover note count as git activity.
const GIT_ROOT_KINDS: [Kind; 4] = [
Kind::GitIssue,
Kind::GitPatch,
Kind::GitPullRequest,
Kind::GitRepoAnnouncement,
];
/// Value of the first tag named `name` on `event`.
fn tag_value<'a>(event: &'a Event, name: &str) -> Option<&'a str> {
event
.tags
.iter()
.find(|tag| tag.kind() == name)
.and_then(|tag| tag.content())
}
/// Kind named by the first tag `name` on `event`.
fn tag_kind(event: &Event, name: &str) -> Option<Kind> {
tag_value(event, name)?.parse::<Kind>().ok()
}
/// Latest announcement event for a repository.
pub fn announcement(addr: &RepoAddr) -> Filter {
Filter::new()
@@ -56,18 +91,6 @@ pub fn statuses_for(roots: impl IntoIterator<Item = EventId>) -> Filter {
.events(roots)
}
/// Cover notes and NIP-32 label events referencing any of the given root events.
/// These are kinds 1624 and 1985, matched via the `#e` tag.
///
/// Because they carry no repository `a` tag, they are fetched by root like comments.
///
/// Batched, like [`statuses_for`].
pub fn annotations_for(roots: impl IntoIterator<Item = EventId>) -> Filter {
Filter::new()
.kinds([crate::COVER_NOTE_KIND, Kind::Label])
.events(roots)
}
/// A user's grasp list, kind `10317`.
pub fn grasp_list(public_key: PublicKey) -> Filter {
Filter::new()
@@ -94,11 +117,66 @@ pub fn comments_for(roots: impl IntoIterator<Item = EventId>) -> Vec<Filter> {
]
}
/// All repositories announced by an author.
pub fn announcements_by(public_key: PublicKey) -> Filter {
/// NIP-22 comments on our issues, patches and pull requests.
/// They are matched via the uppercase `P` and `K` tags, not authorship.
pub fn notification_comments(me: PublicKey) -> Filter {
Filter::new()
.kind(Kind::GitRepoAnnouncement)
.author(public_key)
.kind(Kind::Comment)
.custom_tags(SingleLetterTag::UPPERCASE_P, [me.to_hex()])
.custom_tags(SingleLetterTag::UPPERCASE_K, ["1621", "1617", "1618"])
}
/// Activity directed at us: comments on our roots, and git events tagging us
/// via their lowercase `p` tag. `Filter::pubkey` sets that `p` tag.
pub fn notifications(me: PublicKey) -> Vec<Filter> {
vec![
notification_comments(me),
Filter::new().kinds(NOTIFICATION_KINDS).pubkey(me),
]
}
/// Git activity authored by `me`, for "Continue where you left off".
///
/// A comment on an unrelated kind is matched too, so results must be filtered
/// through [`is_git_activity`] before display.
pub fn authored_activity(me: PublicKey) -> Filter {
Filter::new()
.kinds(
ACTIVITY_KINDS
.into_iter()
.chain(std::iter::once(COVER_NOTE_KIND)),
)
.author(me)
}
/// Whether a kind-1111 comment targets a git root, checked via its `K` tag.
fn is_git_comment(event: &Event) -> bool {
event.kind == Kind::Comment
&& tag_kind(event, "K").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
}
/// Whether a kind-1624 cover note targets a git root, checked via its `k` tag.
fn is_git_cover_note(event: &Event) -> bool {
event.kind == COVER_NOTE_KIND
&& tag_kind(event, "k").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
}
/// Whether a status event references a git root, checked via its `k` tag.
fn is_git_status(event: &Event) -> bool {
tag_kind(event, "k").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
}
/// Whether `event` is git activity worth showing in the activity list.
pub fn is_git_activity(event: &Event) -> bool {
match event.kind {
Kind::GitIssue | Kind::GitPatch | Kind::GitPullRequest => true,
Kind::Comment => is_git_comment(event),
Kind::GitStatusOpen
| Kind::GitStatusApplied
| Kind::GitStatusClosed
| Kind::GitStatusDraft => is_git_status(event),
kind => kind == COVER_NOTE_KIND && is_git_cover_note(event),
}
}
/// All repository announcements, for global discovery.
@@ -141,3 +219,73 @@ pub fn deletions_for_repo(addr: &RepoAddr) -> Vec<Filter> {
Filter::new().kind(Kind::EventDeletion).coordinate(addr),
]
}
#[cfg(test)]
mod tests {
use super::*;
fn keys(seed: u8) -> Keys {
let mut hex = "00000000000000000000000000000000000000000000000000000000000000".to_string();
hex.push_str(&format!("{seed:02x}"));
Keys::new(SecretKey::from_hex(&hex).expect("valid secret key"))
}
fn signed(author: &Keys, kind: Kind, tags: Vec<Tag>) -> Event {
EventBuilder::new(kind, "")
.tags(tags)
.finalize(author)
.expect("signed event")
}
fn kind_tag(name: &str, kind: Kind) -> Tag {
Tag::parse([name, &kind.as_u16().to_string()]).expect("valid kind tag")
}
#[test]
fn comment_activity_depends_on_the_uppercase_k_tag() {
let on_git = signed(&keys(1), Kind::Comment, vec![kind_tag("K", Kind::GitIssue)]);
let on_repo = signed(
&keys(1),
Kind::Comment,
vec![kind_tag("K", Kind::GitRepoAnnouncement)],
);
let on_note = signed(&keys(1), Kind::Comment, vec![kind_tag("K", Kind::TextNote)]);
assert!(is_git_activity(&on_git));
assert!(is_git_activity(&on_repo));
assert!(!is_git_activity(&on_note));
assert!(!is_git_activity(&signed(
&keys(1),
Kind::Comment,
Vec::new()
)));
}
#[test]
fn status_and_cover_note_activity_depend_on_the_lowercase_k_tag() {
let status = signed(
&keys(1),
Kind::GitStatusClosed,
vec![kind_tag("k", Kind::GitPullRequest)],
);
let cover = signed(
&keys(1),
COVER_NOTE_KIND,
vec![kind_tag("k", Kind::GitPatch)],
);
let unrelated = signed(
&keys(1),
Kind::GitStatusClosed,
vec![kind_tag("k", Kind::Metadata)],
);
assert!(is_git_activity(&status));
assert!(is_git_activity(&cover));
assert!(!is_git_activity(&unrelated));
assert!(!is_git_activity(&signed(
&keys(1),
Kind::GitStatusClosed,
Vec::new()
)));
}
}
+675
View File
@@ -0,0 +1,675 @@
use std::collections::{HashMap, HashSet};
use std::time::Duration;
use nostr::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{COVER_NOTE_KIND, RepoAddr, activity_subject};
/// Window before `now` that an advanced cutoff retreats to.
const ADVANCE_WINDOW: Duration = Duration::from_secs(3 * 24 * 60 * 60);
/// Window before `now` that a mark-all cutoff retreats to.
const MARK_ALL_WINDOW: Duration = Duration::from_secs(10 * 24 * 60 * 60);
/// A thread of notification and own-activity events sharing one root.
#[derive(Debug, Clone)]
pub struct InboxItem {
/// The root issue, patch or pull request the events belong to.
pub root: EventId,
/// The root event itself, when it is known locally.
pub root_event: Option<Event>,
/// Repository the root belongs to, from the root's `a` tag.
pub address: Option<RepoAddr>,
/// Notification events directed at the user, newest first.
pub events: Vec<Event>,
/// The user's own events in the thread, newest first.
pub own_events: Vec<Event>,
/// Unread event ids, oldest first.
pub unread_ids: Vec<EventId>,
/// Whether every notification event in the thread is archived.
pub archived: bool,
}
impl InboxItem {
/// Title of the thread, read from its root issue/patch/PR when known.
pub fn title(&self) -> String {
self.root_event
.as_ref()
.or_else(|| self.own_events.first())
.or_else(|| self.events.first())
.map(activity_subject)
.unwrap_or_else(|| "Untitled".to_string())
}
pub fn kind(&self) -> Option<Kind> {
self.root_event
.as_ref()
.or_else(|| self.own_events.first())
.or_else(|| self.events.first())
.map(|event| event.kind)
}
/// Timestamp of the newest event in the thread.
pub fn latest_activity(&self) -> Timestamp {
self.root_event
.as_ref()
.into_iter()
.chain(self.own_events.first())
.chain(self.events.first())
.map(|event| event.created_at)
.max()
.unwrap_or_default()
}
/// Up to `limit` events of the thread, oldest first.
pub fn timeline(&self, limit: usize) -> Vec<Event> {
let mut seen: HashSet<EventId> = HashSet::new();
let mut events: Vec<Event> = Vec::new();
if let Some(root) = &self.root_event {
seen.insert(root.id);
events.push(root.clone());
}
let mut rest: Vec<Event> = self
.own_events
.iter()
.chain(self.events.iter())
.filter(|event| seen.insert(event.id))
.cloned()
.collect();
rest.sort_by(|a, b| {
b.created_at
.cmp(&a.created_at)
.then_with(|| b.id.to_hex().cmp(&a.id.to_hex()))
});
rest.truncate(limit.saturating_sub(events.len()));
events.extend(rest);
events.sort_by_key(|event| event.created_at);
events
}
/// Whether the thread has an unread event still visible in the inbox.
pub fn is_unread(&self) -> bool {
!self.archived && !self.unread_ids.is_empty()
}
pub fn apply_state(&mut self, state: &InboxReadState) {
self.unread_ids = self
.events
.iter()
.rev()
.filter(|event| !state.is_read(event))
.map(|event| event.id)
.collect();
// A thread without notification events is never archived.
self.archived =
!self.events.is_empty() && self.events.iter().all(|event| state.is_archived(event));
}
}
/// Root issue, patch or pull request of a notification event.
///
/// Returns `None` when the event is not git-related, or when its root is a
/// coordinate rather than an event.
///
/// - issue (1621) / PR (1618): itself
/// - patch (1617): its `e` parent patch, else itself
/// - NIP-22 comment (1111): uppercase `E` root pointer
/// - PR update (1619): uppercase `E`
/// - statuses (1630-1633) / cover note (1624): NIP-10 root `e`
pub fn notification_root<L>(event: &Event, lookup: &L) -> Option<EventId>
where
L: Fn(EventId) -> Option<Event>,
{
if event.kind == COVER_NOTE_KIND {
return nip10_root_id(event).map(|root| resolve_thread_root(root, lookup));
}
match event.kind {
Kind::GitIssue | Kind::GitPullRequest => Some(event.id),
Kind::GitPatch => Some(match first_e_id(event) {
Some(parent) => resolve_thread_root(parent, lookup),
None => event.id,
}),
Kind::Comment => match nip22::extract_root(event) {
Some(CommentTarget::Event { id, .. }) => Some(resolve_thread_root(id, lookup)),
_ => None,
},
Kind::GitPullRequestUpdate => {
first_uppercase_e_id(event).map(|root| resolve_thread_root(root, lookup))
}
Kind::GitStatusOpen
| Kind::GitStatusApplied
| Kind::GitStatusClosed
| Kind::GitStatusDraft => {
nip10_root_id(event).map(|root| resolve_thread_root(root, lookup))
}
_ => None,
}
}
/// Group notification events and the user's own events into one item per thread.
pub fn group<E, O, L>(
events: E,
own: O,
me: PublicKey,
state: &InboxReadState,
lookup: &L,
) -> Vec<InboxItem>
where
E: IntoIterator<Item = Event>,
O: IntoIterator<Item = Event>,
L: Fn(EventId) -> Option<Event>,
{
let mut groups: HashMap<EventId, Vec<Event>> = HashMap::new();
for event in events {
if event.pubkey == me {
continue;
}
let Some(root) = notification_root(&event, lookup) else {
continue;
};
groups.entry(root).or_default().push(event);
}
let mut own_groups: HashMap<EventId, Vec<Event>> = HashMap::new();
for event in own {
let root = notification_root(&event, lookup).unwrap_or(event.id);
own_groups.entry(root).or_default().push(event);
}
let mut roots: Vec<EventId> = groups.keys().chain(own_groups.keys()).copied().collect();
roots.sort();
roots.dedup();
let mut items: Vec<InboxItem> = roots
.into_iter()
.map(|root| {
let mut events = groups.remove(&root).unwrap_or_default();
let mut own_events = own_groups.remove(&root).unwrap_or_default();
sort_newest_first(&mut events);
sort_newest_first(&mut own_events);
let root_event = lookup(root);
let mut item = InboxItem {
root,
address: root_event
.as_ref()
.and_then(|event| event.tags.coordinates().next()),
root_event,
events,
own_events,
unread_ids: Vec::new(),
archived: false,
};
item.apply_state(state);
item
})
.collect();
items.sort_by(|a, b| {
b.latest_activity()
.cmp(&a.latest_activity())
.then_with(|| b.root.to_hex().cmp(&a.root.to_hex()))
});
items
}
/// Sort thread events newest first, ties broken by id.
fn sort_newest_first(events: &mut [Event]) {
events.sort_by(|a, b| {
b.created_at
.cmp(&a.created_at)
.then_with(|| b.id.to_hex().cmp(&a.id.to_hex()))
});
}
/// Read and archive state of the inbox, a high-water-mark model.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct InboxReadState {
#[serde(default)]
pub read_before: Timestamp,
#[serde(default)]
pub read_ids: HashSet<EventId>,
#[serde(default)]
pub archived_before: Timestamp,
#[serde(default)]
pub archived_ids: HashSet<EventId>,
}
impl InboxReadState {
/// Whether `event` is at or before the read cutoff, or marked read.
pub fn is_read(&self, event: &Event) -> bool {
event.created_at <= self.read_before || self.read_ids.contains(&event.id)
}
/// Whether `event` is at or before the archived cutoff, or marked archived.
pub fn is_archived(&self, event: &Event) -> bool {
event.created_at <= self.archived_before || self.archived_ids.contains(&event.id)
}
/// Mark one event read. Events at or before the cutoff are already read.
pub fn mark_read(&mut self, event: &Event) {
if event.created_at > self.read_before {
self.read_ids.insert(event.id);
}
}
/// Mark one event archived. Events at or before the cutoff are already archived.
pub fn mark_archived(&mut self, event: &Event) {
if event.created_at > self.archived_before {
self.archived_ids.insert(event.id);
}
}
/// Mark every non-self event read, anchoring the cutoff ten days back.
pub fn mark_all_read(&mut self, all: &[Event], me: PublicKey, now: Timestamp) {
let cutoff = now - MARK_ALL_WINDOW;
self.read_before = cutoff;
self.read_ids = all
.iter()
.filter(|event| event.pubkey != me && event.created_at > cutoff)
.map(|event| event.id)
.collect();
}
/// Advance the read cutoff to the newest point that keeps unread events
/// unread, then prune the id set.
pub fn advance_read(&mut self, all: &[Event], me: PublicKey, now: Timestamp) {
let cutoff = advance_cutoff(all, me, now, self.read_before, |event| self.is_read(event));
self.read_before = cutoff;
prune_ids(&mut self.read_ids, all, cutoff);
}
/// Advance the archived cutoff, mirroring [`Self::advance_read`].
pub fn advance_archived(&mut self, all: &[Event], me: PublicKey, now: Timestamp) {
let cutoff = advance_cutoff(all, me, now, self.archived_before, |event| {
self.is_archived(event)
});
self.archived_before = cutoff;
prune_ids(&mut self.archived_ids, all, cutoff);
}
}
/// Newest cutoff that keeps unread events unread, never earlier than `current`.
fn advance_cutoff<M>(
all: &[Event],
me: PublicKey,
now: Timestamp,
current: Timestamp,
is_marked: M,
) -> Timestamp
where
M: Fn(&Event) -> bool,
{
let fallback = now - ADVANCE_WINDOW;
let oldest = all
.iter()
.filter(|event| event.pubkey != me && !is_marked(event))
.map(|event| event.created_at)
.min();
let candidate = match oldest {
Some(at) if at < fallback => at - 1,
_ => fallback,
};
candidate.max(current)
}
/// Drop ids whose event is unknown or now covered by the cutoff.
fn prune_ids(ids: &mut HashSet<EventId>, all: &[Event], cutoff: Timestamp) {
let created_at: HashMap<EventId, Timestamp> = all
.iter()
.map(|event| (event.id, event.created_at))
.collect();
ids.retain(|id| created_at.get(id).is_some_and(|at| *at >= cutoff));
}
/// Follow NIP-10/NIP-22 parent pointers until a root item is reached.
fn resolve_thread_root(id: EventId, lookup: &impl Fn(EventId) -> Option<Event>) -> EventId {
let mut seen = HashSet::new();
let mut root = id;
loop {
if !seen.insert(root) {
return id;
}
let Some(event) = lookup(root) else {
return root;
};
if matches!(event.kind, Kind::GitIssue | Kind::GitPullRequest) {
return root;
}
match parent_id(&event) {
Some(parent) => root = parent,
None => return root,
}
}
}
/// Parent of a thread event, mirroring gitworkshop's `getParentId`.
fn parent_id(event: &Event) -> Option<EventId> {
for marker in ["reply", "root"] {
if let Some(id) = event
.tags
.iter()
.find_map(|tag| e_tag_with_marker(tag, marker))
{
return Some(id);
}
}
if let Some(id) = event.tags.iter().find_map(|tag| {
if tag.kind() != "e" {
return None;
}
let slice = tag.as_slice();
let is_mention = slice.len() == 4 && slice[3] == "mention";
if is_mention {
return None;
}
tag.content()
.and_then(|content| EventId::from_hex(content).ok())
}) {
return Some(id);
}
first_uppercase_e_id(event)
}
/// NIP-10 root of an event: the `e` tag marked `root`, else the first `e` tag.
fn nip10_root_id(event: &Event) -> Option<EventId> {
event
.tags
.iter()
.find_map(|tag| e_tag_with_marker(tag, "root"))
.or_else(|| first_e_id(event))
}
/// First `e` tag id, in document order.
fn first_e_id(event: &Event) -> Option<EventId> {
first_tag_id(event, "e")
}
/// First uppercase `E` tag id, in document order.
fn first_uppercase_e_id(event: &Event) -> Option<EventId> {
first_tag_id(event, "E")
}
fn first_tag_id(event: &Event, name: &str) -> Option<EventId> {
event.tags.iter().find_map(|tag| {
if tag.kind() != name {
return None;
}
tag.content()
.and_then(|content| EventId::from_hex(content).ok())
})
}
/// Event id from a four-element `e` tag carrying `marker`.
fn e_tag_with_marker(tag: &Tag, marker: &str) -> Option<EventId> {
let slice = tag.as_slice();
if tag.kind() != "e" || slice.len() != 4 || slice[3] != marker {
return None;
}
tag.content()
.and_then(|content| EventId::from_hex(content).ok())
}
#[cfg(test)]
mod tests {
use super::*;
fn keys(seed: u8) -> Keys {
let mut hex = "00000000000000000000000000000000000000000000000000000000000000".to_string();
hex.push_str(&format!("{seed:02x}"));
Keys::new(SecretKey::from_hex(&hex).expect("valid secret key"))
}
fn signed(author: &Keys, kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
EventBuilder::new(kind, "")
.tags(tags)
.custom_created_at(Timestamp::from_secs(created_at))
.finalize(author)
.expect("signed event")
}
fn e_tag(event: &Event) -> Tag {
Tag::parse(["e", &event.id.to_hex()]).expect("valid e tag")
}
fn marked_e_tag(event: &Event, marker: &str) -> Tag {
Tag::parse(["e", &event.id.to_hex(), "wss://relay.example.com", marker])
.expect("valid e tag")
}
fn uppercase_e_tag(event: &Event) -> Tag {
Tag::parse(["E", &event.id.to_hex()]).expect("valid E tag")
}
fn lookup(events: &[Event]) -> impl Fn(EventId) -> Option<Event> + '_ {
move |id| events.iter().find(|event| event.id == id).cloned()
}
fn issue(author: &Keys, at: u64) -> Event {
signed(author, Kind::GitIssue, Vec::new(), at)
}
fn titled_issue(author: &Keys, title: &str, at: u64) -> Event {
signed(
author,
Kind::GitIssue,
vec![Tag::parse(["subject", title]).expect("valid subject tag")],
at,
)
}
#[test]
fn comment_resolves_to_its_uppercase_root() {
let issue = issue(&keys(1), 100);
let comment = signed(
&keys(2),
Kind::Comment,
vec![
uppercase_e_tag(&issue),
Tag::parse(["K", "1621"]).expect("valid K tag"),
],
200,
);
let events = [issue.clone(), comment.clone()];
assert_eq!(
notification_root(&comment, &lookup(&events)),
Some(issue.id)
);
}
#[test]
fn child_patch_resolves_to_the_root_patch() {
let root_patch = signed(&keys(1), Kind::GitPatch, Vec::new(), 100);
let child_patch = signed(&keys(1), Kind::GitPatch, vec![e_tag(&root_patch)], 200);
let events = [root_patch.clone(), child_patch.clone()];
assert_eq!(
notification_root(&child_patch, &lookup(&events)),
Some(root_patch.id)
);
}
#[test]
fn status_resolves_via_the_root_marker() {
let issue = issue(&keys(1), 100);
let status = signed(
&keys(2),
Kind::GitStatusClosed,
vec![marked_e_tag(&issue, "root")],
200,
);
let events = [issue.clone(), status.clone()];
assert_eq!(notification_root(&status, &lookup(&events)), Some(issue.id));
}
#[test]
fn nested_comment_chain_follows_to_the_root() {
let issue = issue(&keys(1), 100);
let reply = signed(&keys(2), Kind::Comment, vec![uppercase_e_tag(&issue)], 200);
let nested = signed(&keys(3), Kind::Comment, vec![uppercase_e_tag(&reply)], 300);
let events = [issue.clone(), reply, nested.clone()];
assert_eq!(notification_root(&nested, &lookup(&events)), Some(issue.id));
}
#[test]
fn group_merges_own_events_into_the_matching_thread() {
let me = keys(1);
let issue = titled_issue(&me, "Add retry logic", 100);
let mine = signed(
&me,
Kind::Comment,
vec![
uppercase_e_tag(&issue),
Tag::parse(["K", "1621"]).expect("K tag"),
],
150,
);
let reply = signed(
&keys(2),
Kind::Comment,
vec![
uppercase_e_tag(&issue),
Tag::parse(["K", "1621"]).expect("K tag"),
],
200,
);
let context = [issue.clone(), mine.clone(), reply.clone()];
let items = group(
[reply.clone()],
[issue.clone(), mine.clone()],
me.public_key(),
&InboxReadState::default(),
&lookup(&context),
);
assert_eq!(items.len(), 1);
assert_eq!(items[0].root, issue.id);
assert_eq!(
items[0].root_event.as_ref().map(|event| event.id),
Some(issue.id)
);
assert_eq!(items[0].kind(), Some(Kind::GitIssue));
assert_eq!(items[0].title(), "Add retry logic");
assert_eq!(items[0].events, vec![reply.clone()]);
// The own events are kept apart from the notifications, newest first.
assert_eq!(items[0].own_events, vec![mine.clone(), issue.clone()]);
assert_eq!(
items[0]
.timeline(5)
.iter()
.map(|event| event.id)
.collect::<Vec<_>>(),
vec![issue.id, mine.id, reply.id]
);
}
#[test]
fn mark_all_read_marks_known_recent_events() {
let me = keys(1);
let now = Timestamp::from_secs(1_000_000_000);
let recent = issue(&keys(2), now.as_secs() - 1000);
let old = issue(&keys(2), now.as_secs() - 5 * 24 * 60 * 60);
let ancient = issue(&keys(2), now.as_secs() - 20 * 24 * 60 * 60);
let mine = issue(&keys(1), now.as_secs() - 100);
let mut state = InboxReadState::default();
state.mark_all_read(
&[recent.clone(), old.clone(), ancient.clone(), mine.clone()],
me.public_key(),
now,
);
assert_eq!(state.read_before, now - MARK_ALL_WINDOW);
assert_eq!(state.read_ids, HashSet::from([recent.id, old.id]));
assert!(state.is_read(&recent));
assert!(state.is_read(&ancient));
assert!(!state.is_read(&mine));
}
#[test]
fn advance_read_never_moves_the_cutoff_backwards() {
let me = keys(1);
let unread = issue(&keys(2), 1_000);
let all = [unread];
let now = Timestamp::from_secs(1_000_000_000);
let mut state = InboxReadState {
read_before: Timestamp::from_secs(999_999_999),
..Default::default()
};
state.advance_read(&all, me.public_key(), now);
assert_eq!(state.read_before, Timestamp::from_secs(999_999_999));
}
#[test]
fn advance_read_moves_before_the_oldest_unread_and_prunes_ids() {
let me = keys(1);
let now = Timestamp::from_secs(1_000_000_000);
let five_days = 5 * 24 * 60 * 60;
let old_unread = issue(&keys(2), now.as_secs() - five_days);
// Read ids that fall before and after the new cutoff.
let stale = signed(
&keys(2),
Kind::GitIssue,
Vec::new(),
now.as_secs() - five_days - 1000,
);
let fresh = signed(
&keys(2),
Kind::GitIssue,
Vec::new(),
now.as_secs() - 100_000,
);
let mut state = InboxReadState {
read_ids: HashSet::from([stale.id, fresh.id]),
..Default::default()
};
state.advance_read(
&[old_unread.clone(), stale.clone(), fresh.clone()],
me.public_key(),
now,
);
assert_eq!(state.read_before, old_unread.created_at - 1);
assert_eq!(state.read_ids, HashSet::from([fresh.id]));
}
#[test]
fn mark_archived_skips_events_at_or_before_the_cutoff() {
let now = Timestamp::from_secs(1_000_000_000);
let event = issue(&keys(2), now.as_secs() - 1000);
let mut state = InboxReadState {
archived_before: now,
..Default::default()
};
state.mark_archived(&event);
assert!(state.archived_ids.is_empty());
let mut state = InboxReadState::default();
state.mark_archived(&event);
assert_eq!(state.archived_ids, HashSet::from([event.id]));
}
}
+10 -4
View File
@@ -1,16 +1,22 @@
pub mod addr;
pub mod annotations;
pub mod clone_url;
pub mod deletions;
pub mod filters;
pub mod inbox;
pub mod model;
pub mod state;
pub mod status;
pub use addr::{RepoAddr, identifier_from_name, repo_addr};
pub use annotations::{COVER_NOTE_KIND, cover_note, labels_and_subject, subject_override};
pub use clone_url::{CloneTarget, parse_clone_url};
pub use annotations::COVER_NOTE_KIND;
pub use deletions::Deletions;
pub use model::{Announcement, activity_subject, pull_request_patch, pull_request_patches};
pub use filters::{
NOTIFICATION_KINDS, authored_activity, is_git_activity, notification_comments, notifications,
};
pub use inbox::{InboxItem, InboxReadState, group, notification_root};
pub use model::{
Announcement, activity_subject, branch_name_of, clone_urls_of, current_commit_of,
fork_candidates, latest_update, merge_base_of, pull_request_patch, pull_request_patches,
};
pub use state::{build_state, parse_state};
pub use status::{RepoStatus, references_root, resolve_status};
+297 -141
View File
@@ -1,9 +1,8 @@
use std::collections::HashSet;
use gpui::SharedString;
use nostr::prelude::*;
use crate::RepoAddr;
use crate::{RepoAddr, repo_addr};
/// Parsed NIP-34 repository announcement, plain data ready for the UI.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -16,8 +15,8 @@ pub struct Announcement {
pub owner: PublicKey,
/// When the announcement was published, used for latest-wins resolution.
pub created_at: Timestamp,
pub name: Option<SharedString>,
pub description: Option<SharedString>,
pub name: Option<String>,
pub description: Option<String>,
/// Webpage URLs for browsing.
pub web: Vec<Url>,
/// URLs for `git clone`.
@@ -42,13 +41,10 @@ pub struct Upstream {
/// Upstream repository coordinate when the `u` tag names a NIP-34 repository.
/// `None` for the git-URL form.
pub addr: Option<RepoAddr>,
/// Relay hint for the upstream, if the `u` tag carries one.
pub relay_hint: Option<RelayUrl>,
}
impl Upstream {
/// Parse the `u` tag values.
fn parse(raw: &str, relay_hint: Option<&str>) -> Self {
fn parse(raw: &str) -> Self {
let coordinate = raw.split('|').next().unwrap_or(raw);
let addr = coordinate
.parse::<Coordinate>()
@@ -57,22 +53,20 @@ impl Upstream {
Self {
raw: raw.to_owned(),
addr,
relay_hint: relay_hint.and_then(|hint| RelayUrl::parse(hint).ok()),
}
}
/// Text for display.
pub fn display(&self) -> SharedString {
pub fn display(&self) -> String {
match &self.addr {
Some(addr) => SharedString::from(addr.to_string()),
None => SharedString::from(self.raw.clone()),
Some(addr) => addr.to_string(),
None => self.raw.clone(),
}
}
}
/// Subject of a NIP-34 issue or pull request event.
/// Taken from the `subject` tag, else the first non-empty line of the content.
pub fn activity_subject(event: &Event) -> SharedString {
pub fn activity_subject(event: &Event) -> String {
let subject = event
.tags
.iter()
@@ -82,16 +76,15 @@ pub fn activity_subject(event: &Event) -> SharedString {
});
subject
.map(SharedString::from)
.or_else(|| {
event
.content
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.map(SharedString::from)
.map(|value| value.to_string())
})
.unwrap_or(SharedString::from("Untitled"))
.unwrap_or("Untitled".to_string())
}
/// The patch set of a pull request.
@@ -145,7 +138,6 @@ pub fn pull_request_patches<'a>(
series
}
/// The patch content of a pull request.
pub fn pull_request_patch<'a>(pr: &Event, patches: impl IntoIterator<Item = &'a Event>) -> String {
let patches: Vec<&'a Event> = patches.into_iter().collect();
let series = pull_request_patches(pr, patches.iter().copied());
@@ -182,7 +174,7 @@ fn forward_series<'a>(root: &'a Event, patches: &[&'a Event]) -> Vec<&'a Event>
}
/// The `c` tag of an event, the tip of the proposed branch, as hex.
fn current_commit_of(event: &Event) -> Option<String> {
pub fn current_commit_of(event: &Event) -> Option<String> {
event
.tags
.iter()
@@ -192,6 +184,82 @@ fn current_commit_of(event: &Event) -> Option<String> {
})
}
/// The `merge-base` tag of an event, the base commit a pull request diffs against.
pub fn merge_base_of(event: &Event) -> Option<String> {
event
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::MergeBase(commit)) => Some(commit.to_string()),
_ => None,
})
}
/// The `clone` tag of an event, URLs the tip commit can be fetched from.
pub fn clone_urls_of(event: &Event) -> Option<Vec<Url>> {
event
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Clone(urls)) => Some(urls),
_ => None,
})
}
/// The `branch-name` tag of an event, the proposed branch's name.
pub fn branch_name_of(event: &Event) -> Option<String> {
event
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::BranchName(name)) => Some(name),
_ => None,
})
}
/// The newest `GitPullRequestUpdate` revising `root`, from the root's own author.
///
/// A pull request's tip is only mutable by its author, per NIP-34; updates
/// from anyone else are ignored even if they are newer.
pub fn latest_update<'a>(
events: impl Iterator<Item = &'a Event>,
root: &Event,
) -> Option<&'a Event> {
let root_hex = root.id.to_hex();
events
.filter(|e| e.kind == Kind::GitPullRequestUpdate)
.filter(|e| e.pubkey == root.pubkey)
.filter(|e| {
e.tags
.iter()
.any(|t| t.kind() == "E" && t.content() == Some(root_hex.as_str()))
})
.max_by_key(|e| e.created_at)
}
/// The announced forks of `base` a new pull request compare can be built from.
///
/// The user's own forks are listed first.
pub fn fork_candidates<'a>(
announcements: &'a [Announcement],
base: &RepoAddr,
base_euc: Option<&str>,
user: Option<PublicKey>,
) -> Vec<&'a Announcement> {
let (mut own, mut others) = (Vec::new(), Vec::new());
for announcement in announcements {
if announcement.clone.is_empty() || !announcement.is_fork_of(base, base_euc) {
continue;
}
if Some(announcement.owner) == user {
own.push(announcement);
} else {
others.push(announcement);
}
}
own.into_iter().chain(others).collect()
}
/// Whether `patch` produces `commit`, found via its `commit` or `r` tag.
///
/// It lets clients find existing patches for a specific commit.
@@ -219,8 +287,8 @@ impl Announcement {
let mut hashtags: Vec<String> = Vec::new();
hashtags.extend(event.tags.hashtags().map(|t| t.to_string()));
let mut name: Option<SharedString> = None;
let mut description: Option<SharedString> = None;
let mut name: Option<String> = None;
let mut description: Option<String> = None;
let mut web: Vec<Url> = Vec::new();
let mut clone: Vec<Url> = Vec::new();
let mut relays: Vec<RelayUrl> = Vec::new();
@@ -230,8 +298,8 @@ impl Announcement {
for tag in event.tags.iter() {
match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Name(value)) => name = Some(value.into()),
Ok(Nip34Tag::Description(value)) => description = Some(value.into()),
Ok(Nip34Tag::Name(value)) => name = Some(value),
Ok(Nip34Tag::Description(value)) => description = Some(value),
Ok(Nip34Tag::Web(urls)) => web.extend(urls),
Ok(Nip34Tag::Clone(urls)) => clone.extend(urls),
Ok(Nip34Tag::Relays(urls)) => relays.extend(urls),
@@ -246,7 +314,7 @@ impl Announcement {
let values = tag.as_slice();
let raw = values.get(1).map(String::as_str).unwrap_or_default();
if !raw.is_empty() {
upstream = Some(Upstream::parse(raw, values.get(2).map(String::as_str)));
upstream = Some(Upstream::parse(raw));
}
}
}
@@ -268,9 +336,13 @@ impl Announcement {
})
}
/// The repository address of this announcement.
pub fn addr(&self) -> crate::RepoAddr {
crate::repo_addr(self.owner, self.id.clone())
pub fn addr(&self) -> RepoAddr {
repo_addr(self.owner, self.id.clone())
}
/// The name of the repository, or a default if none is provided.
pub fn name(&self) -> String {
self.name.clone().unwrap_or("Untitled".into())
}
/// Whether this announcement is a fork of the repository at `base`.
@@ -288,10 +360,10 @@ impl Announcement {
}
/// The description of the repository, or a default if none is provided.
pub fn description(&self) -> SharedString {
pub fn description(&self) -> String {
self.description
.clone()
.unwrap_or(SharedString::from("No description"))
.unwrap_or("No description".to_string())
}
/// The effective maintainers of this repository,
@@ -307,11 +379,11 @@ impl Announcement {
}
/// The `git clone` URLs for this repository, deduplicated.
pub fn clone_urls(&self) -> Vec<SharedString> {
pub fn clone_urls(&self) -> Vec<String> {
let mut seen = HashSet::new();
self.clone
.iter()
.map(|url| SharedString::from(format!("git clone {url}")))
.map(|url| format!("git clone {url}"))
.filter(|command| seen.insert(command.clone()))
.collect()
}
@@ -330,7 +402,6 @@ mod tests {
)
}
/// Build a signed kind `30617` event from raw tag values.
fn announcement_event(tags: &[&[&str]]) -> Event {
let tags: Vec<Tag> = tags
.iter()
@@ -390,22 +461,6 @@ mod tests {
assert_eq!(announcement.hashtags, vec!["rust", "nostr"]);
}
#[test]
fn requires_d_tag() {
let event = announcement_event(&[&["name", "No id"]]);
assert!(Announcement::from_event(&event).is_none());
}
#[test]
fn ignores_other_kinds() {
let event = EventBuilder::new(Kind::GitIssue, "")
.finalize(&keys())
.expect("signed event");
assert!(Announcement::from_event(&event).is_none());
}
#[test]
fn drops_malformed_values() {
let event = announcement_event(&[
@@ -426,17 +481,6 @@ mod tests {
assert!(announcement.maintainers.is_empty());
}
#[test]
fn ignores_unknown_tags() {
let event = announcement_event(&[&["d", "my-repo"], &["t", "label"], &["subject", "n/a"]]);
let announcement = Announcement::from_event(&event).expect("parses");
assert_eq!(announcement.id, "my-repo");
assert!(announcement.name.is_none());
assert!(announcement.web.is_empty());
}
#[test]
fn parses_upstream_tag() {
let event = announcement_event(&[
@@ -464,35 +508,12 @@ mod tests {
upstream.raw,
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git"
);
assert_eq!(
upstream.relay_hint,
Some(RelayUrl::parse("wss://relay.example.com").expect("valid relay"))
);
assert_eq!(
upstream.display().to_string(),
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream"
);
}
#[test]
fn parses_git_url_upstream() {
// The `u` tag may reference a non-nostr upstream by git URL only.
// There is no repository address to navigate to.
let event = announcement_event(&[
&["d", "my-fork"],
&["u", "https://example.com/upstream.git"],
]);
let announcement = Announcement::from_event(&event).expect("parses");
let upstream = announcement.upstream.expect("parses the u tag");
assert_eq!(upstream.addr, None);
assert_eq!(
upstream.display().to_string(),
"https://example.com/upstream.git"
);
}
#[test]
fn is_fork_of_matches_the_u_tag_coordinate() {
// The base repository, announced by the `u` tag's owner.
@@ -553,17 +574,6 @@ mod tests {
assert!(fork.is_fork_of(&base, Some(base_euc)));
}
#[test]
fn is_fork_of_excludes_the_base_itself() {
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
let event = announcement_event(&[&["d", "upstream"], &["r", euc, "euc"]]);
let base = Announcement::from_event(&event).expect("parses");
let base_addr = base.addr();
// The base announcement matches its own EUC but is not a fork of itself.
assert!(!base.is_fork_of(&base_addr, base.euc.as_deref()));
}
#[test]
fn effective_maintainers_include_owner_for_primary_repos() {
let event = announcement_event(&[&["d", "my-repo"], &["maintainers", MAINTAINER_HEX]]);
@@ -598,7 +608,6 @@ mod tests {
);
}
/// Build a signed PR event with the given tags and content.
fn pr_event(content: &str, tags: Vec<Tag>) -> Event {
EventBuilder::new(Kind::GitPullRequest, content)
.tags(tags)
@@ -606,35 +615,6 @@ mod tests {
.expect("signed event")
}
#[test]
fn pull_request_patch_prefers_linked_patch_event() {
let patch = EventBuilder::new(Kind::GitPatch, "patch-content")
.finalize(&keys())
.expect("signed event");
let pr = pr_event("description", vec![Tag::event(patch.id)]);
assert_eq!(pull_request_patch(&pr, [&patch]), "patch-content");
}
#[test]
fn pull_request_patch_falls_back_to_inline_content() {
// Older PRs carried the patch in the content and link no patch event.
let pr = pr_event("patch-inline", vec![]);
assert_eq!(pull_request_patch(&pr, [] as [&Event; 0]), "patch-inline");
}
#[test]
fn pull_request_patch_ignores_unrelated_patch_events() {
let patch = EventBuilder::new(Kind::GitPatch, "patch-content")
.finalize(&keys())
.expect("signed event");
let pr = pr_event("description", vec![]);
assert_eq!(pull_request_patch(&pr, [&patch]), "description");
}
/// Build a signed patch event with a controlled `created_at`.
fn patch_event(content: &str, tags: Vec<Tag>, created_at: u64) -> Event {
EventBuilder::new(Kind::GitPatch, content)
.tags(tags)
@@ -678,24 +658,6 @@ mod tests {
);
}
#[test]
fn pull_request_patches_ignores_unrelated_replies() {
let root = patch_event("patch-one", vec![], 100);
let other = patch_event("other-patch", vec![Tag::event(root.id)], 250);
// A patch replying to a different root is not part of the set.
let stranger = patch_event("stranger", vec![], 150);
let pr = pr_event("description", vec![Tag::event(root.id)]);
let series = pull_request_patches(&pr, [&root, &other, &stranger]);
assert_eq!(
series
.iter()
.map(|p| p.content.as_str())
.collect::<Vec<_>>(),
vec!["patch-one", "other-patch"]
);
}
#[test]
fn pull_request_patches_finds_the_set_via_the_tip_commit() {
// PRs without an `e` tag fall back to the patch producing the tip commit.
@@ -724,4 +686,198 @@ mod tests {
vec!["patch-one", "patch-two"]
);
}
const COMMIT_HEX: &str = "1111111111111111111111111111111111111111";
const OTHER_ROOT_HEX: &str = "2222222222222222222222222222222222222222";
fn signed_at(kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
EventBuilder::new(kind, "")
.tags(tags)
.custom_created_at(Timestamp::from(created_at))
.finalize(&keys())
.expect("signed event")
}
fn pr_root() -> Event {
signed_at(
Kind::GitPullRequest,
vec![
Tag::parse(["c", COMMIT_HEX]).expect("valid tag"),
Tag::parse(["branch-name", "feature/x"]).expect("valid tag"),
],
100,
)
}
#[test]
fn latest_update_picks_newest_revision_of_the_root() {
let root = pr_root();
let root_hex = root.id.to_hex();
let revision = |created_at: u64| {
signed_at(
Kind::GitPullRequestUpdate,
vec![Tag::parse(["E", &root_hex]).expect("valid tag")],
created_at,
)
};
// An update revising a different PR must be ignored even though it is newer.
let unrelated = signed_at(
Kind::GitPullRequestUpdate,
vec![Tag::parse(["E", OTHER_ROOT_HEX]).expect("valid tag")],
999,
);
let events = [unrelated, revision(200), root.clone(), revision(300)];
let latest = latest_update(events.iter(), &root).expect("an update");
assert_eq!(latest.created_at.as_secs(), 300);
assert_eq!(latest.kind, Kind::GitPullRequestUpdate);
}
#[test]
fn latest_update_ignores_other_authors() {
let root = pr_root();
let root_hex = root.id.to_hex();
let other = Keys::new(
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000002")
.expect("valid secret key"),
);
let stranger = EventBuilder::new(Kind::GitPullRequestUpdate, "")
.tags([Tag::parse(["E", &root_hex]).expect("valid tag")])
.custom_created_at(Timestamp::from(999))
.finalize(&other)
.expect("signed event");
// The tip of a PR is only mutable by its author.
// A newer update from anyone else must not win.
assert!(latest_update([&stranger, &root].into_iter(), &root).is_none());
}
const OWNER_KEYS: [&str; 3] = [
"0000000000000000000000000000000000000000000000000000000000000001",
"0000000000000000000000000000000000000000000000000000000000000002",
"0000000000000000000000000000000000000000000000000000000000000003",
];
fn owned_announcement_event(owner: &str, tags: &[&[&str]]) -> Event {
let keys = Keys::new(SecretKey::from_hex(owner).expect("valid secret key"));
let tags: Vec<Tag> = tags
.iter()
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
.collect();
EventBuilder::new(Kind::GitRepoAnnouncement, "")
.tags(tags)
.finalize(&keys)
.expect("signed event")
}
fn owned_announcements(owner_ix: usize, tags: &[&[&str]]) -> Vec<Announcement> {
vec![
Announcement::from_event(&owned_announcement_event(OWNER_KEYS[owner_ix], tags))
.expect("parses"),
]
}
#[test]
fn fork_candidates_orders_own_forks_first() {
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
let clone = "https://grasp.example/npub1x/my-fork.git";
let base_addr = crate::repo_addr(
PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey"),
"upstream",
);
// Newest first, as RepoListStore keeps them.
// Unrelated repo, the user's fork with the shared EUC, another fork with a `u` tag.
let all = vec![
owned_announcements(
2,
&[
&["d", "other-project"],
&["r", "bb231c4c6a5777dc89b42207b499891a344add5c", "euc"],
],
)
.pop()
.unwrap(),
owned_announcements(
1,
&[&["d", "my-fork"], &["r", euc, "euc"], &["clone", clone]],
)
.pop()
.unwrap(),
owned_announcements(
2,
&[
&["d", "their-fork"],
&["u", &base_addr.to_string()],
&["clone", clone],
],
)
.pop()
.unwrap(),
];
let user = PublicKey::from_hex(OWNER_KEYS[1]).expect("pubkey");
let forks = fork_candidates(&all, &base_addr, Some(euc), Some(user));
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
assert_eq!(ids, vec!["my-fork", "their-fork"]);
}
#[test]
fn fork_candidates_excludes_base_unrelated_and_unfetchable() {
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
let base_owner = PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey");
let base_addr = crate::repo_addr(base_owner, "upstream");
let mut all = vec![
owned_announcements(0, &[&["d", "upstream"], &["r", euc, "euc"]])
.pop()
.unwrap(),
owned_announcements(1, &[&["d", "no-clone-fork"], &["r", euc, "euc"]])
.pop()
.unwrap(),
owned_announcements(
2,
&[
&["d", "other"],
&["r", "cc231c4c6a5777dc89b42207b499891a344add5c", "euc"],
],
)
.pop()
.unwrap(),
owned_announcements(
2,
&[
&["d", "mirror"],
&["r", euc, "euc"],
&["clone", "https://grasp.example/x/mirror.git"],
],
)
.pop()
.unwrap(),
];
let forks = fork_candidates(&all, &base_addr, Some(euc), Some(base_owner));
assert_eq!(forks.len(), 1);
assert_eq!(forks[0].id, "mirror");
// Without a base EUC only `u`-tag forks match.
all.push(
owned_announcements(
2,
&[
&["d", "u-fork"],
&["u", &base_addr.to_string()],
&["clone", "https://grasp.example/x/u-fork.git"],
],
)
.pop()
.unwrap(),
);
let forks = fork_candidates(&all, &base_addr, None, Some(base_owner));
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
assert_eq!(ids, vec!["u-fork"]);
}
}
-34
View File
@@ -55,7 +55,6 @@ mod tests {
)
}
/// Build a signed kind `30618` event from raw tag values.
fn state_event(tags: &[&[&str]]) -> Event {
let tags: Vec<Tag> = tags
.iter()
@@ -90,26 +89,6 @@ mod tests {
);
}
#[test]
fn head_without_prefix_is_ignored() {
let event = state_event(&[&["HEAD", "main"]]);
let (refs, head) = parse_state(&event);
assert!(refs.is_empty());
assert!(head.is_none());
}
#[test]
fn ignores_non_state_tags() {
let event = state_event(&[&["d", "my-repo"], &["name", "ignored"]]);
let (refs, head) = parse_state(&event);
assert!(refs.is_empty());
assert!(head.is_none());
}
#[test]
fn build_state_round_trips_through_parse() {
let refs = [
@@ -129,17 +108,4 @@ mod tests {
assert_eq!(parsed_refs, refs);
assert_eq!(head.as_deref(), Some("main"));
}
#[test]
fn build_state_omits_head_when_detached() {
let refs = [("refs/heads/main".to_owned(), COMMIT_A.to_owned())];
let event = build_state("my-repo", &refs, None)
.finalize(&keys())
.expect("signed event");
let (parsed_refs, head) = parse_state(&event);
assert_eq!(parsed_refs, refs);
assert!(head.is_none());
}
}
-62
View File
@@ -76,7 +76,6 @@ mod tests {
EventId::from_hex(ROOT_ID_HEX).expect("valid event id")
}
/// Build a signed status event with a controlled `created_at`.
fn status_event(author: &Keys, kind: Kind, root: EventId, created_at: u64) -> Event {
EventBuilder::new(kind, "")
.tags([Tag::event(root)])
@@ -102,53 +101,6 @@ mod tests {
));
}
#[test]
fn references_root_matches_uppercase_e_tag() {
let root = root_event_id();
let event = EventBuilder::new(Kind::Comment, "")
.tags([Tag::parse(["E", ROOT_ID_HEX]).expect("valid E tag")])
.finalize(&keys_from_hex(
"0000000000000000000000000000000000000000000000000000000000000001",
))
.expect("signed event");
assert!(references_root(&event, &root));
assert!(!references_root(
&event,
&EventId::from_hex(OTHER_ID_HEX).expect("valid id")
));
}
#[test]
fn references_root_false_without_e_tags() {
let event = EventBuilder::new(Kind::GitStatusOpen, "")
.finalize(&keys_from_hex(
"0000000000000000000000000000000000000000000000000000000000000001",
))
.expect("signed event");
assert!(!references_root(&event, &root_event_id()));
}
#[test]
fn defaults_to_open_without_status_events() {
let owner =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let statuses: Vec<Event> = Vec::new();
assert_eq!(
resolve_status(
statuses.iter(),
&owner.public_key(),
&[maintainer.public_key()]
),
RepoStatus::Open
);
}
#[test]
fn latest_status_wins() {
let owner =
@@ -196,18 +148,4 @@ mod tests {
RepoStatus::Draft
);
}
#[test]
fn ignores_non_status_kinds() {
let owner =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
let root = root_event_id();
let statuses = [status_event(&owner, Kind::GitIssue, root, 100)];
assert_eq!(
resolve_status(statuses.iter(), &owner.public_key(), &[]),
RepoStatus::Open
);
}
}
+6
View File
@@ -8,8 +8,14 @@ publish.workspace = true
signed_core = { path = "../signed_core" }
nostr.workspace = true
serde.workspace = true
serde_json.workspace = true
gix = { workspace = true, features = ["revision", "blob-diff"] }
gix-worktree = "0.56"
gix-worktree-state = "0.34"
anyhow.workspace = true
diffy = "0.5"
ignore = "0.4"
[dev-dependencies]
tempfile = "3"
+90
View File
@@ -0,0 +1,90 @@
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use signed_core::{Announcement, RepoAddr};
use crate::remote::{clone_repo, fetch_all};
/// On-disk cache of cloned repositories, keyed by owner pubkey / repo id.
#[derive(Debug, Clone)]
pub struct GitCache {
root: PathBuf,
}
impl GitCache {
pub fn new(root: PathBuf) -> Self {
Self { root }
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn repo_path(&self, addr: &RepoAddr) -> PathBuf {
self.root
.join(addr.public_key.to_hex())
.join(sanitize_path_component(&addr.identifier))
}
pub fn open(&self, addr: &RepoAddr) -> Result<Option<gix::Repository>> {
let path = self.repo_path(addr);
match gix::open(&path) {
Ok(repo) => Ok(Some(repo)),
Err(gix::open::Error::NotARepository { .. }) => Ok(None),
Err(gix::open::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
/// Open the existing clone, fetching it first.
pub fn ensure_clone<U: AsRef<str>>(
&self,
addr: &RepoAddr,
clone_urls: &[U],
) -> Result<gix::Repository> {
let path = self.repo_path(addr);
if let Some(repo) = self.open(addr)? {
fetch_all(&repo).ok();
return Ok(repo);
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("failed to create {}", parent.display()))?;
}
clone_repo(clone_urls, &path)?;
self.open(addr)?
.ok_or_else(|| anyhow::anyhow!("clone finished but the repository cannot be opened"))
}
}
/// Map an untrusted repository id or display name to a safe single path component.
pub fn sanitize_path_component(id: &str) -> String {
let sanitized: String = id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'_'
}
})
.collect();
if sanitized == "." || sanitized == ".." {
return "_".to_owned();
}
sanitized
}
/// The refs namespace of a fork's import in the target mirror.
pub fn fork_namespace(announcement: &Announcement) -> String {
format!(
"{}/{}",
announcement.owner.to_hex(),
sanitize_path_component(&announcement.id)
)
}
+295
View File
@@ -0,0 +1,295 @@
use std::path::Path;
use anyhow::Result;
use gix::diff::blob::unified_diff::{ConsumeHunk, DiffLineKind as GixLineKind, HunkHeader};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffLineKind {
/// An unchanged context line, present on both sides.
Context,
Addition,
Deletion,
}
#[derive(Debug, Clone)]
pub struct DiffLine {
pub kind: DiffLineKind,
/// 1-based line number in the old version, if the line exists there.
pub old: Option<u32>,
/// 1-based line number in the new version, if the line exists there.
pub new: Option<u32>,
/// Line content without the trailing newline.
pub text: String,
}
/// A hunk of a file diff, like `@@ -a,b +c,d @@`.
#[derive(Debug, Clone)]
pub struct DiffHunk {
/// 1-based start line in the old version.
pub old_start: u32,
pub old_lines: u32,
/// 1-based start line in the new version.
pub new_start: u32,
pub new_lines: u32,
pub lines: Vec<DiffLine>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffStatus {
Added,
Modified,
Deleted,
Renamed,
Copied,
}
#[derive(Debug, Clone)]
pub struct FileDiff {
/// Path of the file relative to the repo root.
///
/// For renames and copies, this is the destination path.
pub path: String,
/// Previous path, for renames and copies.
pub old_path: Option<String>,
pub status: DiffStatus,
/// Number of added lines, 0 for binary files.
pub insertions: usize,
/// Number of removed lines, 0 for binary files.
pub deletions: usize,
/// True if either version is binary, then `hunks` is empty.
pub binary: bool,
pub hunks: Vec<DiffHunk>,
}
#[derive(Debug, Clone)]
pub struct CommitDiff {
pub files: Vec<FileDiff>,
}
/// The changes of the commit `id`, short or full, in the repository at `workdir`.
///
/// Compared against its first parent, the empty tree for the root commit.
pub fn worktree_commit_diff(workdir: &Path, id: &str) -> Result<CommitDiff> {
commit_diff(&gix::open(workdir)?, id)
}
fn commit_diff(repo: &gix::Repository, id: &str) -> Result<CommitDiff> {
let commit_id = repo.rev_parse_single(id.as_bytes())?;
let commit = commit_id.object()?.into_commit();
let new_tree = commit.tree()?;
let old_tree = match commit.parent_ids().next() {
Some(parent) => Some(parent.object()?.into_commit().tree()?),
None => None,
};
tree_diff(repo, old_tree.as_ref(), &new_tree)
}
/// The changes between two commits, `base`..`tip`, like `git diff base tip`.
///
/// Directories and submodules are skipped, files are sorted by path.
pub fn worktree_commit_range_diff(workdir: &Path, base: &str, tip: &str) -> Result<CommitDiff> {
let repo = gix::open(workdir)?;
let base_tree = repo
.rev_parse_single(base.as_bytes())?
.object()?
.into_commit()
.tree()?;
let tip_tree = repo
.rev_parse_single(tip.as_bytes())?
.object()?
.into_commit()
.tree()?;
tree_diff(&repo, Some(&base_tree), &tip_tree)
}
fn tree_diff(
repo: &gix::Repository,
old_tree: Option<&gix::Tree<'_>>,
new_tree: &gix::Tree<'_>,
) -> Result<CommitDiff> {
use gix::diff::blob::platform::prepare_diff::Operation;
use gix::object::tree::diff::Change;
use gix::objs::tree::EntryKind;
let changes = repo.diff_tree_to_tree(old_tree, Some(new_tree), None)?;
let mut cache = repo.diff_resource_cache_for_tree_diff()?;
let mut files = Vec::new();
for change in changes {
let attached = Change::from_change_ref(change.to_ref(), repo, repo);
// Skip directory trees and submodule gitlinks, only files are listed.
let (path, old_path, status) = match attached {
Change::Addition {
location,
entry_mode,
..
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) => {
(location.to_owned(), None, DiffStatus::Added)
}
Change::Deletion {
location,
entry_mode,
..
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) => {
(location.to_owned(), None, DiffStatus::Deleted)
}
Change::Modification {
location,
previous_entry_mode,
entry_mode,
..
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit)
&& !matches!(
previous_entry_mode.kind(),
EntryKind::Tree | EntryKind::Commit
) =>
{
(location.to_owned(), None, DiffStatus::Modified)
}
Change::Rewrite {
location,
source_location,
source_entry_mode,
entry_mode,
copy,
..
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit)
&& !matches!(
source_entry_mode.kind(),
EntryKind::Tree | EntryKind::Commit
) =>
{
let status = if copy {
DiffStatus::Copied
} else {
DiffStatus::Renamed
};
(
location.to_owned(),
Some(source_location.to_owned()),
status,
)
}
_ => continue,
};
// Always diff with the built-in algorithm.
// External diff drivers would shell out, out of scope for a read-only viewer.
let platform = attached.diff(&mut cache)?;
platform
.resource_cache
.options
.skip_internal_diff_if_external_is_configured = true;
let outcome = platform.resource_cache.prepare_diff()?;
let (binary, hunks, insertions, deletions) = match outcome.operation {
Operation::InternalDiff { algorithm } => {
let input = outcome.interned_input();
let diff = gix::diff::blob::diff_with_slider_heuristics(algorithm, &input);
let mut hunks = Vec::new();
let mut insertions = 0usize;
let mut deletions = 0usize;
let collector = HunkCollector {
hunks: &mut hunks,
insertions: &mut insertions,
deletions: &mut deletions,
};
gix::diff::blob::UnifiedDiff::new(&diff, &input, collector, Default::default())
.consume()?;
(false, hunks, insertions, deletions)
}
Operation::SourceOrDestinationIsBinary => (true, Vec::new(), 0, 0),
Operation::ExternalCommand { .. } => unreachable!("external diff drivers are disabled"),
};
files.push(FileDiff {
path: String::from_utf8_lossy(&path).into_owned(),
old_path: old_path.map(|p| String::from_utf8_lossy(&p).into_owned()),
status,
insertions,
deletions,
binary,
hunks,
});
}
files.sort_by(|a, b| a.path.cmp(&b.path));
Ok(CommitDiff { files })
}
/// Collects the hunks of one blob diff while tracking per-line numbers.
struct HunkCollector<'a> {
hunks: &'a mut Vec<DiffHunk>,
insertions: &'a mut usize,
deletions: &'a mut usize,
}
impl ConsumeHunk for HunkCollector<'_> {
type Out = ();
fn consume_hunk(
&mut self,
header: HunkHeader,
lines: &[(GixLineKind, &[u8])],
) -> std::io::Result<()> {
let mut old_ln = header.before_hunk_start;
let mut new_ln = header.after_hunk_start;
let mut out = Vec::with_capacity(lines.len());
for (kind, content) in lines {
let text = String::from_utf8_lossy(content).into_owned();
let line = match kind {
GixLineKind::Context => {
let line = DiffLine {
kind: DiffLineKind::Context,
old: Some(old_ln),
new: Some(new_ln),
text,
};
old_ln += 1;
new_ln += 1;
line
}
GixLineKind::Remove => {
*self.deletions += 1;
let line = DiffLine {
kind: DiffLineKind::Deletion,
old: Some(old_ln),
new: None,
text,
};
old_ln += 1;
line
}
GixLineKind::Add => {
*self.insertions += 1;
let line = DiffLine {
kind: DiffLineKind::Addition,
old: None,
new: Some(new_ln),
text,
};
new_ln += 1;
line
}
};
out.push(line);
}
self.hunks.push(DiffHunk {
old_start: header.before_hunk_start,
old_lines: header.before_hunk_len,
new_start: header.after_hunk_start,
new_lines: header.after_hunk_len,
lines: out,
});
Ok(())
}
fn finish(self) {}
}
+248
View File
@@ -0,0 +1,248 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use anyhow::Result;
/// In-memory object cache for history walks, see [`open_with_cache`].
///
/// Without one, a walk re-decodes the same commit objects from the object database.
/// Sized generously: a walk can cover a large portion of the repository's history.
const OBJECT_CACHE_BYTES: usize = 64 * 1024 * 1024;
/// Metadata of a commit, as shown in the repository browser's file header.
#[derive(Debug, Clone)]
pub struct FileCommit {
/// Shortened commit id, 7+ hex chars, disambiguated if needed.
pub id: String,
/// First line of the commit message.
pub summary: String,
/// Rest of the commit message after the title.
///
/// `None` for single-line commit messages.
pub description: Option<String>,
pub author: String,
/// Author time, seconds since the Unix epoch.
pub time: i64,
}
/// Open the repository at `workdir` with an in-memory object cache.
///
/// Only history walks use it, they re-decode the same commit objects repeatedly.
/// Single-object reads open the repository plain.
pub(crate) fn open_with_cache(workdir: &Path) -> Result<gix::Repository> {
let mut repo = gix::open(workdir)?;
repo.object_cache_size_if_unset(OBJECT_CACHE_BYTES);
Ok(repo)
}
/// A [`FileCommit`] with author, message title, body and shortened id.
///
/// The diff panel fetches the full commit on demand.
fn file_commit(commit: &gix::Commit<'_>) -> Result<FileCommit> {
file_commit_with_description(commit, true)
}
/// A [`FileCommit`] without the message body, for history lists that never display it.
///
/// Skipping the body saves an allocation per listed commit.
fn file_commit_summary(commit: &gix::Commit<'_>) -> Result<FileCommit> {
file_commit_with_description(commit, false)
}
fn file_commit_with_description(
commit: &gix::Commit<'_>,
include_description: bool,
) -> Result<FileCommit> {
let author = commit.author()?;
let message = commit.message()?;
Ok(FileCommit {
id: commit.id().shorten_or_id().to_string(),
summary: String::from_utf8_lossy(message.title).trim().to_string(),
description: if include_description {
message
.body
.map(|body| String::from_utf8_lossy(body).trim().to_string())
.filter(|body| !body.is_empty())
} else {
None
},
author: String::from_utf8_lossy(author.name).trim().to_string(),
time: author.time()?.seconds,
})
}
/// Newest commit touching each of `rels`, like `git log -1 -- <rel>` per path.
/// `rels` are paths relative to the worktree.
///
/// Paths without any commit, like untracked files, are absent from the result.
pub fn worktree_last_commits(
workdir: &Path,
rels: &[PathBuf],
) -> Result<Vec<(PathBuf, FileCommit)>> {
last_commits(&open_with_cache(workdir)?, rels)
}
/// Stops as soon as every pending path has its commit.
fn last_commits(repo: &gix::Repository, rels: &[PathBuf]) -> Result<Vec<(PathBuf, FileCommit)>> {
use gix::traverse::commit::simple::CommitTimeOrder;
let Some(head) = repo.head_id().ok() else {
return Ok(Vec::new());
};
let mut pending: Vec<PathBuf> = Vec::with_capacity(rels.len());
let mut seen: HashSet<&Path> = HashSet::with_capacity(rels.len());
for rel in rels {
if seen.insert(rel.as_path()) {
pending.push(rel.clone());
}
}
let walk = repo
.rev_walk([head])
.sorting(gix::revision::walk::Sorting::ByCommitTime(
CommitTimeOrder::NewestFirst,
));
let mut found = Vec::new();
for info in walk.all()? {
if pending.is_empty() {
break;
}
let info = info?;
let commit = info.object()?;
let tree = commit.tree()?;
let parent_tree = match info.parent_ids().next() {
Some(parent) => Some(parent.object()?.into_commit().tree()?),
None => None,
};
// Compare each unresolved path against this commit and its first parent.
let mut ix = 0;
while ix < pending.len() {
let rel = &pending[ix];
let blob = tree.lookup_entry_by_path(rel)?;
let parent_blob = match &parent_tree {
Some(tree) => tree.lookup_entry_by_path(rel)?,
None => None,
};
if blob.map(|entry| entry.id().detach()) != parent_blob.map(|entry| entry.id().detach())
{
found.push((rel.clone(), file_commit(&commit)?));
pending.swap_remove(ix);
} else {
ix += 1;
}
}
}
Ok(found)
}
/// Cap on [`CommitList::commits`]. The virtual list renders a window at a time,
/// the tab badge shows the real count.
///
/// A huge history is never fully materialized in memory.
pub const MAX_LISTED_COMMITS: usize = 20_000;
/// Commits reachable from `HEAD`, newest first, possibly capped.
pub struct CommitList {
/// Number of commits reachable from HEAD.
pub total: usize,
/// Newest commits, capped at [`MAX_LISTED_COMMITS`].
pub commits: Vec<FileCommit>,
}
/// All commits reachable from `HEAD`, newest first, with author and summary.
///
/// Returns an empty list for a repository without any commits yet.
pub fn all_commits(repo: &gix::Repository) -> Result<CommitList> {
use gix::traverse::commit::simple::CommitTimeOrder;
let Some(head) = repo.head_id().ok() else {
return Ok(CommitList {
total: 0,
commits: Vec::new(),
});
};
let walk = repo
.rev_walk([head])
.sorting(gix::revision::walk::Sorting::ByCommitTime(
CommitTimeOrder::NewestFirst,
));
let mut commits = Vec::new();
let mut total = 0;
for info in walk.all()? {
let info = info?;
total += 1;
if commits.len() < MAX_LISTED_COMMITS {
commits.push(file_commit_summary(&info.object()?)?);
}
}
Ok(CommitList { total, commits })
}
/// For non-bare clones the clone root is the worktree.
pub fn worktree_all_commits(workdir: &Path) -> Result<CommitList> {
all_commits(&open_with_cache(workdir)?)
}
/// Commits in the range `base`..`tip`, newest first, like `git log base..tip`.
pub fn worktree_commit_range_commits(
workdir: &Path,
base: &str,
tip: &str,
) -> Result<Vec<FileCommit>> {
use gix::traverse::commit::simple::CommitTimeOrder;
let repo = open_with_cache(workdir)?;
let base_id = repo.rev_parse_single(base.as_bytes())?;
let tip_id = repo.rev_parse_single(tip.as_bytes())?;
let walk = repo
.rev_walk([tip_id])
.sorting(gix::revision::walk::Sorting::ByCommitTime(
CommitTimeOrder::NewestFirst,
))
.with_hidden([base_id]);
let mut commits = Vec::new();
for info in walk.all()? {
let info = info?;
commits.push(file_commit_summary(&info.object()?)?);
}
Ok(commits)
}
/// The commit HEAD points to, like `git log -1`.
///
/// `Ok(None)` for a repository without commits yet, an unborn HEAD.
pub fn head_commit(repo: &gix::Repository) -> Result<Option<FileCommit>> {
let Some(head) = repo.head_id().ok() else {
return Ok(None);
};
let commit = head.object()?.into_commit();
Ok(Some(file_commit(&commit)?))
}
/// Full metadata of the commit `id`, short or full, in the repository at `workdir`.
/// Like [`head_commit`] for an arbitrary commit.
///
/// `Ok(None)` when the id cannot be resolved.
pub fn worktree_commit(workdir: &Path, id: &str) -> Result<Option<FileCommit>> {
let repo = gix::open(workdir)?;
match repo.rev_parse_single(id.as_bytes()) {
Ok(commit_id) => {
let commit = commit_id.object()?.into_commit();
Ok(Some(file_commit(&commit)?))
}
Err(_) => Ok(None),
}
}
File diff suppressed because it is too large Load Diff
+454
View File
@@ -0,0 +1,454 @@
use std::path::Path;
use anyhow::Result;
use gix::bstr::ByteSlice;
use nostr::prelude::*;
/// The kind of NIP-34 relationship a local repository has on disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Nip34Kind {
/// Bound to a NIP-34 coordinate, by `nak`'s `nip34.json` or `ngit`'s `nostr.repo`.
Initialized,
/// Cloned from a `nostr://` remote but never initialized locally.
Cloned,
/// Nostr tooling touched the repository but no binding is recoverable.
ToolingOnly,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GraspSignals {
pub nip34_json: bool,
pub nip34_excluded: bool,
pub nostr_repo_config: bool,
pub nostr_remote: bool,
pub grasp_remote: bool,
/// `nip34_grasp_remote` is the `nak`-specific `nip34/grasp/<host>` remote name.
pub nip34_grasp_remote: bool,
pub nip34_state_refs: bool,
pub nostr_cache: bool,
pub nostr_aux_config: bool,
pub maintainers_yaml: bool,
}
impl GraspSignals {
pub fn any(&self) -> bool {
*self != Self::default()
}
}
/// What a local repository's on-disk state says about its NIP-34 binding.
#[derive(Debug, Clone, PartialEq)]
pub struct Nip34Binding {
pub kind: Nip34Kind,
pub signals: GraspSignals,
/// Coordinate owner and identifier, from `nip34.json` or `nostr.repo`.
pub owner: Option<PublicKey>,
pub identifier: Option<String>,
pub grasp_urls: Vec<String>,
}
#[derive(serde::Deserialize)]
struct Nip34Json {
identifier: Option<String>,
owner: Option<String>,
}
pub fn detect_nip34(repo_path: &Path) -> Option<Nip34Binding> {
let repo = gix::open(repo_path).ok()?;
let common_dir = repo.common_dir().to_path_buf();
let workdir = repo.workdir().map(Path::to_path_buf);
let mut signals = GraspSignals::default();
let mut owner: Option<PublicKey> = None;
let mut identifier: Option<String> = None;
let mut grasp_urls: Vec<String> = Vec::new();
if let Some(workdir) = &workdir {
if let Ok(bytes) = std::fs::read(workdir.join("nip34.json"))
&& let Ok(config) = serde_json::from_slice::<Nip34Json>(&bytes)
{
signals.nip34_json = true;
identifier = config.identifier.and_then(non_empty);
owner = config
.owner
.as_deref()
.and_then(|value| PublicKey::parse(value).ok());
}
if workdir.join("maintainers.yaml").is_file() {
signals.maintainers_yaml = true;
}
}
if let Ok(exclude) = std::fs::read_to_string(common_dir.join("info/exclude"))
&& exclude.contains("nip34.json")
{
signals.nip34_excluded = true;
}
// `ngit` keeps its repository event cache in the Git common directory.
if common_dir.join("nostr-cache.lmdb").is_file() {
signals.nostr_cache = true;
}
// `ngit` reads and writes `nostr.repo` at repository-local scope only.
if let Ok(config) = gix::config::File::from_path_no_includes(
common_dir.join("config"),
gix::config::Source::Local,
) {
if let Some(value) = config.string("nostr.repo")
&& let Some((key, id)) = coordinate_from_naddr(&value.to_str_lossy())
{
signals.nostr_repo_config = true;
owner = Some(key);
identifier = Some(id);
}
for key in ["nostr.repo-relay-only", "nostr.nostate", "nostr.private"] {
if config.string(key).is_some() {
signals.nostr_aux_config = true;
}
}
if let Some(sections) = config.sections_by_name("remote") {
for section in sections {
let Some(name) = section.header().subsection_name() else {
continue;
};
let nak_grasp_remote = name.to_str_lossy().starts_with("nip34/grasp/");
for url in section.values("url") {
let url = url.to_str_lossy();
if url.starts_with("nostr://") {
signals.nostr_remote = true;
// Strong markers win; only fill an empty binding.
if owner.is_none()
&& identifier.is_none()
&& let Some((key, id)) = parse_nostr_url(&url)
{
owner = Some(key);
identifier = Some(id);
}
}
if is_grasp_url(&url) {
signals.grasp_remote = true;
signals.nip34_grasp_remote |= nak_grasp_remote;
grasp_urls.push(url.to_string());
if owner.is_none()
&& identifier.is_none()
&& let Some((key, id)) = grasp_parts(&url)
{
owner = Some(key);
identifier = Some(id);
}
}
}
}
}
}
// `nak` materializes a kind-30618 state as `refs/heads/nip34/state/*`.
if let Ok(platform) = repo.references()
&& let Ok(mut refs) = platform.prefixed(b"refs/heads/nip34/state/")
&& refs.next().is_some()
{
signals.nip34_state_refs = true;
}
if !signals.any() {
return None;
}
let kind = if signals.nip34_json
|| signals.nostr_repo_config
|| signals.nip34_grasp_remote
|| signals.nip34_state_refs
{
Nip34Kind::Initialized
} else if signals.nostr_remote {
Nip34Kind::Cloned
} else {
Nip34Kind::ToolingOnly
};
Some(Nip34Binding {
kind,
signals,
owner,
identifier,
grasp_urls,
})
}
/// Record a repository's NIP-34 coordinate in its local `nostr.repo` config.
pub fn set_nostr_repo(repo_path: &Path, naddr: &str) -> Result<()> {
let repo = gix::open(repo_path)?;
crate::remote::edit_local_config(&repo, |config| {
config.set_raw_value("nostr.repo", naddr)?;
Ok(())
})
}
/// Mirrors `nak`'s `IsGraspURL`: two path segments, a path of at least 65 bytes,
/// and a first segment that decodes as an `npub`.
pub fn is_grasp_url(url: &str) -> bool {
let Ok(parsed) = Url::parse(url) else {
return false;
};
if !matches!(parsed.scheme(), "http" | "https" | "grasp") {
return false;
}
let path = parsed.path();
if path.matches('/').count() != 2 || path.len() < 65 {
return false;
}
grasp_parts(url).is_some()
}
fn grasp_parts(url: &str) -> Option<(PublicKey, String)> {
let parsed = Url::parse(url).ok()?;
let mut segments = parsed.path_segments()?.filter(|part| !part.is_empty());
let owner = PublicKey::parse(segments.next()?).ok()?;
let identifier = non_empty(segments.next()?.trim_end_matches(".git"))?;
Some((owner, identifier))
}
fn coordinate_from_naddr(value: &str) -> Option<(PublicKey, String)> {
let coordinate = Nip19Coordinate::from_bech32(value).ok()?;
if coordinate.kind != Kind::GitRepoAnnouncement {
return None;
}
let identifier = non_empty(coordinate.identifier.clone())?;
Some((coordinate.public_key, identifier))
}
/// Handles a bare `naddr`, an `npub`, and the optional `[ssh-key-file@]`,
/// `[protocol/]` and `[relay/]` components. An `nip05` owner yields no binding.
fn parse_nostr_url(url: &str) -> Option<(PublicKey, String)> {
let rest = url.strip_prefix("nostr://")?;
if rest.starts_with("naddr1") {
return coordinate_from_naddr(rest);
}
let rest = rest.rsplit_once('@').map_or(rest, |(_, after)| after);
let mut parts: Vec<&str> = rest.split('/').filter(|part| !part.is_empty()).collect();
if parts
.first()
.is_some_and(|first| matches!(*first, "ssh" | "https" | "http"))
{
parts.remove(0);
}
// `[owner, (relay), identifier]`.
if parts.len() < 2 {
return None;
}
let owner = PublicKey::parse(parts[0]).ok()?;
let identifier = non_empty(parts.last()?.trim_end_matches(".git"))?;
Some((owner, identifier))
}
fn non_empty(value: impl Into<String>) -> Option<String> {
let value = value.into();
(!value.is_empty()).then_some(value)
}
#[cfg(test)]
mod tests {
use std::process::Command;
use super::*;
fn init_repo() -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("repo");
std::fs::create_dir_all(&path).expect("mkdir");
git(&path, &["init", "-q"]);
(dir, path)
}
fn git(dir: &Path, args: &[&str]) {
let status = Command::new("git")
.current_dir(dir)
.env("GIT_AUTHOR_NAME", "Test Author")
.env("GIT_AUTHOR_EMAIL", "test@example.com")
.env("GIT_COMMITTER_NAME", "Test Author")
.env("GIT_COMMITTER_EMAIL", "test@example.com")
.env("GIT_EDITOR", "true")
.args(args)
.status()
.expect("spawn git");
assert!(status.success(), "git {args:?} failed");
}
fn key() -> PublicKey {
Keys::generate().public_key()
}
fn naddr(kind: Kind, owner: PublicKey, identifier: &str) -> String {
let coordinate = Coordinate::new(kind, owner).identifier(identifier);
Nip19Coordinate::new(coordinate, Vec::<RelayUrl>::new())
.to_bech32()
.expect("naddr")
}
#[test]
fn plain_repository_has_no_binding() {
let (_dir, path) = init_repo();
assert!(detect_nip34(&path).is_none());
}
#[test]
fn nip34_json_marks_a_repository_initialized() {
let (_dir, path) = init_repo();
let owner = key();
let npub = owner.to_bech32().expect("npub");
std::fs::write(
path.join("nip34.json"),
format!(r#"{{"identifier":"my-repo","owner":"{npub}"}}"#),
)
.expect("write");
let binding = detect_nip34(&path).expect("binding");
assert_eq!(binding.kind, Nip34Kind::Initialized);
assert!(binding.signals.nip34_json);
assert_eq!(binding.owner, Some(owner));
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
}
#[test]
fn malformed_nip34_json_is_ignored() {
let (_dir, path) = init_repo();
std::fs::write(path.join("nip34.json"), b"not json").expect("write");
assert!(detect_nip34(&path).is_none());
}
#[test]
fn nak_exclude_and_state_refs_are_detected() {
let (_dir, path) = init_repo();
std::fs::create_dir_all(path.join(".git/info")).expect("mkdir");
std::fs::write(path.join(".git/info/exclude"), "nip34.json\n").expect("write");
git(&path, &["commit", "-q", "--allow-empty", "-m", "initial"]);
git(
&path,
&["update-ref", "refs/heads/nip34/state/HEAD", "HEAD"],
);
let binding = detect_nip34(&path).expect("binding");
assert_eq!(binding.kind, Nip34Kind::Initialized);
assert!(binding.signals.nip34_excluded);
assert!(binding.signals.nip34_state_refs);
}
#[test]
fn nostr_repo_config_marks_a_repository_initialized() {
let (_dir, path) = init_repo();
let owner = key();
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
git(&path, &["config", "nostr.repo", &naddr]);
let binding = detect_nip34(&path).expect("binding");
assert_eq!(binding.kind, Nip34Kind::Initialized);
assert!(binding.signals.nostr_repo_config);
assert_eq!(binding.owner, Some(owner));
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
}
#[test]
fn the_written_nostr_repo_marker_is_detected() {
let (_dir, path) = init_repo();
let owner = key();
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
set_nostr_repo(&path, &naddr).expect("write marker");
let binding = detect_nip34(&path).expect("binding");
assert_eq!(binding.kind, Nip34Kind::Initialized);
assert!(binding.signals.nostr_repo_config);
assert_eq!(binding.owner, Some(owner));
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
}
#[test]
fn nostr_remote_is_a_nip34_clone() {
let (_dir, path) = init_repo();
let owner = key();
let npub = owner.to_bech32().expect("npub");
let url = format!("nostr://{npub}/relay.ngit.dev/my-repo");
git(&path, &["remote", "add", "origin", &url]);
let binding = detect_nip34(&path).expect("binding");
assert_eq!(binding.kind, Nip34Kind::Cloned);
assert!(binding.signals.nostr_remote);
assert_eq!(binding.owner, Some(owner));
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
}
#[test]
fn nak_grasp_remote_marks_a_repository_initialized() {
let (_dir, path) = init_repo();
let owner = key();
let npub = owner.to_bech32().expect("npub");
let url = format!("https://gitnostr.com/{npub}/my-repo.git");
git(
&path,
&["config", "remote.nip34/grasp/gitnostr.com.url", &url],
);
let binding = detect_nip34(&path).expect("binding");
assert_eq!(binding.kind, Nip34Kind::Initialized);
assert!(binding.signals.nip34_grasp_remote);
assert!(binding.signals.grasp_remote);
assert_eq!(binding.grasp_urls, vec![url]);
assert_eq!(binding.owner, Some(owner));
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
}
#[test]
fn nostr_cache_alone_is_tooling_only() {
let (_dir, path) = init_repo();
std::fs::write(path.join(".git/nostr-cache.lmdb"), b"cache").expect("write");
let binding = detect_nip34(&path).expect("binding");
assert_eq!(binding.kind, Nip34Kind::ToolingOnly);
assert!(binding.signals.nostr_cache);
}
#[test]
fn grasp_urls_are_recognised_by_shape() {
let owner = key();
let npub = owner.to_bech32().expect("npub");
assert!(is_grasp_url(&format!(
"https://gitnostr.com/{npub}/my-repo.git"
)));
assert!(is_grasp_url(&format!(
"grasp://gitnostr.com/{npub}/my-repo.git"
)));
assert!(!is_grasp_url("https://gitnostr.com/my-repo.git"));
assert!(!is_grasp_url(
"https://gitnostr.com/not-a-pubkey/my-repo.git"
));
assert!(!is_grasp_url(&format!(
"ssh://gitnostr.com/{npub}/my-repo.git"
)));
}
}
+322
View File
@@ -0,0 +1,322 @@
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use anyhow::{Context, Result, bail};
use diffy::patch_set::{FileOperation, FilePatch, ParseOptions, PatchSet};
use diffy::{Hunk, Line};
use crate::diff::{CommitDiff, DiffHunk, DiffLine, DiffLineKind, DiffStatus, FileDiff};
use crate::history::FileCommit;
/// Apply a `git format-patch` patch or series with `git am`.
///
/// Uses the git CLI because it handles the mbox format natively.
///
/// TODO: replace with a pure-Rust implementation later without changing callers.
pub fn apply_patch(repo_path: &Path, patch: &str) -> Result<()> {
let mut child = Command::new("git")
.arg("am")
.current_dir(repo_path)
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("failed to spawn `git am`")?;
child
.stdin
.as_mut()
.expect("stdin piped")
.write_all(patch.as_bytes())?;
let output = child.wait_with_output()?;
if !output.status.success() {
bail!("git am failed: {}", String::from_utf8_lossy(&output.stderr));
}
Ok(())
}
/// The `git format-patch` mbox series of `base..tip`, like `git format-patch --stdout`.
/// Fails when the range has no commits.
///
/// The mbox is returned untrimmed. Trailing newlines are part of the format.
pub fn format_patch_between(repo_path: &Path, base: &str, tip: &str) -> Result<String> {
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["format-patch", "--stdout", &format!("{base}..{tip}")])
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git format-patch`")?;
if !output.status.success() {
bail!(
"git format-patch failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
let patch = String::from_utf8_lossy(&output.stdout).into_owned();
if patch.trim().is_empty() {
bail!("no commits between {base} and {tip}");
}
Ok(patch)
}
/// Split a `git format-patch` series into its individual patches, mbox messages.
///
/// A single patch yields one element.
/// A malformed input yields one element covering it.
pub fn split_patch_series(patch: &str) -> Vec<&str> {
let mut starts = vec![0usize];
let mut search_from = 1;
while let Some(rel) = patch[search_from..].find("\nFrom ") {
let ix = search_from + rel + 1;
let hex = patch[ix + 5..]
.split(|c: char| !c.is_ascii_hexdigit())
.next()
.unwrap_or("");
if hex.len() == 40 {
starts.push(ix);
}
search_from = ix + 1;
}
starts
.iter()
.enumerate()
.map(|(i, &start)| {
let end = starts.get(i + 1).copied().unwrap_or(patch.len());
&patch[start..end]
})
.collect()
}
/// Parse `git format-patch` output, a single patch or a series.
///
/// Backed by [`diffy::patch_set`], which implements git's extended diff format:
/// `diff --git` headers, rename and copy detection, binary detection, and
/// C-style quoted or octal-escaped paths.
pub fn patch_diffs(patch: &str) -> Result<CommitDiff> {
if !patch.lines().any(|line| line.starts_with("diff --git ")) {
return Ok(CommitDiff { files: Vec::new() });
}
let mut files = Vec::new();
for file in PatchSet::parse(patch, ParseOptions::gitdiff()) {
files.push(file_diff(file?)?);
}
Ok(CommitDiff { files })
}
fn file_diff(file: FilePatch<'_, str>) -> Result<FileDiff> {
// The `---`/`+++` paths carry the `a/`/`b/` prefix, so the first path
// component is dropped, the same way `git apply -p1` does.
// Rename and copy paths come from their own headers, unprefixed.
let stripped;
let operation = match file.operation() {
operation @ (FileOperation::Rename { .. } | FileOperation::Copy { .. }) => operation,
operation => {
stripped = operation.strip_prefix(1);
&stripped
}
};
let (path, old_path, status) = match operation {
FileOperation::Create(path) => (path.as_ref(), None, DiffStatus::Added),
FileOperation::Delete(path) => (path.as_ref(), None, DiffStatus::Deleted),
FileOperation::Modify { modified, .. } => (modified.as_ref(), None, DiffStatus::Modified),
FileOperation::Rename { from, to } => {
(to.as_ref(), Some(from.as_ref()), DiffStatus::Renamed)
}
FileOperation::Copy { from, to } => (to.as_ref(), Some(from.as_ref()), DiffStatus::Copied),
};
let mut insertions = 0usize;
let mut deletions = 0usize;
let mut hunks = Vec::new();
let patch = file.patch();
if let Some(text) = patch.as_text() {
for hunk in text.hunks() {
let hunk = hunk_diff(hunk);
insertions += hunk
.lines
.iter()
.filter(|line| line.kind == DiffLineKind::Addition)
.count();
deletions += hunk
.lines
.iter()
.filter(|line| line.kind == DiffLineKind::Deletion)
.count();
hunks.push(hunk);
}
}
Ok(FileDiff {
path: path.to_owned(),
old_path: old_path.map(str::to_owned),
status,
insertions,
deletions,
binary: patch.is_binary(),
hunks,
})
}
/// The [`DiffHunk`] of one parsed hunk, including the line number of every line.
///
/// `diffy` reports only the hunk header ranges. The per-line numbers are
/// counted from them the way the header encodes them: context lines advance
/// both sides, deletions only the old, insertions only the new.
fn hunk_diff(hunk: &Hunk<'_, str>) -> DiffHunk {
let old_range = hunk.old_range();
let new_range = hunk.new_range();
let mut old = old_range.start() as u32;
let mut new = new_range.start() as u32;
let mut lines = Vec::with_capacity(hunk.lines().len());
for line in hunk.lines() {
let (kind, text) = match line {
Line::Context(text) => (DiffLineKind::Context, *text),
Line::Delete(text) => (DiffLineKind::Deletion, *text),
Line::Insert(text) => (DiffLineKind::Addition, *text),
};
let (old_no, new_no) = match kind {
DiffLineKind::Context => {
let numbers = (Some(old), Some(new));
old += 1;
new += 1;
numbers
}
DiffLineKind::Addition => {
let number = Some(new);
new += 1;
(None, number)
}
DiffLineKind::Deletion => {
let number = Some(old);
old += 1;
(number, None)
}
};
lines.push(DiffLine {
kind,
old: old_no,
new: new_no,
text: line_text(text),
});
}
DiffHunk {
old_start: old_range.start() as u32,
old_lines: old_range.len() as u32,
new_start: new_range.start() as u32,
new_lines: new_range.len() as u32,
lines,
}
}
/// The content of a parsed line without its line ending.
///
/// `diffy` keeps the trailing `\n`, the way `str::lines` splits it off.
fn line_text(text: &str) -> String {
let text = text.strip_suffix('\n').unwrap_or(text);
text.strip_suffix('\r').unwrap_or(text).to_owned()
}
/// Commits of a `git format-patch` output, a single patch or a series.
///
/// Entries appear in patch order, oldest first as `git format-patch` produces them.
pub fn patch_commits(patch: &str) -> Vec<FileCommit> {
let lines: Vec<&str> = patch.lines().collect();
let mut commits = Vec::new();
let mut i = 0;
while i < lines.len() {
// A patch starts with its `From <id> <date>` envelope line.
let Some(rest) = lines[i].strip_prefix("From ") else {
i += 1;
continue;
};
let Some(id) = rest.split_whitespace().next() else {
i += 1;
continue;
};
if id.len() != 40 {
i += 1;
continue;
}
let mut author = String::new();
let mut summary = String::new();
let mut time = 0i64;
// Envelope headers run up to the blank line before the commit message.
i += 1;
while i < lines.len() && !lines[i].is_empty() {
let header = lines[i];
if let Some(value) = header.strip_prefix("From: ") {
author = name_from_address(value);
} else if let Some(value) = header.strip_prefix("Subject: ") {
summary = strip_patch_prefix(value);
} else if let Some(value) = header.strip_prefix("Date: ") {
time = gix::date::parse(value.trim(), None)
.map(|t| t.seconds)
.unwrap_or(0);
}
i += 1;
}
commits.push(FileCommit {
id: id.to_string(),
summary,
description: None,
author,
time,
});
}
commits
}
fn name_from_address(from: &str) -> String {
match from.trim().find('<') {
Some(ix) => from[..ix].trim().to_string(),
None => from.trim().to_string(),
}
}
/// Strip the patch prefix from a `Subject:` header.
///
/// Examples are `[PATCH]`, `[PATCH 1/2]` and `[RFC PATCH]`.
fn strip_patch_prefix(subject: &str) -> String {
let trimmed = subject.trim();
let Some(rest) = trimmed.strip_prefix('[') else {
return trimmed.to_string();
};
let Some(end) = rest.find(']') else {
return trimmed.to_string();
};
if rest[..end].to_ascii_lowercase().contains("patch") {
rest[end + 1..].trim().to_string()
} else {
trimmed.to_string()
}
}
+351
View File
@@ -0,0 +1,351 @@
use std::collections::HashMap;
use std::path::Path;
use std::process::{Command, Stdio};
use anyhow::{Context, Result, bail};
use gix::interrupt::IS_INTERRUPTED;
use gix::progress::Discard;
/// Clone into `path` from the first working URL in `clone_urls`.
///
/// Unlike [`GitCache::ensure_clone`], the clone is not kept in any cache.
pub fn clone_repo<U: AsRef<str>>(clone_urls: &[U], path: &Path) -> Result<()> {
if path.exists() {
bail!("destination {} already exists", path.display());
}
try_each_url(clone_urls, "clone", |url| {
let repo = clone(url, path)?;
// The initial clone uses the default refspecs. Also fetch the `refs/nostr/*` PR refs.
fetch_all(&repo).ok();
Ok(())
})
}
/// Fetch all configured refspecs from `origin`, plus the `refs/nostr/*` namespace.
pub fn fetch_all(repo: &gix::Repository) -> Result<()> {
let options = gix::remote::ref_map::Options {
extra_refspecs: vec![
gix::refspec::parse(
gix::bstr::BStr::new("+refs/nostr/*:refs/nostr/*"),
gix::refspec::parse::Operation::Fetch,
)?
.to_owned(),
],
..Default::default()
};
repo.find_remote("origin")?
.connect(gix::remote::Direction::Fetch)?
.prepare_fetch(Discard, options)?
.receive(Discard, &IS_INTERRUPTED)?;
Ok(())
}
pub fn push_commit_ref(repo_path: &Path, url: &str, commit: &str, reference: &str) -> Result<()> {
let output = Command::new("git")
.arg("-C")
.arg(repo_path)
.args(["push"])
.arg(url)
.arg(format!("{commit}:{reference}"))
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.context("failed to spawn `git push`")?;
if !output.status.success() {
bail!(
"git push failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(())
}
/// Rewrite a grasp server URL to the https URL the git transport actually uses.
///
/// GRASP servers announce `grasp://<host>/<owner>/<repo>` clone URLs.
/// The transport is git smart HTTP, so the scheme is rewritten for gix.
fn transport_url(url: &str) -> String {
url.strip_prefix("grasp://")
.map(|rest| format!("https://{rest}"))
.unwrap_or_else(|| url.to_owned())
}
/// Run `attempt` against each URL in `urls` until one succeeds.
///
/// Returns the last error wrapped in `failed to {verb} from any mirror`,
/// or `no clone URLs provided` when the list is empty.
fn try_each_url<U: AsRef<str>, F>(urls: &[U], verb: &str, mut attempt: F) -> Result<()>
where
F: FnMut(&str) -> Result<()>,
{
let mut last_err: Option<anyhow::Error> = None;
for url in urls {
match attempt(url.as_ref()) {
Ok(()) => return Ok(()),
Err(e) => last_err = Some(e),
}
}
match last_err {
Some(e) => Err(e).context(format!("failed to {verb} from any mirror")),
None => bail!("no clone URLs provided"),
}
}
fn clone(url: &str, path: &Path) -> Result<gix::Repository> {
let url = transport_url(url);
let url = gix::url::parse(url).context("invalid clone URL")?;
let mut prepare = gix::prepare_clone(url, path)?;
let (mut checkout, _fetch) = prepare.fetch_then_checkout(Discard, &IS_INTERRUPTED)?;
let (repo, _checkout) = checkout.main_worktree(Discard, &IS_INTERRUPTED)?;
Ok(repo)
}
pub fn push_main(repo_path: &Path, base_url: &str, owner: &str, repo_id: &str) -> Result<()> {
push_refspecs(
repo_path,
base_url,
owner,
repo_id,
&["refs/heads/main:refs/heads/main"],
)
}
/// Push every local branch and tag of the repository at `repo_path` to a grasp server.
///
/// This mirrors an initialized repository's whole history.
pub fn push_all(repo_path: &Path, base_url: &str, owner: &str, repo_id: &str) -> Result<()> {
push_refspecs(
repo_path,
base_url,
owner,
repo_id,
&["refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*"],
)
}
fn push_refspecs(
repo_path: &Path,
base_url: &str,
owner: &str,
repo_id: &str,
refspecs: &[&str],
) -> Result<()> {
let url = format!("{base_url}/{owner}/{repo_id}.git");
let mut args: Vec<&str> = Vec::with_capacity(refspecs.len() + 2);
args.push("push");
args.push(&url);
args.extend_from_slice(refspecs);
let output = git_output(repo_path, &args, "git push")?;
if !output.status.success() {
bail!(
"git push to {base_url} failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(())
}
/// Whether `url` advertises every ref in `expected` at the given commit.
///
/// Extra advertised refs are ignored: the question is whether the data this
/// push wanted to land is already there, not whether the remote is an exact mirror.
/// This is the convergence probe for a push that lost the compare-and-swap race
/// to the grasp server's own background ref alignment.
pub fn remote_has_refs(repo_path: &Path, url: &str, expected: &[(String, String)]) -> Result<bool> {
if expected.is_empty() {
return Ok(true);
}
let repo = gix::open(repo_path)?;
let url = transport_url(url);
// A URL-created remote has no configured fetch refspecs, and `ref_map` only
// keeps refs that match one. Match each expected ref by its exact name,
// like `git ls-remote <url> <name>` would; ref maps never write to the repository.
let refspecs = expected
.iter()
.map(|(name, _)| {
gix::refspec::parse(
gix::bstr::BStr::new(format!("+{name}:{name}").as_bytes()),
gix::refspec::parse::Operation::Fetch,
)
.map(|spec| spec.to_owned())
})
.collect::<Result<Vec<_>, _>>()
.context("invalid refspec")?;
let options = gix::remote::ref_map::Options {
extra_refspecs: refspecs,
..Default::default()
};
let (refs, _) = repo
.remote_at(url.as_str())
.with_context(|| format!("cannot use remote {url}"))?
.connect(gix::remote::Direction::Fetch)
.with_context(|| format!("cannot connect to {url}"))?
.ref_map(Discard, options)
.with_context(|| format!("listing refs of {url} failed"))?;
// Peeled tag entries carry the tag object in their direct oid, so mapping
// each advertised ref to its direct oid matches `git ls-remote` while
// skipping the duplicated `^{}` lines.
let advertised: HashMap<String, String> = refs
.remote_refs
.iter()
.filter_map(|reference| {
let (name, object, _peeled) = reference.unpack();
object.map(|oid| (String::from_utf8_lossy(name).into_owned(), oid.to_string()))
})
.collect();
Ok(expected
.iter()
.all(|(name, oid)| advertised.get(name.as_str()) == Some(oid)))
}
/// Add `origin` pointing at `url` when the repository has no remote yet.
///
/// No-op if `origin` already exists.
pub fn ensure_origin(repo_path: &Path, url: &str) -> Result<()> {
let repo = gix::open(repo_path)?;
if repo.find_remote("origin").is_ok() {
return Ok(());
}
// `git remote add` also configures the default fetch refspec.
edit_local_config(&repo, |config| {
config.set_raw_value("remote.origin.url", url)?;
config.set_raw_value("remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*")?;
Ok(())
})
}
/// Point `origin` at `url`, replacing an existing remote,
/// used after a clone whose `origin` points at the cloned-from path.
///
/// A working copy cloned from a local mirror is re-targeted at the grasp server.
pub fn set_origin(repo_path: &Path, url: &str) -> Result<()> {
let repo = gix::open(repo_path)?;
let had_origin = repo.find_remote("origin").is_ok();
edit_local_config(&repo, |config| {
// Replaces the existing url, like `git remote set-url origin <url>`.
// A pre-existing fetch refspec is left untouched.
config.set_raw_value("remote.origin.url", url)?;
if !had_origin {
config.set_raw_value("remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*")?;
}
Ok(())
})
}
/// Apply `edit` to the repository-local configuration and persist it.
pub(crate) fn edit_local_config(
repo: &gix::Repository,
edit: impl FnOnce(&mut gix::config::File) -> Result<()>,
) -> Result<()> {
let config_path = repo.common_dir().join("config");
let mut lock = gix::lock::File::acquire_to_update_resource(
&config_path,
gix::lock::acquire::Fail::Immediately,
None,
)
.context("failed to lock repository config")?;
let mut config =
match gix::config::File::from_path_no_includes(config_path, gix::config::Source::Local) {
Ok(config) => config,
// A repository without a config file yet starts from scratch.
Err(gix::config::file::init::from_paths::Error::Io { source, .. })
if source.kind() == std::io::ErrorKind::NotFound =>
{
gix::config::File::default()
}
Err(error) => return Err(error).context("failed to read repository config"),
};
edit(&mut config)?;
config
.write_to(&mut lock)
.context("failed to write repository config")?;
lock.commit().context("failed to save repository config")?;
Ok(())
}
/// Fetch `refspec` into `repo_path` from the first working URL in `urls`.
/// When no URL works, the last error is returned.
///
/// Never touches the checked-out refs or the worktree.
pub fn fetch_repo_refs<U: AsRef<str>>(repo_path: &Path, urls: &[U], refspec: &str) -> Result<()> {
let repo = gix::open(repo_path)?;
let refspec = gix::refspec::parse(
gix::bstr::BStr::new(refspec),
gix::refspec::parse::Operation::Fetch,
)
.context("invalid fetch refspec")?
.to_owned();
try_each_url(urls, "fetch", |url| {
let url = transport_url(url);
let options = gix::remote::ref_map::Options {
extra_refspecs: vec![refspec.clone()],
..Default::default()
};
repo.remote_at(url.as_str())
.with_context(|| format!("fetch from {url} failed"))?
.connect(gix::remote::Direction::Fetch)
.with_context(|| format!("fetch from {url} failed"))?
.prepare_fetch(Discard, options)
.with_context(|| format!("fetch from {url} failed"))?
.receive(Discard, &IS_INTERRUPTED)
.with_context(|| format!("fetch from {url} failed"))?;
Ok(())
})
}
/// The URL of the `origin` remote of the repository at `workdir`.
///
/// `None` when it has no `origin` yet.
pub fn origin_url(workdir: &Path) -> Result<Option<String>> {
let Ok(repo) = gix::open(workdir) else {
return Ok(None);
};
let Ok(remote) = repo.find_remote("origin") else {
return Ok(None);
};
Ok(remote
.url(gix::remote::Direction::Fetch)
.map(|url| url.to_string()))
}
/// Run `git -C dir args`, disabling the terminal prompt and capturing stderr.
///
/// `what` names the command in the spawn error.
pub(crate) fn git_output(dir: &Path, args: &[&str], what: &str) -> Result<std::process::Output> {
Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.env("GIT_TERMINAL_PROMPT", "0")
.stderr(Stdio::piped())
.output()
.with_context(|| format!("failed to spawn `{what}`"))
}
+469
View File
@@ -0,0 +1,469 @@
use std::path::Path;
use anyhow::{Context, Result};
use crate::history::open_with_cache;
use crate::worktree::{force_checkout, worktree_dirty};
/// The merge base of two revisions in the repository at `repo_path`,
/// revisions may be branch names, remote-tracking refs or commit ids.
///
/// `Ok(None)` when the revisions share no common ancestor.
///
/// Unresolvable revisions are errors.
pub fn merge_base(repo_path: &Path, a: &str, b: &str) -> Result<Option<String>> {
let repo = open_with_cache(repo_path)?;
let a = repo.rev_parse_single(a.as_bytes())?;
let b = repo.rev_parse_single(b.as_bytes())?;
match repo.merge_base(a, b) {
Ok(id) => Ok(Some(id.to_string())),
// No common ancestor, a valid outcome for a proposal.
Err(gix::repository::merge_base::Error::NotFound { .. }) => Ok(None),
Err(e) => Err(e.into()),
}
}
/// The commit HEAD points to in the repository at `repo_path`.
///
/// `None` when the repository has no commits yet, an unborn HEAD.
pub fn head_commit_id(repo_path: &Path) -> Result<Option<String>> {
let Ok(repo) = gix::open(repo_path) else {
return Ok(None);
};
match repo.head_id() {
Ok(id) => Ok(Some(id.to_string())),
Err(_) => Ok(None),
}
}
/// The commits in `base..HEAD` of the repository at `repo_path`, oldest first.
/// This is the order `git am` creates them.
///
/// `HEAD` alone when `base` is `None`.
pub fn commits_since(repo_path: &Path, base: Option<&str>) -> Result<Vec<String>> {
let repo = match gix::open(repo_path) {
Ok(repo) => repo,
Err(_) if base.is_none() => return Ok(Vec::new()),
Err(e) => return Err(e.into()),
};
let head = match repo.head_id() {
Ok(head) => head,
Err(_) if base.is_none() => return Ok(Vec::new()),
Err(e) => return Err(e).context("repository has no commits"),
};
let Some(base) = base else {
return Ok(vec![head.to_string()]);
};
let base = repo.rev_parse_single(base.as_bytes())?;
let mut commits = Vec::new();
for info in repo
.rev_walk([head])
.sorting(gix::revision::walk::Sorting::ByCommitTime(
gix::traverse::commit::simple::CommitTimeOrder::NewestFirst,
))
.with_hidden([base])
.all()?
{
commits.push(info?.id().to_string());
}
// Oldest first, like `git rev-list --reverse`, the order `git am` creates them.
commits.reverse();
Ok(commits)
}
/// The identity written to reflogs and commits created by this crate itself.
///
/// Like `git -c user.name=… -c user.email=…` per invocation: the repository works
/// without a global git identity, and `gix` runs no hooks and never signs.
pub(crate) fn repository_signature() -> (gix::actor::Signature, gix::date::parse::TimeBuf) {
let seconds = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_secs() as i64)
.unwrap_or_default();
let signature = gix::actor::Signature {
name: gix::bstr::BString::from("Signed"),
email: gix::bstr::BString::from("signed@localhost"),
time: gix::date::Time { seconds, offset: 0 },
};
(signature, gix::date::parse::TimeBuf::default())
}
/// Create a repository at `path` with an initial `main` branch.
/// Write a `README.md` from `name` and `description`, then create the initial commit.
///
/// Returns the initial commit id.
pub fn init_repository(path: &Path, name: &str, description: &str) -> Result<String> {
use gix::refs::transaction::{Change, LogChange, PreviousValue, RefEdit, RefLog};
std::fs::create_dir_all(path)
.with_context(|| format!("failed to create {}", path.display()))?;
let repo = gix::init(path)?;
let (signature, mut time_buf) = repository_signature();
let signature = signature.to_ref(&mut time_buf);
// The initial branch is `main`, regardless of `init.defaultBranch` in
// the user's git configuration: point the unborn HEAD there.
let head = gix::refs::FullName::try_from("HEAD")
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?;
repo.edit_references_as(
[RefEdit {
change: Change::Update {
log: LogChange {
mode: RefLog::AndReference,
force_create_reflog: false,
message: "checkout: moving to main".into(),
},
expected: PreviousValue::Any,
new: gix::refs::Target::Symbolic(
gix::refs::FullName::try_from("refs/heads/main")
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?,
),
},
name: head,
deref: false,
}],
Some(signature),
)?;
let readme = if description.trim().is_empty() {
format!("# {name}\n")
} else {
format!("# {name}\n\n{description}\n")
};
std::fs::write(path.join("README.md"), &readme).context("failed to write README.md")?;
let blob = repo.write_object(gix::objs::Blob {
data: readme.into_bytes(),
})?;
let tree = repo.write_object(gix::objs::Tree {
entries: vec![gix::objs::tree::Entry {
mode: gix::objs::tree::EntryKind::Blob.into(),
filename: gix::bstr::BString::from("README.md"),
oid: blob.into(),
}],
})?;
let commit = repo.commit_as(
signature,
signature,
"HEAD",
"Initial commit",
tree,
Vec::<gix::ObjectId>::new(),
)?;
// Populate the index so the fresh repository is clean,
// as `git add` and `git commit` would leave it.
let mut index = repo.index_from_tree(&tree)?;
index.write(gix::index::write::Options::default())?;
Ok(commit.to_string())
}
/// The earliest unique commit of the repository at `repo_path`.
/// Used as the NIP-34 announcement's `euc` marker.
///
/// `None` for a repository without commits.
pub fn root_commit(repo_path: &Path) -> Result<Option<String>> {
let Ok(repo) = gix::open(repo_path) else {
return Ok(None);
};
let Ok(head) = repo.head_id() else {
return Ok(None);
};
for info in repo
.rev_walk([head])
.sorting(gix::revision::walk::Sorting::ByCommitTime(
gix::traverse::commit::simple::CommitTimeOrder::NewestFirst,
))
.all()?
{
let info = info?;
if info.parent_ids().next().is_none() {
return Ok(Some(info.id().to_string()));
}
}
Ok(None)
}
/// Full ref names under `prefix`, sorted lexicographically, like `git for-each-ref`.
/// `prefix` is a ref namespace like `refs/fork/<owner>/<id>`.
///
/// Returns an empty list when nothing matches.
pub fn refs_with_prefix(repo_path: &Path, prefix: &str) -> Result<Vec<String>> {
let pattern = prefix.trim_end_matches('/');
let repo = gix::open(repo_path)?;
let mut names = Vec::new();
for reference in repo.references()?.all()? {
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
let name = String::from_utf8_lossy(reference.name().as_bstr()).into_owned();
// Match the pattern itself and everything beneath it, like `git for-each-ref`.
let under_pattern = name
.strip_prefix(pattern)
.is_some_and(|rest| rest.is_empty() || rest.starts_with('/'));
if under_pattern {
names.push(name);
}
}
names.sort();
Ok(names)
}
/// Delete every ref under `prefix` of the repository at `repo_path`.
/// `prefix` is a ref namespace like `refs/fork/<owner>/<id>`.
pub fn delete_refs_with_prefix(repo_path: &Path, prefix: &str) -> Result<()> {
use gix::refs::transaction::{Change, PreviousValue, RefEdit, RefLog};
let refs = refs_with_prefix(repo_path, prefix)?;
if refs.is_empty() {
return Ok(());
}
let repo = gix::open(repo_path)?;
let edits: Vec<RefEdit> = refs
.iter()
.map(|name| {
let full = gix::refs::FullName::try_from(name.as_str())
.map_err(|e| anyhow::anyhow!("invalid ref name {name}: {e}"))?;
Ok(RefEdit {
change: Change::Delete {
expected: PreviousValue::Any,
log: RefLog::AndReference,
},
name: full,
deref: false,
})
})
.collect::<Result<Vec<_>>>()?;
repo.edit_references(edits)?;
Ok(())
}
/// Short name of the branch HEAD points to at `workdir`,
/// `None` when detached or unreadable, like `git branch --show-current`.
pub fn worktree_current_branch(workdir: &Path) -> Option<String> {
let repo = gix::open(workdir).ok()?;
let head = repo.head().ok()?;
let name = head.referent_name()?;
Some(String::from_utf8_lossy(name.shorten()).into_owned())
}
pub fn worktree_ref_exists(workdir: &Path, name: &str) -> bool {
let Ok(repo) = gix::open(workdir) else {
return false;
};
repo.find_reference(name).is_ok()
}
/// Fast-forward local branches that trail their remote-tracking counterpart.
///
/// Returns whether any branch moved.
pub fn fast_forward_branches(workdir: &Path) -> Result<bool> {
let repo = gix::open(workdir)?;
let current = worktree_current_branch(workdir);
let heads = refs_with_prefix(workdir, "refs/heads")?;
let (signature, mut time_buf) = repository_signature();
let signature = signature.to_ref(&mut time_buf);
let mut moved = false;
for head in heads {
let Some(branch) = head.strip_prefix("refs/heads/") else {
continue;
};
let remote = format!("refs/remotes/origin/{branch}");
// No remote-tracking counterpart means the remote lacks this branch.
let Ok(mut remote_reference) = repo.find_reference(&remote) else {
continue;
};
let Ok(mut local_reference) = repo.find_reference(&head) else {
continue;
};
let Ok(remote_oid) = remote_reference.peel_to_id() else {
continue;
};
let Ok(local_oid) = local_reference.peel_to_id() else {
continue;
};
let remote_oid = remote_oid.detach();
let local_oid = local_oid.detach();
if local_oid == remote_oid {
continue;
}
// Only fast-forward.
// Local-only commits or diverged history must never be rewritten by a refresh.
let Ok(base) = repo.merge_base(local_oid, remote_oid) else {
continue;
};
if base != local_oid {
continue;
}
let full = gix::refs::FullName::try_from(head.as_str())
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?;
let edit = |new: gix::refs::Target| {
use gix::refs::transaction::{Change, LogChange, PreviousValue, RefEdit, RefLog};
RefEdit {
change: Change::Update {
log: LogChange {
mode: RefLog::AndReference,
force_create_reflog: false,
message: format!("merge {remote}: Fast-forward").into(),
},
expected: PreviousValue::ExistingMustMatch(gix::refs::Target::Object(
local_oid,
)),
new,
},
name: full.clone(),
deref: false,
}
};
if current.as_deref() == Some(branch) {
// Merge so the checked-out worktree follows the branch.
// Only proceed on a clean worktree, like `git merge --ff-only`.
if worktree_dirty(workdir) {
continue;
}
let tree = repo.find_object(remote_oid)?.peel_to_tree()?.id;
force_checkout(&repo, &tree)?;
repo.edit_references_as(
[edit(gix::refs::Target::Object(remote_oid))],
Some(signature),
)?;
moved = true;
} else {
repo.edit_references_as(
[edit(gix::refs::Target::Object(remote_oid))],
Some(signature),
)?;
moved = true;
}
}
Ok(moved)
}
/// Short names of local branches, `refs/heads/*`, of `repo`, sorted alphabetically.
pub fn repo_branches(repo: &gix::Repository) -> Result<Vec<String>> {
let mut names = Vec::new();
for reference in repo.references()?.local_branches()? {
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
names.push(String::from_utf8_lossy(reference.name().shorten()).into_owned());
}
names.sort();
Ok(names)
}
/// Short names of tags, `refs/tags/*`, of `repo`, sorted alphabetically.
pub fn repo_tags(repo: &gix::Repository) -> Result<Vec<String>> {
let mut names = Vec::new();
for reference in repo.references()?.tags()? {
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
names.push(String::from_utf8_lossy(reference.name().shorten()).into_owned());
}
names.sort();
Ok(names)
}
/// Short names of local branches, `refs/heads/*`, sorted alphabetically.
pub fn worktree_branches(workdir: &Path) -> Result<Vec<String>> {
repo_branches(&gix::open(workdir)?)
}
/// Short name of the branch HEAD points to, or `None` when detached.
///
/// Detached after checking out a tag or a commit directly.
pub fn current_branch(repo: &gix::Repository) -> Result<Option<String>> {
let head = repo.head()?;
let Some(name) = head.referent_name() else {
return Ok(None);
};
Ok(Some(String::from_utf8_lossy(name.shorten()).into_owned()))
}
/// Branch, tag and HEAD refs of a repository.
///
/// Ready for a NIP-34 kind-30618 repository state announcement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoRefState {
/// `(full refname, commit id)` pairs for heads and tags, sorted.
pub refs: Vec<(String, String)>,
/// Short branch name HEAD points to, or `None` when detached.
pub head: Option<String>,
}
pub fn repo_ref_state(repo: &gix::Repository) -> Result<RepoRefState> {
let mut refs = Vec::new();
for reference in repo.references()?.local_branches()? {
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
refs.push((
String::from_utf8_lossy(reference.name().as_bstr()).into_owned(),
reference.id().to_string(),
));
}
for reference in repo.references()?.tags()? {
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
refs.push((
String::from_utf8_lossy(reference.name().as_bstr()).into_owned(),
reference.id().to_string(),
));
}
refs.sort();
let head = match repo.head() {
Ok(head) => head
.referent_name()
.filter(|name| name.as_bstr().starts_with(b"refs/heads/"))
.map(|name| String::from_utf8_lossy(name.shorten()).into_owned()),
Err(_) => None,
};
Ok(RepoRefState { refs, head })
}
pub fn worktree_ref_state(workdir: &Path) -> Result<RepoRefState> {
repo_ref_state(&gix::open(workdir)?)
}
+56
View File
@@ -0,0 +1,56 @@
use std::path::{Path, PathBuf};
use ignore::WalkBuilder;
use crate::nip34::{Nip34Binding, detect_nip34};
/// Caps nesting so pathological trees can't stall the scan.
const SCAN_MAX_DEPTH: usize = 12;
/// A git repository discovered under a scan root.
#[derive(Debug, Clone)]
pub struct LocalRepo {
pub path: PathBuf,
/// `None` for a plain repository.
pub nip34: Option<Nip34Binding>,
}
/// Walk `root` recursively and collect the git repositories below it.
pub fn find_git_repos(root: &Path) -> Vec<LocalRepo> {
if !root.is_dir() {
return Vec::new();
}
let walker = WalkBuilder::new(root)
.max_depth(Some(SCAN_MAX_DEPTH))
// Honour `.gitignore` even when the scan root is not itself a repository.
.require_git(false)
.build();
let mut repos: Vec<PathBuf> = walker
.flatten()
.filter(|entry| entry.file_type().is_some_and(|kind| kind.is_dir()))
.map(ignore::DirEntry::into_path)
.filter(|dir| dir.join(".git").exists())
.filter_map(|dir| dir.canonicalize().ok())
.collect();
repos.sort();
repos.dedup();
// A repository nested inside another, like a submodule worktree, is not reported.
let mut roots: Vec<PathBuf> = Vec::with_capacity(repos.len());
for repo in repos {
if !roots.iter().any(|kept| repo.starts_with(kept)) {
roots.push(repo);
}
}
roots
.into_iter()
.map(|path| {
let nip34 = detect_nip34(&path);
LocalRepo { path, nip34 }
})
.collect()
}
File diff suppressed because it is too large Load Diff
+334
View File
@@ -0,0 +1,334 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use gix::progress::Discard;
use crate::history::{FileCommit, head_commit};
use crate::repo::{current_branch, repository_signature};
/// Whether the worktree of `workdir` has uncommitted changes.
///
/// Best-effort: any read failure is reported as clean.
pub fn worktree_dirty(workdir: &Path) -> bool {
let Ok(repo) = gix::open(workdir) else {
return false;
};
// Changes to tracked files, staged or not; untracked files are excluded.
match repo.is_dirty() {
Ok(true) => return true,
Ok(false) => {}
Err(_) => return false,
}
// Untracked files surface as `DirectoryContents` items of the index-vs-worktree walk,
// tracked files only appear there when modified.
let Ok(platform) = repo.status(Discard) else {
return false;
};
let Ok(mut changes) = platform.into_index_worktree_iter(Vec::<gix::bstr::BString>::new())
else {
return false;
};
for change in changes.by_ref() {
match change {
Ok(gix::status::index_worktree::Item::DirectoryContents { .. }) => return true,
Ok(_) => {}
Err(_) => return false,
}
}
false
}
/// Commits in `base..branch` of the checkout at `workdir`.
///
/// Best-effort: 0 when the range cannot be computed.
pub fn worktree_commits_ahead(workdir: &Path, base: &str, branch: &str) -> u32 {
let Ok(repo) = gix::open(workdir) else {
return 0;
};
let (Some(base), Some(branch)) = (resolve_commit(&repo, base), resolve_commit(&repo, branch))
else {
return 0;
};
let Ok(walk) = repo.rev_walk([branch]).with_hidden([base]).all() else {
return 0;
};
walk.filter_map(Result::ok).count().min(u32::MAX as usize) as u32
}
/// Resolve `rev` to a commit id, accepting full refs or the bare branch names
/// callers pass. `gix`'s revision parser already applies git's ref DWIM.
fn resolve_commit<'a>(repo: &'a gix::Repository, rev: &str) -> Option<gix::Id<'a>> {
repo.rev_parse_single(rev.as_bytes()).ok()
}
/// Relative paths of all entries in the worktree, files and directories.
///
/// The `.git` directory is skipped.
pub fn worktree_entries(repo: &gix::Repository) -> Result<Vec<PathBuf>> {
let workdir = repo.workdir().context("repository has no worktree")?;
let mut entries: Vec<(PathBuf, bool)> = Vec::new();
collect_entries(workdir, workdir, &mut entries)?;
entries.sort_by(|(a, a_is_dir), (b, b_is_dir)| {
b_is_dir
.cmp(a_is_dir)
.then_with(|| a.as_os_str().cmp(b.as_os_str()))
});
Ok(entries.into_iter().map(|(path, _)| path).collect())
}
/// Read a file from the worktree.
///
/// Returns `Ok(None)` if the path is missing or not a regular file.
pub fn worktree_read(repo: &gix::Repository, rel: &Path) -> Result<Option<Vec<u8>>> {
let workdir = repo.workdir().context("repository has no worktree")?;
let path = workdir.join(rel);
match std::fs::read(&path) {
Ok(bytes) => Ok(Some(bytes)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) if e.kind() == std::io::ErrorKind::IsADirectory => Ok(None),
Err(e) => Err(e).with_context(|| format!("failed to read {}", path.display())),
}
}
/// Find the README file in the repository root.
///
/// Falls back to any other file whose name starts with `readme`.
pub fn find_readme(repo: &gix::Repository) -> Result<Option<PathBuf>> {
let Some(workdir) = repo.workdir() else {
return Ok(None);
};
let mut candidates: Vec<PathBuf> = Vec::new();
for entry in std::fs::read_dir(workdir)? {
let entry = entry?;
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
if name.to_ascii_lowercase().starts_with("readme") {
candidates.push(entry.path());
}
}
candidates.sort_by_key(|path| {
let ext = path
.extension()
.map(|e| e.to_string_lossy().to_ascii_lowercase());
match ext.as_deref() {
Some("md") => 0,
Some("markdown") => 1,
Some("mdown") => 2,
Some("mkdn") => 3,
Some(_) => 5,
None => 4,
}
});
Ok(candidates
.into_iter()
.next()
.and_then(|path| path.strip_prefix(workdir).ok().map(Path::to_path_buf)))
}
/// Everything the browser needs to refresh after a branch or tag switch.
pub struct WorktreeSnapshot {
/// Relative paths of all worktree entries, directories first.
pub entries: Vec<PathBuf>,
/// README path relative to the worktree, if any.
pub readme_path: Option<PathBuf>,
/// Contents of the README, if any.
pub readme: Option<Vec<u8>>,
/// Branch HEAD points to, `None` when detached, for example on a tag.
pub current_branch: Option<String>,
/// Commit HEAD points to, if any, see [`head_commit`].
pub head_commit: Option<FileCommit>,
}
/// Collects entries, the README, the branch HEAD points to and its commit.
pub fn worktree_snapshot(workdir: &Path) -> Result<WorktreeSnapshot> {
let repo = gix::open(workdir)?;
let readme_path = find_readme(&repo)?;
let readme = match &readme_path {
Some(path) => worktree_read(&repo, path)?,
None => None,
};
Ok(WorktreeSnapshot {
entries: worktree_entries(&repo)?,
readme_path,
readme,
current_branch: current_branch(&repo)?,
head_commit: head_commit(&repo)?,
})
}
pub(crate) fn force_checkout(repo: &gix::Repository, tree: &gix::hash::oid) -> Result<()> {
let workdir = repo
.workdir()
.context("repository has no worktree")?
.to_path_buf();
let mut index = repo.index_from_tree(tree)?;
// Files the previous index tracked but `tree` no longer contains are removed,
// like git deleting files that vanish between branches.
if let Ok(previous) = repo.index_or_empty() {
let keep: HashSet<PathBuf> = index
.entries()
.iter()
.map(|entry| PathBuf::from(String::from_utf8_lossy(entry.path(&index)).into_owned()))
.collect();
for entry in previous.entries() {
let rel = entry.path(&previous);
let rel = PathBuf::from(String::from_utf8_lossy(rel).into_owned());
if keep.contains(&rel) {
continue;
}
let path = workdir.join(&rel);
match std::fs::remove_file(&path) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(error)
.with_context(|| format!("failed to remove {}", path.display()));
}
}
}
}
let mut options =
repo.checkout_options(gix_worktree::stack::state::attributes::Source::IdMapping)?;
options.overwrite_existing = true;
let objects = repo.objects.clone().into_arc()?;
let files = gix::progress::Discard;
let bytes = gix::progress::Discard;
gix_worktree_state::checkout(
&mut index,
workdir,
objects,
&files,
&bytes,
&gix::interrupt::IS_INTERRUPTED,
options,
)?;
index.write(gix::index::write::Options::default())?;
Ok(())
}
/// Point `HEAD` at `target` and record the switch in the reflog.
fn move_head(
repo: &gix::Repository,
signature: gix::actor::SignatureRef<'_>,
target: gix::refs::Target,
message: &str,
) -> Result<()> {
use gix::refs::transaction::{Change, LogChange, PreviousValue, RefEdit, RefLog};
let head = gix::refs::FullName::try_from("HEAD")
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?;
repo.edit_references_as(
[RefEdit {
change: Change::Update {
log: LogChange {
mode: RefLog::AndReference,
force_create_reflog: false,
message: message.into(),
},
expected: PreviousValue::Any,
new: target,
},
name: head,
deref: false,
}],
Some(signature),
)?;
Ok(())
}
/// Check out the local branch `name`, HEAD stays attached to it.
pub fn worktree_checkout_branch(workdir: &Path, name: &str) -> Result<()> {
let repo = gix::open(workdir)?;
let full = format!("refs/heads/{name}");
let branch = gix::refs::FullName::try_from(full.as_str())
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?;
let mut reference = repo.find_reference(&full)?;
let tree = reference.peel_to_tree()?.id;
let (signature, mut time_buf) = repository_signature();
let signature = signature.to_ref(&mut time_buf);
move_head(
&repo,
signature,
gix::refs::Target::Symbolic(branch),
&format!("checkout: moving to {name}"),
)?;
force_checkout(&repo, &tree)?;
Ok(())
}
/// Check out the tag `name`, HEAD becomes detached at the tagged commit.
pub fn worktree_checkout_tag(workdir: &Path, name: &str) -> Result<()> {
let repo = gix::open(workdir)?;
let full = format!("refs/tags/{name}");
let mut reference = repo.find_reference(&full)?;
let commit = reference.peel_to_id()?;
let tree = reference.peel_to_tree()?.id;
let (signature, mut time_buf) = repository_signature();
let signature = signature.to_ref(&mut time_buf);
move_head(
&repo,
signature,
gix::refs::Target::Object(commit.detach()),
&format!("checkout: moving to {name}"),
)?;
force_checkout(&repo, &tree)?;
Ok(())
}
fn collect_entries(root: &Path, dir: &Path, out: &mut Vec<(PathBuf, bool)>) -> Result<()> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
if entry.file_name() == ".git" {
continue;
}
let is_dir = entry.file_type()?.is_dir();
let path = entry.path();
let rel = path.strip_prefix(root)?.to_path_buf();
out.push((rel, is_dir));
if is_dir {
collect_entries(root, &path, out)?;
}
}
Ok(())
}
+16 -39
View File
@@ -5,32 +5,9 @@ use std::pin::Pin;
use std::sync::{Arc, RwLock};
use nostr_connect::client::AuthUrlHandler;
use nostr_sdk::error::Error as SignerError;
use nostr_sdk::prelude::*;
#[derive(Debug)]
pub struct UniversalSignerError(Box<dyn Error + Send + Sync + 'static>);
impl fmt::Display for UniversalSignerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Error for UniversalSignerError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.0)
}
}
impl UniversalSignerError {
pub fn new<E>(err: E) -> Self
where
E: Error + Send + Sync + 'static,
{
UniversalSignerError(Box::new(err))
}
}
/// A type-erased signer whose inner signer can be swapped in-place.
#[derive(Clone, Debug)]
pub struct UniversalSigner {
@@ -65,21 +42,21 @@ impl UniversalSigner {
trait InnerSigner: fmt::Debug + Send + Sync + 'static {
fn get_public_key_async(
&self,
) -> Pin<Box<dyn Future<Output = Result<PublicKey, UniversalSignerError>> + Send + '_>>;
) -> Pin<Box<dyn Future<Output = Result<PublicKey, SignerError>> + Send + '_>>;
fn sign_event_async(
&self,
unsigned: UnsignedEvent,
) -> Pin<Box<dyn Future<Output = Result<Event, UniversalSignerError>> + Send + '_>>;
) -> Pin<Box<dyn Future<Output = Result<Event, SignerError>> + Send + '_>>;
fn nip44_encrypt_async<'a>(
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, UniversalSignerError>> + Send + 'a>>;
) -> Pin<Box<dyn Future<Output = Result<String, SignerError>> + Send + 'a>>;
fn nip44_decrypt_async<'a>(
&'a self,
public_key: &'a PublicKey,
payload: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, UniversalSignerError>> + Send + 'a>>;
) -> Pin<Box<dyn Future<Output = Result<String, SignerError>> + Send + 'a>>;
}
#[derive(Debug)]
@@ -94,22 +71,22 @@ where
{
fn get_public_key_async(
&self,
) -> Pin<Box<dyn Future<Output = Result<PublicKey, UniversalSignerError>> + Send + '_>> {
) -> Pin<Box<dyn Future<Output = Result<PublicKey, SignerError>> + Send + '_>> {
Box::pin(async move {
AsyncGetPublicKey::get_public_key_async(&self.0)
.await
.map_err(UniversalSignerError::new)
.map_err(SignerError::other)
})
}
fn sign_event_async(
&self,
unsigned: UnsignedEvent,
) -> Pin<Box<dyn Future<Output = Result<Event, UniversalSignerError>> + Send + '_>> {
) -> Pin<Box<dyn Future<Output = Result<Event, SignerError>> + Send + '_>> {
Box::pin(async move {
AsyncSignEvent::sign_event_async(&self.0, unsigned)
.await
.map_err(UniversalSignerError::new)
.map_err(SignerError::other)
})
}
@@ -117,11 +94,11 @@ where
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, UniversalSignerError>> + Send + 'a>> {
) -> Pin<Box<dyn Future<Output = Result<String, SignerError>> + Send + 'a>> {
Box::pin(async move {
AsyncNip44::nip44_encrypt_async(&self.0, public_key, content)
.await
.map_err(UniversalSignerError::new)
.map_err(SignerError::other)
})
}
@@ -129,17 +106,17 @@ where
&'a self,
public_key: &'a PublicKey,
payload: &'a str,
) -> Pin<Box<dyn Future<Output = Result<String, UniversalSignerError>> + Send + 'a>> {
) -> Pin<Box<dyn Future<Output = Result<String, SignerError>> + Send + 'a>> {
Box::pin(async move {
AsyncNip44::nip44_decrypt_async(&self.0, public_key, payload)
.await
.map_err(UniversalSignerError::new)
.map_err(SignerError::other)
})
}
}
impl AsyncGetPublicKey for UniversalSigner {
type Error = UniversalSignerError;
type Error = SignerError;
fn get_public_key_async(
&self,
@@ -150,7 +127,7 @@ impl AsyncGetPublicKey for UniversalSigner {
}
impl AsyncSignEvent for UniversalSigner {
type Error = UniversalSignerError;
type Error = SignerError;
fn sign_event_async(
&self,
@@ -162,7 +139,7 @@ impl AsyncSignEvent for UniversalSigner {
}
impl AsyncNip44 for UniversalSigner {
type Error = UniversalSignerError;
type Error = SignerError;
fn nip44_encrypt_async<'a>(
&'a self,
-1
View File
@@ -10,7 +10,6 @@ pub struct Update {
}
impl Update {
/// Build an update from a received event.
pub fn from_event(event: &Event) -> Self {
let coordinate = event.tags.coordinates().nth(0);
+2
View File
@@ -17,11 +17,13 @@ nostr-connect.workspace = true
bitcoin_hashes = "1"
gix.workspace = true
gpui.workspace = true
flume.workspace = true
futures.workspace = true
anyhow.workspace = true
log.workspace = true
serde_json.workspace = true
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rustls = "0.23"
File diff suppressed because it is too large Load Diff
+330 -267
View File
@@ -1,30 +1,34 @@
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::Error;
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task};
use gpui::{App, AppContext, Context, Entity, Global, Subscription};
use nostr::prelude::*;
use settings::{CheckoutRecord, SettingsStore};
use signed_core::{Announcement, RepoAddr};
use crate::backend::{Backend, BackendEvent};
use crate::git_store::GitStore;
use crate::git_store::repo_mirror_root;
use crate::local_repos::LocalReposStore;
use crate::refresh::{RefreshGate, RefreshRequest};
use crate::repo_list::RepoListStore;
use crate::repos::RepoListStore;
/// Delay between a refresh request and the actual re-computation.
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
/// How often the statuses of open repository panels are refreshed.
/// How often the statuses are recomputed against the local refs.
///
/// A commit lands in a checkout long before the remote reconciliation cadence,
/// so this fast pass surfaces ready-to-push and ready-to-contribute checkouts
/// within a second or two. It reads the tracking refs only, no network.
const LOCAL_POLL: Duration = Duration::from_secs(2);
/// How often a full pass refreshes the remotes while any repository panel is open.
const STATUS_POLL: Duration = Duration::from_secs(15);
/// Background poll interval for the `ready to push` badges of the user's own repositories.
/// Remote refresh interval for the `ready to push` badges of the user's own repositories.
const PUSH_POLL: Duration = Duration::from_secs(60);
/// Maximum checkouts considered per repository when computing statuses.
const MAX_STATUS_CHECKOUTS: usize = 8;
struct GlobalCheckoutsStore(Entity<CheckoutsStore>);
@@ -36,7 +40,6 @@ impl Global for GlobalCheckoutsStore {}
/// Carries the git facts needed to suggest a pull request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckoutStatus {
/// The checkout folder.
pub path: PathBuf,
/// The branch checked out. A detached checkout is idle and yields no status.
pub branch: String,
@@ -64,10 +67,17 @@ struct Remembered {
}
/// Global store of local-checkout associations and per-checkout statuses.
///
/// Readers (the sidebar rows, the repository panels) observe this store and
/// derive what they display from their own snapshots, so publishing needs no
/// fine-grained entities: the store notifies when a slice changed and each
/// reader re-derives only what it shows.
pub struct CheckoutsStore {
/// Checkout paths per announced repository.
by_repo: HashMap<RepoAddr, Vec<PathBuf>>,
/// Ready-to-contribute statuses of the requested repositories.
///
/// Those are the repository detail panels currently open.
statuses: HashMap<RepoAddr, Vec<CheckoutStatus>>,
/// Repositories whose statuses are recomputed on every input change.
///
@@ -77,20 +87,25 @@ pub struct CheckoutsStore {
///
/// The sidebar rows of the user's own repositories and their detail panels.
push_requested: HashSet<RepoAddr>,
/// Ready-to-push statuses of the requested own repositories.
/// The ready-to-push statuses of the requested own repositories.
push_statuses: HashMap<RepoAddr, Vec<CheckoutStatus>>,
/// Last announced head branch per requested repository.
///
/// A recompute defaults the base the same way.
requested_head: HashMap<RepoAddr, Option<String>>,
/// Refresh coalescing, see [`RefreshGate`].
refresh: RefreshGate,
/// True while the timer between a scheduled refresh and its run is pending.
debounce_pending: bool,
local_pending: bool,
/// When the last full pass (with a remote refresh) completed.
///
/// The local pass runs a full pass again once this is older than the
/// reconciliation cadence, so remote moves still land.
last_full_sync: Option<Instant>,
_subscriptions: Vec<Subscription>,
tasks: Vec<Task<Result<(), Error>>>,
}
impl CheckoutsStore {
/// Retrieve the global checkouts store.
pub fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalCheckoutsStore>().0.clone()
}
@@ -99,7 +114,6 @@ impl CheckoutsStore {
cx.set_global(GlobalCheckoutsStore(entity));
}
/// Create the store.
pub fn new(cx: &mut Context<Self>) -> Self {
let mut subscriptions = Vec::new();
@@ -122,20 +136,29 @@ impl CheckoutsStore {
}));
// Another identity's repositories must not keep the old statuses alive.
// Their polls stop too.
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
if matches!(event, BackendEvent::SignerChanged) {
this.status_requested.clear();
this.push_requested.clear();
this.requested_head.clear();
this.statuses = HashMap::new();
this.push_statuses = HashMap::new();
this.statuses.clear();
this.push_statuses.clear();
cx.notify();
this.refresh(cx);
}
}));
}
let mut store = Self {
if !cfg!(target_arch = "wasm32") {
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.refresh(cx)) {
log::warn!("checkouts store dropped before initial refresh could run: {error}");
}
});
}
Self {
by_repo: HashMap::new(),
statuses: HashMap::new(),
status_requested: HashSet::new(),
@@ -143,26 +166,13 @@ impl CheckoutsStore {
push_statuses: HashMap::new(),
requested_head: HashMap::new(),
refresh: RefreshGate::default(),
debounce_pending: false,
local_pending: false,
last_full_sync: None,
_subscriptions: subscriptions,
tasks: Vec::new(),
};
if !cfg!(target_arch = "wasm32") {
store.refresh(cx);
}
store
}
/// Track a spawned task, pruning finished tasks first.
///
/// Keeps the store's task list bounded by the number of in-flight tasks.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
/// Remember a successful local-checkout use.
pub fn record(&mut self, path: PathBuf, addr: RepoAddr, cx: &mut Context<Self>) {
if cfg!(target_arch = "wasm32") {
return;
@@ -218,7 +228,7 @@ impl CheckoutsStore {
/// The ready-to-contribute statuses of `addr`.
///
/// Empty while none are known or nothing is ahead.
pub fn statuses_of(&self, addr: &RepoAddr) -> Vec<CheckoutStatus> {
pub fn ready_statuses_of(&self, addr: &RepoAddr) -> Vec<CheckoutStatus> {
self.statuses.get(addr).cloned().unwrap_or_default()
}
@@ -228,36 +238,78 @@ impl CheckoutsStore {
self.refresh(cx);
}
/// The checkout at `path` was just pushed to the remote.
///
/// Its ready-to-push status is obsolete. Drop it from the cached statuses
/// and notify observers right away, so the sidebar badge and the push
/// banner update immediately instead of waiting for the next background
/// pass, which re-scans and re-fetches the remote. The debounced refresh
/// reconciles the remaining checkouts of the repository afterwards.
pub fn checkout_pushed(&mut self, addr: &RepoAddr, path: &Path, cx: &mut Context<Self>) {
let mut removed = false;
if let Some(statuses) = self.push_statuses.get_mut(addr) {
let before = statuses.len();
statuses.retain(|status| status.path.as_path() != path);
removed = statuses.len() != before;
if removed && statuses.is_empty() {
self.push_statuses.remove(addr);
}
}
if removed {
cx.notify();
}
// The other checkouts of this repository still need re-deriving
// against the remote, now that the pushed refs landed there.
self.request_push_statuses(addr, cx);
}
/// The ready-to-push statuses of `addr`.
/// Only meaningful for repositories announced by the signed-in user.
///
/// Empty while none are known or nothing is unpushed.
pub fn push_statuses_of(&self, addr: &RepoAddr) -> Vec<CheckoutStatus> {
self.push_statuses.get(addr).cloned().unwrap_or_default()
}
pub fn unpushed(&self, addr: &RepoAddr) -> usize {
self.push_statuses
.get(addr)
.map(|list| list.iter().map(|status| status.ahead as usize).sum())
.unwrap_or(0)
}
/// Re-resolve the associations and the requested statuses.
///
/// Requests arriving while a pass runs fold into a follow-up.
/// Requests arriving while a pass runs fold into a follow-up, requests
/// arriving while the debounce timer is pending are dropped.
pub fn refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() != RefreshRequest::Schedule {
if self.debounce_pending || self.refresh.request() != RefreshRequest::Schedule {
return;
}
let task = cx.spawn(async move |this, cx| {
self.debounce_pending = true;
cx.spawn(async move |this, cx| {
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
this.update(cx, |this, cx| this.run_refresh(cx))
});
self.push_task(task);
})
.detach();
}
/// One resolve and apply cycle, the debounced entry point.
/// One full resolve and apply cycle, the debounced entry point.
///
/// Re-resolves the associations from the settings, the scan and the
/// announcements, then recomputes the requested statuses against freshly
/// fetched remotes. Full passes run on every input change and on the
/// remote reconciliation cadence ([`Self::local_tick`]); they also restart
/// the fast local pass.
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.debounce_pending = false;
self.refresh.begin();
// Inputs snapshot, all cheap shared reads.
let records = {
let settings = SettingsStore::global(cx);
settings.read(cx).settings().checkouts.records.clone()
@@ -277,7 +329,7 @@ impl CheckoutsStore {
let announcements = RepoListStore::global(cx).read(cx).announcements.clone();
let scanned = LocalReposStore::global(cx).read(cx).repos.clone();
let cache_root = GitStore::global(cx).cache().root().canonicalize().ok();
let cache_root = repo_mirror_root().canonicalize().ok();
let requested: Vec<(RepoAddr, Option<String>)> = self
.status_requested
@@ -298,7 +350,9 @@ impl CheckoutsStore {
//
// The facts are the origin URL and the root commit, both CLI reads.
let mut facts: Vec<(PathBuf, Option<String>, Option<String>)> = Vec::new();
for path in scanned.iter() {
for scanned in scanned.iter() {
let path = &scanned.path;
// The browser's mirror clones share the announce URLs and EUCs. They are not user checkouts.
if cache_root
.as_ref()
@@ -319,56 +373,42 @@ impl CheckoutsStore {
.map(|(addr, paths)| (addr, paths.into_iter().filter(|p| p.is_dir()).collect()))
.collect();
let mut statuses: HashMap<RepoAddr, Vec<CheckoutStatus>> = HashMap::new();
for (addr, announced_head) in &requested {
let Some(paths) = associations.get(addr) else {
continue;
};
let list: Vec<CheckoutStatus> = paths
.iter()
.take(MAX_STATUS_CHECKOUTS)
.filter_map(|path| checkout_status(path, announced_head.as_deref()))
.collect();
if !list.is_empty() {
statuses.insert(addr.clone(), list);
}
}
let mut push_statuses: HashMap<RepoAddr, Vec<CheckoutStatus>> = HashMap::new();
for addr in &push_requested {
let Some(paths) = associations.get(addr) else {
continue;
};
let list: Vec<CheckoutStatus> = paths
.iter()
.take(MAX_STATUS_CHECKOUTS)
.filter_map(|path| checkout_push_status(path))
.collect();
if !list.is_empty() {
push_statuses.insert(addr.clone(), list);
}
}
let (statuses, push_statuses) =
compute_statuses(&associations, &requested, &push_requested, true);
Ok::<_, Error>((associations, statuses, push_statuses))
});
self.push_task(cx.spawn(async move |this, cx| {
cx.spawn(async move |this, cx| {
let (associations, statuses, push_statuses) = match work.await {
Ok(results) => results,
Err(_) => {
// Git reads are best-effort, keep the last results.
return this.update(cx, |this, _cx| {
return this.update(cx, |this, cx| {
this.refresh.abort();
if poll {
this.schedule_local_pass(cx);
}
});
}
};
let again = this.update(cx, |this, cx| {
let associations_changed = this.by_repo != associations;
let statuses_changed = this.statuses != statuses;
let push_statuses_changed = this.push_statuses != push_statuses;
this.by_repo = associations;
this.statuses = statuses;
this.push_statuses = push_statuses;
cx.notify();
// Notify only when something actually changed, so observers
// skip the no-op heartbeats.
if associations_changed || statuses_changed || push_statuses_changed {
cx.notify();
}
this.last_full_sync = Some(Instant::now());
this.refresh.finish()
})?;
@@ -376,33 +416,136 @@ impl CheckoutsStore {
this.update(cx, |this, cx| this.refresh(cx))?;
}
// Keep the statuses current while any repository panel is open.
// Restart the fast local pass so the freshly resolved
// associations drive it. The pass itself decides when the next
// full pass runs.
this.update(cx, |this, cx| {
if poll && this.refresh.idle() {
this.refresh.debounce();
// Open panels get the fast cadence.
// Each cycle fetches every watched checkout's remote.
let delay = if this.status_requested.is_empty() {
PUSH_POLL
} else {
STATUS_POLL
};
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(delay).await;
this.update(cx, |this, cx| this.run_refresh(cx))
});
this.push_task(task);
if poll {
this.schedule_local_pass(cx);
}
})?;
Ok(())
}));
})
.detach();
}
/// Schedule the fast local status pass, unless one is already pending.
///
/// Every [`LOCAL_POLL`] the pass recomputes the requested statuses against
/// the local refs, with no network, so a new commit in a checkout surfaces in
/// a second or two instead of at the next remote reconciliation.
fn schedule_local_pass(&mut self, cx: &mut Context<Self>) {
if self.local_pending {
return;
}
self.local_pending = true;
cx.spawn(async move |this, cx| {
cx.background_executor().timer(LOCAL_POLL).await;
this.update(cx, |this, cx| {
this.local_pending = false;
this.local_tick(cx);
})
})
.detach();
}
/// The fast local status pass.
///
/// Recomputes the statuses against the local refs; when the remote
/// reconciliation cadence elapsed, it runs a full pass instead so pushes
/// made elsewhere do not linger as `to push`.
fn local_tick(&mut self, cx: &mut Context<Self>) {
// Nothing watched: the chain idles out until a new request restarts it.
if self.status_requested.is_empty() && self.push_requested.is_empty() {
return;
}
// A full pass or a fresh request covers this tick, skip it.
if self.refresh.running() || self.debounce_pending {
self.schedule_local_pass(cx);
return;
}
// Open panels get the faster remote cadence.
let cadence = if self.status_requested.is_empty() {
PUSH_POLL
} else {
STATUS_POLL
};
let full_due = self
.last_full_sync
.is_none_or(|sync| sync.elapsed() >= cadence);
if full_due {
self.last_full_sync = Some(Instant::now());
self.refresh(cx);
} else {
self.run_local_statuses(cx);
}
self.schedule_local_pass(cx);
}
/// Recompute the requested statuses against the tracking refs only.
///
/// The refs were last refreshed by a full pass. Comparing against them is
/// enough to pick up new local commits, and skipping the network keeps
/// this pass cheap enough to run every [`LOCAL_POLL`].
fn run_local_statuses(&mut self, cx: &mut Context<Self>) {
let associations = self.by_repo.clone();
let requested: Vec<(RepoAddr, Option<String>)> = self
.status_requested
.iter()
.map(|addr| {
(
addr.clone(),
self.requested_head.get(addr).cloned().flatten(),
)
})
.collect();
let push_requested: Vec<RepoAddr> = self.push_requested.iter().cloned().collect();
let work = cx.background_spawn(async move {
let (statuses, push_statuses) =
compute_statuses(&associations, &requested, &push_requested, false);
Ok::<_, Error>((statuses, push_statuses))
});
let task: gpui::Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let Ok((statuses, push_statuses)) = work.await else {
// Git reads are best-effort, keep the last results.
return Ok(());
};
this.update(cx, |this, cx| {
// A full pass or a fresh request will apply fresher data
// (the tracking refs move only when a full pass fetches).
if this.refresh.running() || this.debounce_pending {
return;
}
let statuses_changed = this.statuses != statuses;
let push_statuses_changed = this.push_statuses != push_statuses;
this.statuses = statuses;
this.push_statuses = push_statuses;
if statuses_changed || push_statuses_changed {
cx.notify();
}
})?;
Ok(())
});
task.detach();
}
}
/// Identity of a repository URL.
fn url_identity(url: &str) -> Option<(String, Option<u16>, String)> {
let parsed = Url::parse(url).ok()?;
let host = parsed.host_str()?.to_ascii_lowercase();
@@ -413,7 +556,6 @@ fn url_identity(url: &str) -> Option<(String, Option<u16>, String)> {
Some((host, parsed.port(), path))
}
/// Whether two repository URLs point at the same repository.
fn same_repo_url(a: &str, b: &str) -> bool {
match (url_identity(a), url_identity(b)) {
(Some(a), Some(b)) => a == b,
@@ -421,7 +563,6 @@ fn same_repo_url(a: &str, b: &str) -> bool {
}
}
/// Resolve the associations between local checkouts and announced repositories.
fn resolve_associations<'a>(
remembered: &[Remembered],
scanned: &[(PathBuf, Option<String>, Option<String>)],
@@ -464,67 +605,26 @@ fn resolve_associations<'a>(
out
}
/// Whether the worktree of `path` has uncommitted changes.
fn worktree_dirty(path: &Path) -> bool {
let output = Command::new("git")
.arg("-C")
.arg(path)
.args(["status", "--porcelain"])
.env("GIT_TERMINAL_PROMPT", "0")
.output();
match output {
Ok(output) => !String::from_utf8_lossy(&output.stdout).trim().is_empty(),
Err(_) => false,
}
}
/// Commits in `base..branch` of the checkout at `path`.
fn commits_ahead(path: &Path, base: &str, branch: &str) -> u32 {
let output = Command::new("git")
.arg("-C")
.arg(path)
.args(["rev-list", "--count", &format!("{base}..{branch}")])
.env("GIT_TERMINAL_PROMPT", "0")
.output();
match output {
Ok(output) => String::from_utf8_lossy(&output.stdout)
.trim()
.parse()
.unwrap_or(0),
Err(_) => 0,
}
}
/// The branch checked out at `path`, read via `git branch --show-current`.
fn current_branch_of(path: &Path) -> Option<String> {
let output = Command::new("git")
.arg("-C")
.arg(path)
.args(["branch", "--show-current"])
.env("GIT_TERMINAL_PROMPT", "0")
.output()
.ok()?;
let branch = String::from_utf8_lossy(&output.stdout).trim().to_owned();
(!branch.is_empty()).then_some(branch)
}
/// The ready-to-contribute status of one checkout.
fn checkout_status(path: &Path, announced_head: Option<&str>) -> Option<CheckoutStatus> {
let branches = signed_git::worktree_branches(path).ok()?;
if branches.is_empty() || worktree_dirty(path) {
if branches.is_empty() || signed_git::worktree_dirty(path) {
return None;
}
let branch = current_branch_of(path)?;
let branch = signed_git::worktree_current_branch(path)?;
let head = signed_git::head_commit_id(path).ok().flatten()?;
let base = announced_head
.filter(|name| branches.iter().any(|b| b == name))
.map(str::to_owned)
.or_else(|| branches.iter().find(|b| *b == "main").cloned())
.or_else(|| branches.first().cloned())?;
if base == branch {
return None;
}
let ahead = commits_ahead(path, &base, &branch);
let ahead = signed_git::worktree_commits_ahead(path, &base, &branch);
(ahead > 0).then_some(CheckoutStatus {
path: path.to_path_buf(),
branch,
@@ -534,43 +634,40 @@ fn checkout_status(path: &Path, announced_head: Option<&str>) -> Option<Checkout
})
}
/// Whether the reference `name` exists in the checkout at `path`.
///
/// Example, `refs/remotes/origin/main`.
fn ref_exists(path: &Path, name: &str) -> bool {
let output = Command::new("git")
.arg("-C")
.arg(path)
.args(["rev-parse", "--verify", "--quiet", name])
.env("GIT_TERMINAL_PROMPT", "0")
.output();
matches!(output, Ok(output) if output.status.success())
}
/// The `ready to push` status of one checkout of the user's own repository.
fn checkout_push_status(path: &Path) -> Option<CheckoutStatus> {
if worktree_dirty(path) {
///
/// `fetch` refreshes the remote heads first, so a full pass sees pushes made
/// elsewhere; the fast local pass skips it and compares against the tracking
/// refs left by the last full pass, which is enough to detect local commits.
fn checkout_push_status(path: &Path, fetch: bool) -> Option<CheckoutStatus> {
if signed_git::worktree_dirty(path) {
return None;
}
let branch = current_branch_of(path)?;
let branch = signed_git::worktree_current_branch(path)?;
let head = signed_git::head_commit_id(path).ok().flatten()?;
let origin = signed_git::origin_url(path).ok().flatten()?;
// Refresh the remote heads first.
// Commits made elsewhere or pushed from another machine must not linger as `to push`.
signed_git::fetch_repo_refs(path, &[origin], "+refs/heads/*:refs/remotes/origin/*").ok();
if fetch {
// Refresh the remote heads first.
// Commits made elsewhere or pushed from another machine must not linger as `to push`.
signed_git::fetch_repo_refs(path, &[origin], "+refs/heads/*:refs/remotes/origin/*").ok();
}
let remote = format!("refs/remotes/origin/{branch}");
// A branch never fetched or pushed yet compares against the remote HEAD.
// The remote HEAD is the fork point in practice.
let base = if ref_exists(path, &remote) {
let base = if signed_git::worktree_ref_exists(path, &remote) {
remote
} else if ref_exists(path, "refs/remotes/origin/HEAD") {
} else if signed_git::worktree_ref_exists(path, "refs/remotes/origin/HEAD") {
"refs/remotes/origin/HEAD".to_owned()
} else {
return None;
};
let ahead = commits_ahead(path, &base, &branch);
let ahead = signed_git::worktree_commits_ahead(path, &base, &branch);
(ahead > 0).then_some(CheckoutStatus {
path: path.to_path_buf(),
branch,
@@ -580,7 +677,57 @@ fn checkout_push_status(path: &Path) -> Option<CheckoutStatus> {
})
}
/// Whether the pull request `pr` already proposes the same change as `checkout`.
/// Compute the requested statuses against the checkout paths of `associations`.
///
/// Shared by the full and the local pass. `fetch` refreshes the checkouts'
/// remote heads first, so the full pass sees remote moves; the fast local
/// pass reads the tracking refs only, which is enough to detect local commits.
fn compute_statuses(
associations: &HashMap<RepoAddr, Vec<PathBuf>>,
requested: &[(RepoAddr, Option<String>)],
push_requested: &[RepoAddr],
fetch: bool,
) -> (
HashMap<RepoAddr, Vec<CheckoutStatus>>,
HashMap<RepoAddr, Vec<CheckoutStatus>>,
) {
let mut statuses: HashMap<RepoAddr, Vec<CheckoutStatus>> = HashMap::new();
for (addr, announced_head) in requested {
let Some(paths) = associations.get(addr) else {
continue;
};
let list: Vec<CheckoutStatus> = paths
.iter()
.take(MAX_STATUS_CHECKOUTS)
.filter_map(|path| checkout_status(path, announced_head.as_deref()))
.collect();
if !list.is_empty() {
statuses.insert(addr.clone(), list);
}
}
let mut push_statuses: HashMap<RepoAddr, Vec<CheckoutStatus>> = HashMap::new();
for addr in push_requested {
let Some(paths) = associations.get(addr) else {
continue;
};
let list: Vec<CheckoutStatus> = paths
.iter()
.take(MAX_STATUS_CHECKOUTS)
.filter_map(|path| checkout_push_status(path, fetch))
.collect();
if !list.is_empty() {
push_statuses.insert(addr.clone(), list);
}
}
(statuses, push_statuses)
}
pub fn pr_proposes_checkout(
pr: &Event,
open: bool,
@@ -608,6 +755,8 @@ pub fn pr_proposes_checkout(
#[cfg(test)]
mod tests {
use std::process::Command;
use signed_core::{RepoAddr, repo_addr};
use super::*;
@@ -706,40 +855,6 @@ mod tests {
assert_eq!(resolved.len(), 2);
}
#[test]
fn resolve_matches_scanned_repos_by_origin_and_euc() {
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
let announcements = vec![
announcement("repo", &["grasp://host/npub1x/repo"], None),
announcement("family", &[], Some(euc)),
];
let repo = addr("repo");
let family = addr("family");
let resolved = resolve_associations(
&[],
&[
// Origin matches modulo scheme and the `.git` suffix.
scanned("/clone", Some("https://host/npub1x/repo.git"), None),
// Root commit matches the family EUC.
scanned("/family-checkout", None, Some(euc)),
// Neither matches anything.
scanned("/unrelated", Some("https://elsewhere/x.git"), None),
],
&announcements,
);
assert_eq!(
resolved.get(&repo).expect("repo matches"),
&vec![PathBuf::from("/clone")]
);
assert_eq!(
resolved.get(&family).expect("family matches"),
&vec![PathBuf::from("/family-checkout")]
);
assert_eq!(resolved.len(), 2);
}
#[test]
fn resolve_deduplicates_paths_remembering_first() {
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
@@ -854,21 +969,26 @@ mod tests {
};
// A fresh clone has nothing to push.
assert_eq!(checkout_push_status(&checkout), None);
assert_eq!(checkout_push_status(&checkout, true), None);
// One local commit, ready to push, counted against the remote.
std::fs::write(checkout.join("work.txt"), "x\n").expect("write");
run(&["add", "-A"]);
run(&["commit", "-m", "local work"]);
let status = checkout_push_status(&checkout).expect("status");
let status = checkout_push_status(&checkout, true).expect("status");
assert_eq!(status.branch, "main");
assert_eq!(status.base, "refs/remotes/origin/main");
assert_eq!(status.ahead, 1);
assert_eq!(status.head.len(), 40);
// The local-only pass reads the tracking refs, no fetch needed:
// a commit lands locally long before the remote is reconciled.
let local = checkout_push_status(&checkout, false).expect("local status");
assert_eq!(local.ahead, 1);
// After the push the same commit is on the remote, idle again.
run(&["push", "origin", "main"]);
assert_eq!(checkout_push_status(&checkout), None);
assert_eq!(checkout_push_status(&checkout, true), None);
// A commit made by someone else on the remote must not count as local work.
// It is behind, not ahead.
@@ -887,63 +1007,6 @@ mod tests {
std::fs::write(remote.join("other.txt"), "y\n").expect("write");
remote_run(&["add", "-A"]);
remote_run(&["commit", "-m", "remote work"]);
assert_eq!(checkout_push_status(&checkout), None);
}
fn pr_event(author: &str, tags: &[&[&str]]) -> Event {
let keys = Keys::new(SecretKey::from_hex(author).expect("secret"));
let tags: Vec<Tag> = tags
.iter()
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
.collect();
EventBuilder::new(Kind::GitPullRequest, "")
.tags(tags)
.finalize(&keys)
.expect("signed event")
}
fn status(branch: &str, head: &str) -> CheckoutStatus {
CheckoutStatus {
path: PathBuf::from("/checkout"),
branch: branch.to_owned(),
head: head.to_owned(),
base: "main".to_owned(),
ahead: 1,
}
}
#[test]
fn pr_proposes_checkout_matches_branch_or_tip() {
let author = "0000000000000000000000000000000000000000000000000000000000000002";
let tip = "aa231c4c6a5777dc89b42207b499891a344add5c";
// A matching `branch-name` covers the proposal.
let pr = pr_event(author, &[&["branch-name", "feature"], &["c", tip]]);
let status = status("feature", "bb231c4c6a5777dc89b42207b499891a344add5c");
assert!(pr_proposes_checkout(&pr, true, pr.pubkey, &status));
// Without a branch-name tag, the `c` tip still matches for a renamed branch.
let pr = pr_event(
author,
&[&["c", "bb231c4c6a5777dc89b42207b499891a344add5c"]],
);
assert!(pr_proposes_checkout(&pr, true, pr.pubkey, &status));
// Someone else's PR, a closed PR, a different branch and a missing tip.
// They all leave the checkout uncovered.
let pr = pr_event(author, &[&["branch-name", "feature"]]);
assert!(!pr_proposes_checkout(&pr, false, pr.pubkey, &status));
let other = pr_event(
"0000000000000000000000000000000000000000000000000000000000000003",
&[&["branch-name", "feature"]],
);
assert!(!pr_proposes_checkout(&pr, true, other.pubkey, &status));
let other_branch = pr_event(author, &[&["branch-name", "other"]]);
assert!(!pr_proposes_checkout(
&other_branch,
true,
other_branch.pubkey,
&status
));
assert_eq!(checkout_push_status(&checkout, true), None);
}
}
+29 -23
View File
@@ -1,35 +1,41 @@
use std::path::PathBuf;
use std::sync::OnceLock;
use gpui::{App, Global};
use anyhow::Result;
use gix::Repository;
use signed_core::RepoAddr;
use signed_git::GitCache;
struct GlobalGitStore(GitCache);
static GIT_CACHE: OnceLock<GitCache> = OnceLock::new();
impl Global for GlobalGitStore {}
fn git_cache() -> &'static GitCache {
GIT_CACHE
.get()
.expect("git cache is initialized by signed_state::init")
}
/// Global access to the on-disk git clone cache, the grasp mirrors.
#[derive(Debug, Clone)]
pub struct GitStore(GitCache);
/// The root directory of the repository mirrors.
pub(crate) fn repo_mirror_root() -> PathBuf {
git_cache().root().to_path_buf()
}
impl GitStore {
/// Register the clone cache rooted at `root` as an app-wide global.
pub fn set_global(root: impl Into<PathBuf>, cx: &mut App) -> Self {
let store = Self::new(root);
cx.set_global(GlobalGitStore(store.0.clone()));
store
}
/// The on-disk path of the mirror of `addr`.
pub fn repo_mirror_path(addr: &RepoAddr) -> PathBuf {
git_cache().repo_path(addr)
}
/// The app-wide clone cache.
pub fn global(cx: &App) -> Self {
Self(cx.global::<GlobalGitStore>().0.clone())
}
/// Open the mirror of `addr`, if it has been cloned.
pub fn open_repo_mirror(addr: &RepoAddr) -> Result<Option<Repository>> {
git_cache().open(addr)
}
fn new(root: impl Into<PathBuf>) -> Self {
Self(GitCache::new(root.into()))
}
/// Open the mirror of `addr`, cloning it first when it does not exist yet.
pub fn ensure_repo_mirror<U: AsRef<str>>(addr: &RepoAddr, clone_urls: &[U]) -> Result<Repository> {
git_cache().ensure_clone(addr, clone_urls)
}
/// Underlying clone cache.
pub fn cache(&self) -> &GitCache {
&self.0
pub(crate) fn set_git_cache(root: impl Into<PathBuf>) {
if GIT_CACHE.set(GitCache::new(root.into())).is_err() {
log::warn!("git cache root is already set, keeping the first one");
}
}
+254
View File
@@ -0,0 +1,254 @@
use std::collections::{HashMap, HashSet};
use anyhow::Error;
use gpui::{AppContext, Context, Task};
use nostr_sdk::prelude::*;
use signed_core::{Deletions, InboxItem, InboxReadState, filters, inbox};
use crate::backend::Backend;
/// The user's persisted inbox read state.
#[derive(Default)]
pub struct Inbox {
state: InboxReadState,
loaded: bool,
}
impl Inbox {
/// The current read/archive cutoffs.
pub fn state(&self) -> &InboxReadState {
&self.state
}
pub fn is_loaded(&self) -> bool {
self.loaded
}
pub fn mark_read(
&mut self,
group: &[Event],
all: &[Event],
me: PublicKey,
cx: &mut Context<Self>,
) {
for event in group {
self.state.mark_read(event);
}
self.state.advance_read(all, me, Timestamp::now());
self.persist(cx);
cx.notify();
}
/// Archived events are always read too.
pub fn mark_archived(
&mut self,
group: &[Event],
all: &[Event],
me: PublicKey,
cx: &mut Context<Self>,
) {
for event in group {
self.state.mark_archived(event);
self.state.mark_read(event);
}
let now = Timestamp::now();
self.state.advance_archived(all, me, now);
self.state.advance_read(all, me, now);
self.persist(cx);
cx.notify();
}
pub fn mark_all_read(&mut self, all: &[Event], me: PublicKey, cx: &mut Context<Self>) {
self.state.mark_all_read(all, me, Timestamp::now());
self.persist(cx);
cx.notify();
}
pub(crate) fn activate(&mut self, me: PublicKey, client: Client, cx: &mut Context<Self>) {
self.state = InboxReadState::default();
self.loaded = false;
cx.notify();
let backend = Backend::global(cx);
let work = cx.background_spawn(async move { load_state(&client, me).await });
cx.spawn(async move |this, cx| {
let loaded = work.await;
this.update(cx, |this, cx| {
if backend.read(cx).current_user() != Some(me) {
return;
}
match loaded {
Ok(Some(state)) => this.state = state,
Ok(None) => this.state = InboxReadState::default(),
Err(error) => log::warn!("failed to load inbox state: {error}"),
}
this.loaded = true;
cx.notify();
})?;
Ok::<(), Error>(())
})
.detach();
}
pub(crate) fn reset(&mut self, cx: &mut Context<Self>) {
self.state = InboxReadState::default();
self.loaded = false;
cx.notify();
}
/// Sign the state with a random key and store it locally.
fn persist(&mut self, cx: &mut Context<Self>) {
let Some(me) = Backend::global(cx).read(cx).current_user() else {
return;
};
let client = Backend::global(cx).read(cx).client();
let state = self.state.clone();
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
if let Err(error) = save_state(&client, me, &state).await {
log::warn!("failed to save inbox state: {error}");
}
Ok(())
});
task.detach();
}
}
pub async fn query_inbox(
client: &Client,
me: PublicKey,
state: &InboxReadState,
) -> Result<(Vec<InboxItem>, usize), Error> {
let deletion_events = client.database().query(filters::deletions()).await?;
let deletions = Deletions::from_events(deletion_events);
let (notification_events, mut by_id) = fetch_notifications(client, me, &deletions).await?;
let mut activity = Vec::new();
for event in client
.database()
.query(filters::authored_activity(me))
.await?
{
if deletions.is_deleted(&event) || !filters::is_git_activity(&event) {
continue;
}
by_id.entry(event.id).or_insert_with(|| event.clone());
activity.push(event);
}
let items = inbox::group(notification_events, activity, me, state, &|id| {
by_id.get(&id).cloned()
});
let unread_count = items.iter().filter(|item| item.is_unread()).count();
Ok((items, unread_count))
}
/// `d` tag identifying the inbox state event of `me`.
fn inbox_state_d_tag(me: PublicKey) -> String {
format!("signed-inbox-state:{}", me.to_hex())
}
async fn load_state(client: &Client, me: PublicKey) -> Result<Option<InboxReadState>, Error> {
let filter = Filter::new()
.kind(Kind::ApplicationSpecificData)
.identifier(inbox_state_d_tag(me));
let events = client.database().query(filter).await?;
let Some(event) = events.into_iter().max_by_key(|event| event.created_at) else {
return Ok(None);
};
match serde_json::from_str(&event.content) {
Ok(state) => Ok(Some(state)),
Err(error) => {
log::warn!("ignoring unreadable inbox state {}: {error}", event.id);
Ok(None)
}
}
}
/// Sign with a random key and store locally.
async fn save_state(client: &Client, me: PublicKey, state: &InboxReadState) -> Result<(), Error> {
let event = EventBuilder::new(Kind::ApplicationSpecificData, serde_json::to_string(state)?)
.tags([Tag::identifier(inbox_state_d_tag(me))])
.finalize(&Keys::generate())?;
client.database().save_event(&event).await?;
Ok(())
}
/// Notification events and a lookup of every ancestor they reference.
async fn fetch_notifications(
client: &Client,
me: PublicKey,
deletions: &Deletions,
) -> Result<(Vec<Event>, HashMap<EventId, Event>), Error> {
let mut notifications: Vec<Event> = Vec::new();
let mut by_id: HashMap<EventId, Event> = HashMap::new();
for filter in filters::notifications(me) {
for event in client.database().query(filter).await? {
if deletions.is_deleted(&event) {
continue;
}
if by_id.insert(event.id, event.clone()).is_none() {
notifications.push(event);
}
}
}
let mut pending: Vec<EventId> = notifications.iter().flat_map(event_references).collect();
let mut seen: HashSet<EventId> = by_id.keys().copied().collect();
loop {
pending.retain(|id| seen.insert(*id));
if pending.is_empty() {
break;
}
let ancestors = client
.database()
.query(Filter::new().ids(pending.iter().copied()))
.await?;
let mut next = Vec::new();
for event in ancestors {
if deletions.is_deleted(&event) {
continue;
}
next.extend(event_references(&event).filter(|id| !seen.contains(id)));
by_id.entry(event.id).or_insert(event);
}
pending = next;
}
Ok((notifications, by_id))
}
/// Event ids referenced by `event` through its `e` and `E` tags.
fn event_references(event: &Event) -> impl Iterator<Item = EventId> + '_ {
event.tags.iter().filter_map(|tag| {
if tag.kind() != "e" && tag.kind() != "E" {
return None;
}
tag.content()
.and_then(|content| EventId::from_hex(content).ok())
})
}
+31 -25
View File
@@ -1,39 +1,41 @@
mod backend;
mod checkouts;
mod git_store;
mod inbox;
mod local_repos;
mod profile;
mod refresh;
mod repo;
mod repo_list;
mod repos;
use std::path::{Path, PathBuf};
pub use backend::{Backend, BackendEvent, user_grasp_list_servers};
pub use checkouts::{CheckoutStatus, CheckoutsStore, pr_proposes_checkout};
pub use git_store::GitStore;
use gpui::{App, AppContext, Entity};
pub use local_repos::LocalReposStore;
use git_store::set_git_cache;
pub use git_store::{ensure_repo_mirror, open_repo_mirror, repo_mirror_path};
use gpui::{App, AppContext};
pub use inbox::{Inbox, query_inbox};
pub use local_repos::{LocalReposStore, ResolvedLocalRepo, local_repo_addr, resolve_local_repos};
pub use nostr_sdk::prelude::Timestamp;
pub use profile::{Profile, ProfileStore};
pub use refresh::{RefreshGate, RefreshRequest};
pub use repo::RepoStore;
pub use repo_list::{RepoActivityCounts, RepoListStore};
pub use repos::{RepoActivityCounts, RepoListStore};
pub use signed_git::{GraspSignals, LocalRepo, Nip34Binding, Nip34Kind};
use signed_nostr::new_backend;
/// Initialize the backend and stores, and install them as globals.
/// Call once at startup, before opening any window that uses the stores.
#[cfg(not(target_arch = "wasm32"))]
pub fn init(
db_path: impl AsRef<Path>,
repos_root: impl Into<PathBuf>,
scan_paths: Vec<PathBuf>,
cx: &mut App,
) -> Entity<Backend> {
) {
// rustls uses the `aws_lc_rs` provider by default.
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.ok();
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
// Initialize the nostr client and signer
let (client, signer) = cx.foreground_executor().block_on(async move {
let path = db_path.as_ref().to_path_buf();
new_backend(path)
@@ -41,29 +43,33 @@ pub fn init(
.expect("failed to initialize nostr backend")
});
let entity = cx.new(|cx| Backend::new(client, signer, cx));
Backend::set_global(entity.clone(), cx);
// Set Git cache for the repos root
set_git_cache(repos_root);
// Set global stores for the backend
Backend::set_global(cx.new(|cx| Backend::new(client, signer, cx)), cx);
// Set global stores for the profile
ProfileStore::set_global(cx.new(ProfileStore::new), cx);
RepoListStore::set_global(cx.new(|cx| RepoListStore::new(None, cx)), cx);
// The local git clone cache, the grasp mirrors.
GitStore::set_global(repos_root, cx);
LocalReposStore::set_global(cx.new(|cx| LocalReposStore::new(scan_paths, cx)), cx);
CheckoutsStore::set_global(cx.new(CheckoutsStore::new), cx);
// Set global stores for the repo list and local repos
RepoListStore::set_global(cx.new(RepoListStore::new), cx);
entity
// Set global stores for the local repos
LocalReposStore::set_global(cx.new(|cx| LocalReposStore::new(scan_paths, cx)), cx);
// Set global stores for the checkouts
CheckoutsStore::set_global(cx.new(CheckoutsStore::new), cx);
}
/// Initialize the backend with an in-memory database on wasm.
#[cfg(target_arch = "wasm32")]
pub fn init(cx: &mut App) -> Entity<Backend> {
pub fn init(cx: &mut App) {
let (client, signer) = new_backend().expect("failed to initialize nostr backend");
let entity = cx.new(|cx| Backend::new(client, signer, cx));
Backend::set_global(entity.clone(), cx);
set_git_cache(PathBuf::new());
Backend::set_global(cx.new(|cx| Backend::new(client, signer, cx)), cx);
ProfileStore::set_global(cx.new(ProfileStore::new), cx);
RepoListStore::set_global(cx.new(|cx| RepoListStore::new(None, cx)), cx);
GitStore::set_global(PathBuf::new(), cx);
RepoListStore::set_global(cx.new(RepoListStore::new), cx);
LocalReposStore::set_global(cx.new(|cx| LocalReposStore::new(Vec::new(), cx)), cx);
CheckoutsStore::set_global(cx.new(|cx| CheckoutsStore::new(cx)), cx);
entity
}
+206 -20
View File
@@ -1,9 +1,11 @@
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::Error;
use gpui::{App, AppContext, Context, Entity, Global, Task};
use signed_git::find_git_repos;
use gpui::{App, AppContext, Context, Entity, Global, SharedString, Task};
use signed_core::{Announcement, RepoAddr, repo_addr};
use signed_git::{LocalRepo, Nip34Binding, find_git_repos};
struct GlobalLocalReposStore(Entity<LocalReposStore>);
@@ -11,19 +13,14 @@ impl Global for GlobalLocalReposStore {}
/// Store of the git repositories discovered under a set of scan paths.
pub struct LocalReposStore {
/// The directories being scanned.
pub roots: Arc<Vec<PathBuf>>,
/// Git repositories discovered under [`Self::roots`], sorted by path.
pub repos: Arc<Vec<PathBuf>>,
/// A scan is currently running.
pub repos: Arc<Vec<LocalRepo>>,
pub scanning: bool,
/// A scan was requested while one was already running.
scan_dirty: bool,
tasks: Vec<Task<Result<(), Error>>>,
}
impl LocalReposStore {
/// Retrieve the global local-repositories store.
pub fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalLocalReposStore>().0.clone()
}
@@ -32,17 +29,20 @@ impl LocalReposStore {
cx.set_global(GlobalLocalReposStore(entity));
}
/// Create a store scanning `roots` right away.
pub fn new(roots: Vec<PathBuf>, cx: &mut Context<Self>) -> Self {
let mut store = Self {
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.rescan(cx)) {
log::warn!("local repos store dropped before initial scan could run: {error}");
}
});
Self {
roots: Arc::new(roots),
repos: Arc::new(Vec::new()),
scanning: false,
scan_dirty: false,
tasks: Vec::new(),
};
store.rescan(cx);
store
}
}
/// Forget a repository that has just been published to NIP-34.
@@ -50,19 +50,19 @@ impl LocalReposStore {
self.repos = Arc::new(
self.repos
.iter()
.filter(|repo| repo.as_path() != path)
.filter(|repo| repo.path.as_path() != path)
.cloned()
.collect(),
);
cx.notify();
}
/// Re-run the scan.
pub fn rescan(&mut self, cx: &mut Context<Self>) {
if self.scanning {
self.scan_dirty = true;
return;
}
if self.roots.is_empty() {
return;
}
@@ -71,17 +71,18 @@ impl LocalReposStore {
cx.notify();
let roots = self.roots.clone();
let work = cx.background_spawn(async move {
let mut repos = Vec::new();
for root in roots.iter() {
repos.extend(find_git_repos(root));
}
repos.sort();
repos.dedup();
repos.sort_by(|a, b| a.path.cmp(&b.path));
repos.dedup_by(|a, b| a.path == b.path);
repos
});
self.tasks.push(cx.spawn(async move |this, cx| {
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let repos = work.await;
let again = this.update(cx, |this, cx| {
this.repos = Arc::new(repos);
@@ -99,6 +100,191 @@ impl LocalReposStore {
}
Ok(())
}));
});
task.detach();
}
}
/// The NIP-34 coordinate a repository's detection resolved, when both the owner
/// and the identifier were recovered.
pub fn local_repo_addr(repo: &LocalRepo) -> Option<RepoAddr> {
let binding = repo.nip34.as_ref()?;
let owner = binding.owner?;
let identifier = binding.identifier.as_deref()?;
Some(repo_addr(owner, identifier))
}
/// A scanned repository resolved against the known announcements.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedLocalRepo {
pub path: PathBuf,
/// `None` for a plain repository.
pub nip34: Option<Nip34Binding>,
/// The known announcement this repository is bound to, when one matched.
pub announcement: Option<Announcement>,
}
impl ResolvedLocalRepo {
/// The repository's directory name, or `Untitled` when the path has none.
pub fn name(&self) -> SharedString {
self.path
.file_name()
.map(|name| SharedString::from(name.to_string_lossy().into_owned()))
.unwrap_or_else(|| SharedString::from("Untitled"))
}
}
/// Resolve the scanned repositories against the known announcements.
pub fn resolve_local_repos(
repos: &[LocalRepo],
known: &[Announcement],
own: &[Announcement],
) -> Vec<ResolvedLocalRepo> {
let shown: HashSet<RepoAddr> = own.iter().map(Announcement::addr).collect();
repos
.iter()
.filter_map(|repo| {
let addr = local_repo_addr(repo);
if let Some(addr) = &addr
&& shown.contains(addr)
{
return None;
}
let announcement = addr
.as_ref()
.and_then(|addr| {
known
.iter()
.find(|announcement| announcement.addr() == *addr)
})
.cloned();
Some(ResolvedLocalRepo {
path: repo.path.clone(),
nip34: repo.nip34.clone(),
announcement,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use nostr::prelude::*;
use signed_git::{GraspSignals, Nip34Kind};
use super::*;
const KEY: &str = "0000000000000000000000000000000000000000000000000000000000000001";
const OTHER_KEY: &str = "0000000000000000000000000000000000000000000000000000000000000002";
fn announcement(secret: &str, id: &str) -> Announcement {
let keys = Keys::new(SecretKey::from_hex(secret).expect("secret"));
let tag = Tag::parse(vec!["d", id]).expect("tag");
let event = EventBuilder::new(Kind::GitRepoAnnouncement, "")
.tags(vec![tag])
.finalize(&keys)
.expect("signed");
Announcement::from_event(&event).expect("parsed")
}
fn owner(secret: &str) -> PublicKey {
Keys::new(SecretKey::from_hex(secret).expect("secret")).public_key()
}
fn bound(secret: &str, id: &str) -> LocalRepo {
let binding = Nip34Binding {
kind: Nip34Kind::Initialized,
signals: GraspSignals {
nip34_json: true,
..Default::default()
},
owner: Some(owner(secret)),
identifier: Some(id.to_owned()),
grasp_urls: Vec::new(),
};
LocalRepo {
path: PathBuf::from(id),
nip34: Some(binding),
}
}
#[test]
fn the_users_own_announcement_is_dropped() {
let own = announcement(KEY, "mine");
let repo = bound(KEY, "mine");
let own = std::slice::from_ref(&own);
assert!(resolve_local_repos(&[repo], own, own).is_empty());
}
#[test]
fn another_owners_announcement_is_linked_and_kept() {
let known = announcement(OTHER_KEY, "theirs");
let repo = bound(OTHER_KEY, "theirs");
let resolved = resolve_local_repos(&[repo], std::slice::from_ref(&known), &[]);
assert_eq!(resolved.len(), 1);
assert_eq!(resolved[0].announcement.as_ref(), Some(&known));
}
#[test]
fn an_unmatched_repository_keeps_its_binding() {
let repo = bound(KEY, "unlisted");
let resolved = resolve_local_repos(&[repo], &[], &[]);
assert_eq!(resolved.len(), 1);
assert!(resolved[0].announcement.is_none());
assert_eq!(
resolved[0].nip34.as_ref().map(|binding| binding.kind),
Some(Nip34Kind::Initialized)
);
}
#[test]
fn a_plain_repository_is_kept_without_a_binding() {
let repo = LocalRepo {
path: PathBuf::from("plain"),
nip34: None,
};
let resolved = resolve_local_repos(&[repo], &[], &[]);
assert_eq!(resolved.len(), 1);
assert!(resolved[0].nip34.is_none());
assert!(resolved[0].announcement.is_none());
}
#[test]
fn the_name_is_the_directory_name() {
let repo = LocalRepo {
path: PathBuf::from("/tmp/my-repo"),
nip34: None,
};
let resolved = resolve_local_repos(&[repo], &[], &[]);
assert_eq!(resolved[0].name(), SharedString::from("my-repo"));
}
#[test]
fn a_path_without_a_directory_name_is_untitled() {
let repo = LocalRepo {
path: PathBuf::from("/"),
nip34: None,
};
let resolved = resolve_local_repos(&[repo], &[], &[]);
assert_eq!(resolved[0].name(), SharedString::from("Untitled"));
}
}
+30 -35
View File
@@ -50,10 +50,9 @@ impl Profile {
return SharedString::from(name.trim().to_owned());
}
SharedString::from(shorten_pubkey(self.public_key, 4))
SharedString::from(shorten_pubkey(self.public_key))
}
/// Avatar URL, if set.
pub fn picture(&self) -> Option<SharedString> {
self.metadata
.picture
@@ -75,7 +74,6 @@ pub struct ProfileStore {
seen: RefCell<HashSet<PublicKey>>,
/// Sender for queuing fetch requests, batched by a background task.
sender: Sender<PublicKey>,
tasks: Vec<Task<Result<(), Error>>>,
_subscription: Subscription,
}
@@ -84,7 +82,6 @@ struct GlobalProfileStore(Entity<ProfileStore>);
impl Global for GlobalProfileStore {}
impl ProfileStore {
/// Retrieve the global profile store.
pub fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalProfileStore>().0.clone()
}
@@ -97,8 +94,13 @@ impl ProfileStore {
let backend = Backend::global(cx);
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| match event {
BackendEvent::NostrUpdate(update) if update.kind == Kind::Metadata => {
this.apply_author(update.author, cx);
BackendEvent::NostrUpdate(updates) => {
for update in updates
.iter()
.filter(|update| update.kind == Kind::Metadata)
{
this.apply_author(update.author, cx);
}
}
BackendEvent::Published(event) if event.kind == Kind::Metadata => {
let metadata = Metadata::from_json(&event.content).unwrap_or_default();
@@ -114,30 +116,24 @@ impl ProfileStore {
let (sender, receiver) = flume::unbounded::<PublicKey>();
let entity = cx.entity().downgrade();
let mut tasks = Vec::new();
tasks.push(cx.spawn(async move |_this, cx| {
cx.spawn(async move |_this, cx| {
Self::handle_requests(entity, &client, &receiver, cx).await
}));
})
.detach();
let mut store = Self {
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.load(cx)) {
log::warn!("profile store dropped before initial load could run: {error}");
}
});
Self {
profiles: HashMap::new(),
seen: RefCell::new(HashSet::new()),
sender,
tasks,
_subscription: subscription,
};
store.load(cx);
store
}
/// Track a spawned task, pruning finished tasks first.
///
/// Keeps the store's task list bounded by the number of in-flight tasks.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
}
/// Get a profile.
@@ -159,7 +155,6 @@ impl ProfileStore {
Profile::new(public_key, Metadata::default())
}
/// Load recently seen profiles from the local database.
fn load(&mut self, cx: &mut Context<Self>) {
let backend = Backend::global(cx);
let client = backend.read(cx).client();
@@ -181,7 +176,7 @@ impl ProfileStore {
Ok::<_, Error>(profiles)
});
self.push_task(cx.spawn(async move |this, cx| {
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let profiles = work.await?;
this.update(cx, |this, cx| {
@@ -192,10 +187,10 @@ impl ProfileStore {
})?;
Ok(())
}));
});
task.detach();
}
/// Re-read the latest metadata of an author from the local database.
fn apply_author(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
let backend = Backend::global(cx);
let client = backend.read(cx).client();
@@ -217,7 +212,7 @@ impl ProfileStore {
Ok::<_, Error>(profile)
});
self.push_task(cx.spawn(async move |this, cx| {
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let profile = work.await?;
this.update(cx, |this, cx| {
@@ -228,7 +223,8 @@ impl ProfileStore {
})?;
Ok(())
}));
});
task.detach();
}
/// Re-read the latest metadata of every requested author from the local database.
@@ -273,7 +269,7 @@ impl ProfileStore {
Ok::<_, Error>(profiles)
});
self.push_task(cx.spawn(async move |this, cx| {
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let profiles = work.await?;
this.update(cx, |this, cx| {
@@ -284,7 +280,8 @@ impl ProfileStore {
})?;
Ok(())
}));
});
task.detach();
}
/// Sync metadata for requested authors in batches, debounced to collect requests.
@@ -299,7 +296,6 @@ impl ProfileStore {
let mut batch: HashSet<PublicKey> = HashSet::new();
loop {
// Wait for the first request of a batch.
match receiver.recv_async().await {
Ok(public_key) => {
batch.insert(public_key);
@@ -307,7 +303,6 @@ impl ProfileStore {
Err(_) => return Ok(()),
}
// Collect everything that arrives within the debounce window.
// The channel has no async timeout, race the receive against a timer.
let deadline = Instant::now() + BATCH_TIMEOUT;
loop {
@@ -337,7 +332,7 @@ impl ProfileStore {
// Re-apply from the database afterwards.
match sync_bootstrap_only(client, filter, SyncOptions::default()).await {
Ok(_) => {
let _ = this.update(cx, |this, cx| this.apply_seen(cx));
this.update(cx, |this, cx| this.apply_seen(cx)).ok();
}
Err(e) => log::warn!("profile sync failed: {e}"),
}
+49 -35
View File
@@ -1,68 +1,37 @@
/// Refresh coalescing shared by the event stores.
///
/// [`crate::RepoStore`], [`crate::RepoListStore`] and [`crate::CheckoutsStore`]
/// re-query their inputs on a debounce timer with the same policy:
/// a request arriving while a run is in flight is folded into a follow-up run,
/// a request arriving while the debounce timer is pending is dropped by it.
#[derive(Debug, Default)]
pub struct RefreshGate {
/// A run is in flight.
running: bool,
/// A request arrived while a run was in flight.
dirty: bool,
/// The debounce timer is pending.
debouncing: bool,
}
/// What a refresh request decided.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshRequest {
/// No run or timer covers the request, start the debounce timer.
/// No run covers the request, start one now.
Schedule,
/// A run or pending timer already covers the request.
/// A run is in flight and covers the request, fold it into a follow-up.
Fold,
}
impl RefreshGate {
/// Whether a run is in flight.
pub fn running(&self) -> bool {
self.running
}
/// Whether the debounce timer is pending.
pub fn debouncing(&self) -> bool {
self.debouncing
}
/// Whether no run is in flight and no timer is pending.
pub fn idle(&self) -> bool {
!self.running && !self.debouncing
}
/// A new refresh request arrived.
///
/// Folded into a follow-up run while one is in flight, dropped while the
/// debounce timer is pending, otherwise starts the timer.
/// Folded into a follow-up run while one is in flight, otherwise the
/// caller starts the run itself.
pub fn request(&mut self) -> RefreshRequest {
if self.running {
self.dirty = true;
RefreshRequest::Fold
} else if self.debouncing {
RefreshRequest::Fold
} else {
self.debouncing = true;
RefreshRequest::Schedule
}
}
/// A timer was started without a request, e.g. a poll cycle.
pub fn debounce(&mut self) {
self.debouncing = true;
}
/// The debounce timer fired and the run starts now.
pub fn begin(&mut self) {
self.debouncing = false;
self.running = true;
}
@@ -77,3 +46,48 @@ impl RefreshGate {
self.running = false;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_request_while_running_folds_into_a_follow_up() {
let mut gate = RefreshGate::default();
gate.begin();
assert_eq!(gate.request(), RefreshRequest::Fold);
assert!(gate.finish());
}
#[test]
fn a_request_without_a_run_schedules() {
let mut gate = RefreshGate::default();
assert_eq!(gate.request(), RefreshRequest::Schedule);
assert!(!gate.running());
}
#[test]
fn a_request_after_a_run_schedules_again() {
let mut gate = RefreshGate::default();
gate.begin();
assert_eq!(gate.request(), RefreshRequest::Fold);
assert!(gate.finish());
assert_eq!(gate.request(), RefreshRequest::Schedule);
}
#[test]
fn abort_keeps_the_pending_request() {
let mut gate = RefreshGate::default();
gate.begin();
assert_eq!(gate.request(), RefreshRequest::Fold);
gate.abort();
assert!(!gate.running());
gate.begin();
assert!(gate.finish());
}
}
File diff suppressed because it is too large Load Diff
@@ -3,18 +3,13 @@ use std::sync::Arc;
use std::time::Duration;
use anyhow::Error;
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task};
use gpui::{App, AppContext, Context, Entity, Global, Subscription};
use nostr_sdk::prelude::*;
use signed_core::{Announcement, Deletions, RepoAddr, filters, repo_addr};
use crate::backend::{Backend, BackendEvent};
use crate::refresh::{RefreshGate, RefreshRequest};
/// Delay between a refresh request and the actual re-query.
///
/// Bursts of events, e.g. sync progress ticks, collapse into one query.
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
/// How far back activity events count toward a repository's last activity.
const ACTIVITY_WINDOW: Duration = Duration::from_secs(90 * 86_400);
@@ -42,26 +37,21 @@ impl RepoActivityCounts {
}
}
/// Store listing repository announcements, global discovery or per-author.
/// Store listing the discovered repository announcements, newest first.
pub struct RepoListStore {
/// Shared so views can clone the list per frame without a deep copy.
pub announcements: Arc<Vec<Announcement>>,
/// Latest known activity timestamp per repository.
/// Covers announcements, state updates, patches, PRs, issues and statuses.
pub last_activity: Arc<HashMap<RepoAddr, Timestamp>>,
/// Issues, pull requests and commits per repository.
///
/// Used for the Popular ranking of the explore list.
pub counts: Arc<HashMap<RepoAddr, RepoActivityCounts>>,
author: Option<PublicKey>,
/// Refresh coalescing, see [`RefreshGate`].
refresh: RefreshGate,
tasks: Vec<Task<Result<(), Error>>>,
_subscription: Subscription,
}
impl RepoListStore {
/// Retrieve the global explore store.
pub fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalRepoListStore>().0.clone()
}
@@ -70,13 +60,13 @@ impl RepoListStore {
cx.set_global(GlobalRepoListStore(entity));
}
/// Create a store. If `author` is `None`, all announcements are listed.
pub fn new(author: Option<PublicKey>, cx: &mut Context<Self>) -> Self {
pub fn new(cx: &mut Context<Self>) -> Self {
let backend = Backend::global(cx);
let weak = cx.entity().downgrade();
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
let relevant = match event {
BackendEvent::NostrUpdate(update) => {
BackendEvent::NostrUpdate(updates) => updates.iter().any(|update| {
// Deletions may target anything we list, always refresh.
if update.kind == Kind::EventDeletion || update.kind == Kind::RequestToVanish {
true
@@ -87,14 +77,11 @@ impl RepoListStore {
} else {
let is_announcement = update.kind == Kind::GitRepoAnnouncement;
let is_repo_state = update.kind == Kind::RepoState;
let tracked = is_announcement || is_repo_state;
tracked && this.author.is_none_or(|a| a == update.author)
is_announcement || is_repo_state
}
}
}),
BackendEvent::Published(event) => {
let kind_match = event.kind == Kind::GitRepoAnnouncement;
let author_match = this.author.is_none_or(|a| a == event.pubkey);
let announcement = kind_match && author_match;
let announcement = event.kind == Kind::GitRepoAnnouncement;
// Locally published deletions are already in the local database.
// Refresh so they take effect immediately, like relay deletions.
@@ -103,7 +90,10 @@ impl RepoListStore {
announcement || deletion
}
BackendEvent::Synced | BackendEvent::SyncProgress { .. } => true,
// Only a completed sync refreshes the list.
// Progress ticks would re-scan the whole database several times
// per sync to reveal entries incrementally.
BackendEvent::Synced => true,
_ => false,
};
@@ -112,90 +102,64 @@ impl RepoListStore {
}
});
let mut store = Self {
cx.defer(move |cx| {
weak.update(cx, |this, cx| {
this.subscribe_remote(cx);
this.refresh(cx);
})
.ok();
});
Self {
announcements: Arc::new(Vec::new()),
last_activity: Arc::new(HashMap::new()),
counts: Arc::new(HashMap::new()),
author,
refresh: RefreshGate::default(),
_subscription: subscription,
tasks: Vec::new(),
};
store.subscribe_remote(cx);
// Query the local database right away.
// The list never waits for the relay syncs started above to finish.
store.refresh_initial(cx);
store
}
}
/// Track a spawned task, pruning finished tasks first.
///
/// Keeps the store's task list bounded by the number of in-flight tasks.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
/// The announcements of `user`, newest first.
pub fn announcements_of(&self, user: &PublicKey) -> Vec<Announcement> {
self.announcements
.iter()
.filter(|a| a.owner == *user)
.cloned()
.collect()
}
/// Negentropy-sync announcements with the bootstrap relays.
fn subscribe_remote(&mut self, cx: &mut Context<Self>) {
let backend = Backend::global(cx);
let author = self.author;
backend.update(cx, |backend, cx| {
let filter = match author {
Some(a) => filters::announcements_by(a),
None => filters::all_announcements(),
};
backend.sync_bootstrap(filter, cx);
backend.sync_bootstrap(filters::all_announcements(), cx);
// Deletion requests, NIP-09/62, must be known before any announcement is shown.
backend.sync_bootstrap(filters::deletions(), cx);
});
}
/// One-shot initial load.
///
/// Query the local database immediately, no debounce.
/// Stored announcements appear as soon as the app opens.
fn refresh_initial(&mut self, cx: &mut Context<Self>) {
debug_assert!(!self.refresh.debouncing());
if self.refresh.running() {
self.refresh.request();
return;
}
self.run_refresh(cx);
}
/// Re-query the local database.
///
/// Runs immediately. The backend pump already batches the relay events that
/// trigger a refresh, so no per-store debounce is needed.
pub fn refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() != RefreshRequest::Schedule {
return;
}
let task = cx.spawn(async move |this, cx| {
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
this.update(cx, |this, cx| this.run_refresh(cx))
});
self.push_task(task);
self.run_refresh(cx);
}
/// One query and apply cycle, the debounced entry point.
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refresh.begin();
let backend = Backend::global(cx);
let client = backend.read(cx).client();
let author = self.author;
let work = cx.background_spawn(async move {
let filter = match author {
Some(a) => filters::announcements_by(a),
None => filters::all_announcements(),
};
let filter = filters::all_announcements();
let events = client.database().query(filter).await?;
let deletion_events = client.database().query(filters::deletions()).await?;
let deletions = Deletions::from_events(deletion_events);
@@ -299,7 +263,7 @@ impl RepoListStore {
Ok::<_, Error>((announcements, last_activity, counts))
});
self.push_task(cx.spawn(async move |this, cx| {
cx.spawn(async move |this, cx| {
let (announcements, last_activity, counts) = match work.await {
Ok(results) => results,
// Database errors are transient, keep the last list.
@@ -326,6 +290,7 @@ impl RepoListStore {
}
Ok(())
}));
})
.detach();
}
}
+4 -1
View File
@@ -5,10 +5,13 @@ use gpui_component::menu::PopupMenuItem;
use gpui_component::{ActiveTheme, StyledExt, h_flex};
/// A muted command row with a copy button.
pub fn copy_row<E>(copy_id: E, command: &SharedString, cx: &App) -> Div
pub fn copy_row<E, T>(copy_id: E, command: T, cx: &App) -> Div
where
E: Into<ElementId>,
T: Into<SharedString>,
{
let command = command.into();
h_flex()
.h_8()
.w_full()
+7 -45
View File
@@ -8,22 +8,18 @@ use gpui_component::menu::PopupMenu;
use gpui_component::{ActiveTheme, Icon, IconName, Sizable, h_flex};
/// A split dropdown button built on `gpui_base::Popover`.
/// An action element with a separate caret trigger that opens a [`PopupMenu`].
/// The action and the caret are caller-supplied elements, so the look stays in the app.
/// This component only owns the popover wiring.
/// An action element next to a caret that opens a [`PopupMenu`].
#[derive(IntoElement)]
pub struct DropdownButton {
id: ElementId,
style: StyleRefinement,
anchor: Anchor,
action: Option<AnyElement>,
caret: Option<CaretBuilder>,
menu: Option<MenuBuilder>,
}
type MenuBuilder =
Box<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static>;
type CaretBuilder = Box<dyn FnOnce(bool, &Window, &App) -> AnyElement>;
impl DropdownButton {
pub fn new(id: impl Into<ElementId>) -> Self {
@@ -32,7 +28,6 @@ impl DropdownButton {
style: StyleRefinement::default(),
anchor: Anchor::TopRight,
action: None,
caret: None,
menu: None,
}
}
@@ -54,14 +49,6 @@ impl DropdownButton {
self.menu = Some(Box::new(builder));
self
}
/// Which corner of the caret the menu anchors to.
/// Defaults to [`Anchor::TopRight`], lining the menu's right edge up with the caret's.
#[allow(dead_code)] // API knob, current call sites use the default anchor.
pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
self.anchor = anchor.into();
self
}
}
impl Styled for DropdownButton {
@@ -91,28 +78,24 @@ impl RenderOnce for DropdownButton {
let menu_state =
window.use_keyed_state(popover_id.clone(), cx, |_, _| DropdownMenuState::default());
let caret = self.caret.unwrap_or_else(|| {
let id = popover_id.clone();
Box::new(move |is_open, _, cx| {
let caret = default_caret(id.clone(), cx);
let selected = caret.is_selected();
caret.selected(selected || is_open).into_any_element()
})
});
h_flex()
.id(self.id)
.refine_style(&self.style)
.gap_0p5()
.when_some(self.action, |this, action| this.child(action))
.when_some(self.menu, |this, builder| {
let caret_id = popover_id.clone();
this.child(
Popover::new(popover_id)
.anchor(anchor)
// The menu dismisses itself on outside click or Escape.
// The subscription below closes the popover along with it.
.overlay_closable(false)
.trigger_with(caret)
.trigger_with(move |is_open, _, cx| {
let caret = default_caret(caret_id.clone(), cx);
let selected = caret.is_selected();
caret.selected(selected || is_open).into_any_element()
})
.content(
move |_, window, cx| match menu_state.read(cx).menu.clone() {
Some(menu) => menu,
@@ -162,24 +145,3 @@ fn default_caret(id: impl Into<ElementId>, cx: &App) -> BaseButton {
})
.child(Icon::new(IconName::ChevronDown).xsmall())
}
#[cfg(test)]
mod tests {
use gpui::div;
use super::*;
#[test]
fn dropdown_button_builder_state() {
let button = DropdownButton::new("issues")
.action(div())
.anchor(Anchor::BottomLeft)
.dropdown_menu(|menu, _, _| menu);
assert!(button.action.is_some());
// The caret is `None` until render, which falls back to the default.
assert!(button.caret.is_none());
assert!(button.menu.is_some());
assert_eq!(button.anchor, Anchor::BottomLeft);
}
}
+2
View File
@@ -2,6 +2,7 @@ mod dropdown_button;
mod nav_item;
mod pixel_avatar;
mod placeholder;
mod ref_selector;
mod segment_button;
mod setting;
mod status_badge;
@@ -17,6 +18,7 @@ pub use dropdown_button::DropdownButton;
pub use nav_item::NavItem;
pub use pixel_avatar::PixelAvatar;
pub use placeholder::placeholder;
pub use ref_selector::ref_selector_trigger;
pub use segment_button::{CountBadge, SegmentButton};
pub use setting::{SelectOption, setting_block, setting_row};
pub use status_badge::status_badge;
-1
View File
@@ -35,7 +35,6 @@ impl NavItem {
}
}
/// A trailing element rendered at the right edge of the row
pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
self.suffix = Some(suffix.into_any_element());
self
+32 -39
View File
@@ -1,7 +1,7 @@
use gpui::prelude::*;
use gpui::{App, Pixels, StyleRefinement, Window, div, px};
use gpui_base::StyledExt;
use gpui_component::{ActiveTheme, Colorize};
use gpui_component::{ActiveTheme, Colorize, Sizable, Size};
/// Number of rows and columns in the pixel grid.
const GRID_SIZE: usize = 8;
@@ -10,34 +10,36 @@ const FILL_PROBABILITY: f32 = 0.42;
/// Probability that a filled cell uses the accent shade instead of the main color.
const ACCENT_PROBABILITY: f32 = 0.25;
/// Minimum number of filled left-half cells.
/// A sparse roll still yields a recognizable shape.
/// Each left-half cell is mirrored to a right-half one.
const MIN_FILLED: usize = 5;
/// Side length of the avatar in pixels, no setter.
const AVATAR_SIZE: Pixels = px(16.);
/// A deterministic, offline pixel-art avatar.
/// An 8×8 grid with horizontal mirror symmetry.
/// Seeded from a stable string such as the repository id and owner public key.
/// The same seed always renders the same avatar.
#[derive(IntoElement)]
pub struct PixelAvatar {
seed: u64,
size: Size,
style: StyleRefinement,
}
impl PixelAvatar {
/// Create an avatar seeded from `seed`.
///
/// The seed should be a stable string unique to the entity the avatar represents.
pub fn new(seed: impl AsRef<str>) -> Self {
Self {
seed: fnv1a(seed.as_ref().as_bytes()),
size: Size::XSmall,
style: StyleRefinement::default(),
}
}
}
impl Sizable for PixelAvatar {
fn with_size(mut self, size: impl Into<Size>) -> Self {
self.size = size.into();
self
}
}
impl Styled for PixelAvatar {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
@@ -48,16 +50,17 @@ impl RenderOnce for PixelAvatar {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let pattern = pattern(self.seed);
let mut cells = Vec::new();
let hue = self.seed as f32 / u64::MAX as f32;
let main = theme.blue.hue(hue);
let shade = if theme.is_dark() {
main.lightness((main.l * 1.6).min(0.95))
} else {
main.lightness((main.l * 0.45).max(0.18))
};
let mut cells = Vec::new();
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
let value = pattern[row * GRID_SIZE + col];
@@ -80,7 +83,7 @@ impl RenderOnce for PixelAvatar {
.grid()
.grid_cols(GRID_SIZE as u16)
.grid_rows(GRID_SIZE as u16)
.size(AVATAR_SIZE)
.size(side_length(self.size))
.flex_shrink_0()
.overflow_hidden()
.bg(main.opacity(0.16))
@@ -88,9 +91,16 @@ impl RenderOnce for PixelAvatar {
}
}
/// Generate the 8×8 cell pattern for `seed`.
/// Cells are `0` for empty, `1` for main color and `2` for accent shade.
/// The right half mirrors the left half.
fn side_length(size: Size) -> Pixels {
match size {
Size::XSmall => px(16.),
Size::Small => px(24.),
Size::Medium => px(48.),
Size::Large => px(80.),
Size::Size(size) => size,
}
}
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let mut rng = PixelRng::new(seed);
let mut pattern = [0u8; GRID_SIZE * GRID_SIZE];
@@ -106,18 +116,19 @@ fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
}
}
// Sparse rolls can come out nearly empty.
// Top the pattern up to the minimum fill, scanning from a seeded starting cell.
if filled < MIN_FILLED {
let half = GRID_SIZE * GRID_SIZE / 2;
let start = (rng.next() % half as u64) as usize;
for offset in 0..half {
if filled >= MIN_FILLED {
break;
}
let ix = (start + offset) % half;
let row = ix / (GRID_SIZE / 2);
let col = ix % (GRID_SIZE / 2);
if pattern[row * GRID_SIZE + col] == 0 {
set_cell(&mut pattern, row, col, 1);
filled += 1;
@@ -175,9 +186,13 @@ mod tests {
}
#[test]
fn pattern_is_mirror_symmetric() {
fn pattern_properties() {
for seed in 0..50 {
let pattern = pattern(seed);
assert!(
count_filled(&pattern) >= MIN_FILLED * 2,
"pattern too sparse for seed {seed}"
);
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
assert_eq!(
@@ -188,31 +203,9 @@ mod tests {
}
}
}
}
#[test]
fn pattern_has_minimum_fill() {
for seed in 0..50 {
let pattern = pattern(seed);
assert!(
count_filled(&pattern) >= MIN_FILLED * 2,
"pattern too sparse for seed {seed}"
);
}
}
#[test]
fn pattern_is_deterministic() {
for seed in [0, 1, 42, u64::MAX] {
assert_eq!(pattern(seed), pattern(seed));
}
assert_ne!(pattern(42), pattern(43));
}
#[test]
fn fnv1a_is_stable_and_distinct() {
assert_eq!(fnv1a(b""), 0xcbf2_9ce4_8422_2325);
assert_eq!(fnv1a(b"repo"), fnv1a(b"repo"));
assert_ne!(fnv1a(b"repo:a"), fnv1a(b"repo:b"));
}
}
+41
View File
@@ -0,0 +1,41 @@
use assets::CustomIconName;
use gpui::prelude::*;
use gpui::{AnyElement, App, SharedString, div};
use gpui_component::combobox::{Caret, ComboboxTriggerContext};
use gpui_component::searchable_list::SearchableVec;
use gpui_component::{ActiveTheme, Icon, Sizable, h_flex};
/// The kind icon, the selection or placeholder, and the caret. `Combobox`
/// replaces its default trigger entirely, the only way to show an icon inside it.
pub fn ref_selector_trigger(
ctx: &ComboboxTriggerContext<SearchableVec<SharedString>>,
icon: CustomIconName,
cx: &App,
) -> AnyElement {
let muted = cx.theme().muted_foreground;
h_flex()
.w_full()
.min_w_0()
.gap_1()
.items_center()
.child(Icon::new(icon).small().flex_shrink_0())
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.text_ellipsis()
.whitespace_nowrap()
.when(ctx.selection().is_empty(), |this| this.text_color(muted))
.child(
ctx.selection()
.first()
.map(|(_, item)| item.clone())
.or_else(|| ctx.placeholder().cloned())
.unwrap_or_default(),
),
)
.child(Caret::new(ctx.size()).text_color(muted))
.into_any_element()
}
-2
View File
@@ -21,12 +21,10 @@ impl SelectOption {
}
}
/// The stored value of this option.
pub fn value(&self) -> &SharedString {
&self.value
}
/// The display label of this option.
pub fn label(&self) -> &SharedString {
&self.label
}
-1
View File
@@ -35,7 +35,6 @@ where
.child(div().text_sm().text_ellipsis().child(item.label.clone())),
)
.on_click(move |_event, window, cx| {
// Folders expand/collapse via the tree itself.
if is_folder {
return;
}
+11 -2
View File
@@ -1,7 +1,7 @@
use gpui::prelude::*;
use gpui::{App, SharedString, StyleRefinement, Window};
use gpui_component::avatar::Avatar;
use gpui_component::{ActiveTheme, Sizable, StyledExt};
use gpui_component::{ActiveTheme, Sizable, Size, StyledExt};
/// A small user avatar from gpui-component [`Avatar`], rounded with the theme radius.
/// It shows the user's picture or falls back to name initials.
@@ -9,6 +9,7 @@ use gpui_component::{ActiveTheme, Sizable, StyledExt};
pub struct UserAvatar {
name: SharedString,
picture: Option<SharedString>,
size: Size,
style: StyleRefinement,
}
@@ -19,6 +20,7 @@ impl UserAvatar {
Self {
name: name.into(),
picture: None,
size: Size::Small,
style: StyleRefinement::default(),
}
}
@@ -30,6 +32,13 @@ impl UserAvatar {
}
}
impl Sizable for UserAvatar {
fn with_size(mut self, size: impl Into<Size>) -> Self {
self.size = size.into();
self
}
}
impl Styled for UserAvatar {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
@@ -43,6 +52,6 @@ impl RenderOnce for UserAvatar {
.when_some(self.picture, |this, url| this.src(url))
.rounded(cx.theme().radius)
.refine_style(&self.style)
.small()
.with_size(self.size)
}
}
-1
View File
@@ -33,7 +33,6 @@ mod tests {
),
"30617:a008...3564d:ngit"
);
// Too short to save space with the ellipsis, left alone.
assert_eq!(middle_truncate("short", 10, 10), "short");
}
}
+45 -3
View File
@@ -1,7 +1,49 @@
use nostr::prelude::*;
/// Shorten a [`PublicKey`] to `npub1abc...wxyz` form.
pub fn shorten_pubkey(public_key: PublicKey, len: usize) -> String {
let npub = public_key.to_bech32().unwrap();
format!("{}...{}", &npub[..(len + 5)], &npub[npub.len() - len..])
pub fn shorten_pubkey(public_key: PublicKey) -> String {
let encoded = public_key
.to_bech32()
.unwrap_or_else(|_| public_key.to_hex());
truncate_middle(&encoded)
}
fn truncate_middle(value: &str) -> String {
const HEAD_CHARS: usize = 9;
const TAIL_CHARS: usize = 4;
let length = value.chars().count();
if length <= HEAD_CHARS + TAIL_CHARS + 3 {
return value.to_owned();
}
let head: String = value.chars().take(HEAD_CHARS).collect();
let tail: String = value.chars().skip(length - TAIL_CHARS).collect();
format!("{head}...{tail}")
}
#[cfg(test)]
mod tests {
use super::*;
const PUBLIC_KEY_HEX: &str = "68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272";
#[test]
fn shortens_a_valid_pubkey() {
let public_key = PublicKey::from_hex(PUBLIC_KEY_HEX).expect("valid pubkey");
let npub = public_key.to_bech32().expect("valid pubkey encodes");
assert_eq!(
shorten_pubkey(public_key),
format!("{}...{}", &npub[..9], &npub[npub.len() - 4..])
);
}
#[test]
fn leaves_short_values_intact() {
assert_eq!(truncate_middle("npub1short"), "npub1short");
assert_eq!(truncate_middle("thirteenchars"), "thirteenchars");
}
}
+1 -5
View File
@@ -39,10 +39,6 @@ mod tests {
assert_eq!(relative_time(now - 3 * 86_400), "3d ago");
assert_eq!(relative_time(now - 60 * 86_400), "2mo ago");
assert_eq!(relative_time(now - 800 * 86_400), "2y ago");
}
#[test]
fn clamps_future_timestamps() {
assert_eq!(relative_time(Timestamp::now() + 600), "just now");
assert_eq!(relative_time(now + 600), "just now");
}
}
-1
View File
@@ -18,7 +18,6 @@ utils = { path = "../utils" }
gpui.workspace = true
gpui-component.workspace = true
gpui-base.workspace = true
gpui-fps.workspace = true
gix.workspace = true
nostr.workspace = true
@@ -13,34 +13,25 @@ use gpui_component::resizable::{resizable_panel, v_resizable};
use gpui_component::scroll::{ScrollableElement, Scrollbar};
use gpui_component::spinner::Spinner;
use gpui_component::tag::Tag;
use gpui_component::tree::{TreeEntry, TreeState, tree};
use gpui_component::tree::{TreeEntry, TreeItem, TreeState, tree};
use gpui_component::{
ActiveTheme, Sizable, StyledExt, VirtualListScrollHandle, h_flex, v_flex, v_virtual_list,
};
use signed_git::{CommitDiff, DiffStatus, FileCommit, FileDiff};
use signed_git::{CommitDiff, DiffHunk, DiffLine, DiffLineKind, DiffStatus, FileCommit, FileDiff};
use signed_ui::{placeholder, tree_row};
use utils::relative_time_secs;
use super::helpers::{
DIFF_ROW_HEIGHT, DiffRow, build_tree_items, diff_rows, find_item, render_diff_row, tree_items,
};
use crate::views::tree::{build_tree_items, tree_items};
/// Width of the changed-files column.
const TREE_WIDTH: f32 = 260.;
/// Tree and per-file diff body, shared by the commit diff and compare views.
pub struct DiffPane {
/// Loaded diff, `None` until [`Self::set_diff`] is called.
diff: Option<CommitDiff>,
/// Changed-files explorer state.
tree_state: Entity<TreeState>,
/// Path of the file whose diff is shown in the detail column.
selected_file: Option<SharedString>,
/// Rows of the selected file's diff, hunk headers and lines.
rows: Vec<DiffRow>,
/// Per-row heights of [`Self::rows`].
item_sizes: Rc<Vec<Size<Pixels>>>,
/// Virtual list state of the diff rows.
scroll_handle: VirtualListScrollHandle,
}
@@ -56,12 +47,10 @@ impl DiffPane {
}
}
/// The loaded diff, for stats and badges in the host's header.
pub fn diff(&self) -> Option<&CommitDiff> {
self.diff.as_ref()
}
/// Replace the diff and rebuild the tree and the selected file's rows.
pub fn set_diff(&mut self, diff: CommitDiff, cx: &mut Context<Self>) {
let mut paths: Vec<PathBuf> = diff
.files
@@ -86,9 +75,6 @@ impl DiffPane {
}
}
/// Forget the diff, e.g. when the compared branches changed.
///
/// Clears the tree, the selection and the diff rows.
pub fn clear(&mut self, cx: &mut Context<Self>) {
self.diff = None;
self.selected_file = None;
@@ -99,14 +85,12 @@ impl DiffPane {
});
}
/// Show the diff of the file at `path`, selected in the tree.
fn select_file(&mut self, path: &str, cx: &mut Context<Self>) {
self.selected_file = Some(path.into());
self.set_diff_rows(path);
cx.notify();
}
/// Rebuild the virtual list state for `path` and scroll back to the top.
fn set_diff_rows(&mut self, path: &str) {
let Some(diff) = self.diff.as_ref() else {
return;
@@ -119,7 +103,6 @@ impl DiffPane {
self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
}
/// One row of the changed-files tree, icon and name, indented by depth.
fn render_tree_item(
ix: usize,
entry: &TreeEntry,
@@ -136,7 +119,6 @@ impl DiffPane {
})
}
/// Left column showing the changed-files tree.
fn render_tree_column(&self, cx: &mut Context<Self>) -> AnyElement {
let tree_state = self.tree_state.clone();
let view = cx.entity().downgrade();
@@ -166,7 +148,6 @@ impl DiffPane {
.into_any_element()
}
/// Right column, header of the selected file plus its diff.
fn render_detail_column(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(diff) = self.diff.as_ref() else {
return placeholder("No changes", cx);
@@ -184,7 +165,6 @@ impl DiffPane {
self.render_file_diff(file, cx.entity(), cx)
}
/// The diff of one file, with a header showing status and stats.
fn render_file_diff(&self, file: &FileDiff, view: Entity<Self>, cx: &App) -> AnyElement {
let status_label = match file.status {
DiffStatus::Added => "A",
@@ -311,22 +291,15 @@ impl Render for DiffPane {
}
}
/// Detail panel showing the diff of one commit.
pub struct CommitDiffView {
focus_handle: FocusHandle,
/// Local clone the commit lives in.
worktree: PathBuf,
/// Display name of the repository the commit belongs to.
repo_name: SharedString,
/// The commit being shown in the header and tab title.
commit: FileCommit,
/// The diff is being computed on a background task.
loading: bool,
error: Option<SharedString>,
/// Changed-files explorer and per-file diff, also used by the new PR panel's compare view.
pane: Entity<DiffPane>,
/// In-flight tasks, pruned on every push.
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
}
impl CommitDiffView {
@@ -358,11 +331,9 @@ impl CommitDiffView {
loading: true,
error: None,
pane,
tasks: Vec::new(),
}
}
/// Load the commit diff and the full commit metadata.
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.loading = true;
self.error = None;
@@ -371,45 +342,45 @@ impl CommitDiffView {
let worktree = self.worktree.clone();
let id = self.commit.id.clone();
let task = cx.spawn_in(window, async move |this, cx| {
let commit = cx
.background_spawn({
let worktree = worktree.clone();
let id = id.clone();
async move { signed_git::worktree_commit(&worktree, &id) }
})
.await;
let diff = cx
.background_spawn({
let worktree = worktree.clone();
let id = id.clone();
async move { signed_git::worktree_commit_diff(&worktree, &id) }
})
.await;
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let commit = cx
.background_spawn({
let worktree = worktree.clone();
let id = id.clone();
async move { signed_git::worktree_commit(&worktree, &id) }
})
.await;
let diff = cx
.background_spawn({
let worktree = worktree.clone();
let id = id.clone();
async move { signed_git::worktree_commit_diff(&worktree, &id) }
})
.await;
this.update_in(cx, |this, _window, cx| {
this.loading = false;
if let Ok(Some(commit)) = commit {
this.commit = commit;
}
match diff {
Ok(diff) => {
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
this.update_in(cx, |this, _window, cx| {
this.loading = false;
if let Ok(Some(commit)) = commit {
this.commit = commit;
}
Err(error) => {
this.error = Some(error.to_string().into());
match diff {
Ok(diff) => {
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.error = Some(error.to_string().into());
}
}
}
cx.notify();
})?;
cx.notify();
})?;
Ok(())
});
Ok(())
});
self.tasks.push(task);
task.detach();
}
/// Header with the commit id, summary, author/time and overall change stats.
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let commit = &self.commit;
let (files, insertions, deletions) = self.pane.read(cx).diff().map_or((0, 0, 0), |diff| {
@@ -537,3 +508,180 @@ impl Render for CommitDiffView {
.child(resizable_panel().child(body))
}
}
const GUTTER_WIDTH: f32 = 44.;
const DIFF_ROW_HEIGHT: f32 = 20.;
#[derive(Clone, Copy)]
enum DiffRow {
Hunk {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
},
Line {
hunk: usize,
line: usize,
},
}
fn diff_rows(file: &FileDiff) -> Vec<DiffRow> {
let mut rows = Vec::new();
for (hunk_ix, hunk) in file.hunks.iter().enumerate() {
rows.push(DiffRow::Hunk {
old_start: hunk.old_start,
old_lines: hunk.old_lines,
new_start: hunk.new_start,
new_lines: hunk.new_lines,
});
rows.extend((0..hunk.lines.len()).map(|line| DiffRow::Line {
hunk: hunk_ix,
line,
}));
}
rows
}
fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> AnyElement {
match row {
DiffRow::Hunk {
old_start,
old_lines,
new_start,
new_lines,
} => div()
.px_2()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font_family.clone())
.text_xs()
.bg(cx.theme().muted)
.border_y(px(1.))
.border_color(cx.theme().border)
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(format!(
"@@ -{},{} +{},{} @@",
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => render_diff_line(&hunks[hunk].lines[line], cx),
}
}
fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement {
let bg = match line.kind {
DiffLineKind::Addition => Some(cx.theme().success.opacity(0.2)),
DiffLineKind::Deletion => Some(cx.theme().danger.opacity(0.2)),
DiffLineKind::Context => None,
};
let gutter = cx.theme().muted_foreground;
// Fixed height and nowrap, the virtual list assumes every row has the same height.
// Long lines are clipped instead of wrapped.
h_flex()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.items_center()
.font_family(cx.theme().mono_font_family.clone())
.text_xs()
.when_some(bg, |this, bg| this.bg(bg))
.child(
div()
.w(px(GUTTER_WIDTH))
.flex_none()
.pr_2()
.text_right()
.text_color(gutter)
.child(line.old.map(|n| n.to_string()).unwrap_or_default()),
)
.child(
div()
.w(px(GUTTER_WIDTH))
.flex_none()
.pr_2()
.text_right()
.text_color(gutter)
.child(line.new.map(|n| n.to_string()).unwrap_or_default()),
)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_color(cx.theme().foreground)
.child(line.text.clone()),
)
.into_any_element()
}
fn find_item<'a>(items: &'a [TreeItem], id: Option<&str>) -> Option<&'a TreeItem> {
let id = id?;
items.iter().find_map(|item| {
if item.id.as_ref() == id {
Some(item)
} else {
find_item(&item.children, Some(id))
}
})
}
pub(crate) const COMMIT_ROW_HEIGHT: f32 = 56.;
pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit,
on_click: impl Fn(&mut Window, &mut App) + 'static,
cx: &App,
) -> AnyElement {
h_flex()
.id(ix)
.px_4()
.h(px(COMMIT_ROW_HEIGHT))
.w_full()
.gap_3()
.items_center()
.border_b(px(1.))
.border_color(cx.theme().border)
.hover(|this| this.bg(cx.theme().list_hover))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_0p5()
.justify_center()
.child(
h_flex()
.gap_2()
.items_center()
.overflow_hidden()
.child(
div()
.font_family(cx.theme().mono_font_family.clone())
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(commit.id.clone()),
)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
.child(
h_flex()
.gap_2()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
)
.on_click(move |_event, window, cx| on_click(window, cx))
.into_any_element()
}
+3 -4
View File
@@ -2,8 +2,7 @@ use gpui::prelude::*;
use gpui::{AnyElement, App, SharedString, div};
use gpui_component::ActiveTheme;
/// Progress of an async dialog action: a busy flag disabling the form,
/// and an error line shown under it.
/// Progress of an async dialog action: a busy flag that disables the form and an error shown below it.
#[derive(Debug, Default)]
pub struct DialogProgress {
pub busy: bool,
@@ -11,13 +10,13 @@ pub struct DialogProgress {
}
impl DialogProgress {
/// An action started, disable the form and clear the previous error.
/// Marks an action as started, disabling the form and clearing the previous error.
pub fn begin(&mut self) {
self.busy = true;
self.error = None;
}
/// An action failed, re-enable the form and surface `message`.
/// Marks an action as failed, enabling the form and showing `message`.
pub fn fail(&mut self, message: impl Into<SharedString>) {
self.busy = false;
self.error = Some(message.into());
+217
View File
@@ -0,0 +1,217 @@
use assets::CustomIconName;
use gpui::prelude::*;
use gpui::{AnyElement, App, Entity, SharedString, div, px};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::input::{Textarea, TextareaState};
use gpui_component::tag::Tag;
use gpui_component::{ActiveTheme, Icon, Sizable, StyledExt, h_flex, v_flex};
use nostr::prelude::{Event, EventId, PublicKey};
use signed_state::{ProfileStore, RepoStore};
use signed_ui::UserAvatar;
use utils::relative_time;
pub(crate) fn issue_roots(store: &RepoStore) -> &[Event] {
&store.issues
}
pub(crate) fn pr_roots(store: &RepoStore) -> &[Event] {
&store.pull_requests
}
fn sidebar_title(text: &str, cx: &App) -> AnyElement {
div()
.text_xs()
.font_semibold()
.text_color(cx.theme().muted_foreground)
.child(text.to_string())
.into_any_element()
}
pub(crate) fn sidebar_section(
store: &Entity<RepoStore>,
id: EventId,
roots: fn(&RepoStore) -> &[Event],
top_gap: bool,
cx: &App,
) -> AnyElement {
let store = store.read(cx);
let Some(root) = roots(store).iter().find(|event| event.id == id) else {
// The caller bails out when the root is missing.
return div().into_any_element();
};
let profile_store = ProfileStore::global(cx);
// Participants, the root author plus everyone who commented.
let mut participants: Vec<PublicKey> = vec![root.pubkey];
participants.extend(store.comments_of(&root.id).map(|comment| comment.pubkey));
participants.sort_by_key(PublicKey::to_hex);
participants.dedup();
// Labels are NIP-34 `t` hashtag tags on the event.
let labels: Vec<String> = root.tags.hashtags().map(|tag| tag.to_string()).collect();
v_flex()
.w(px(240.))
.h_full()
.flex_none()
.px_4()
.gap_4()
.border_l(px(1.))
.border_color(cx.theme().sidebar_border)
.child(
v_flex()
.when(top_gap, |this| this.mt_4())
.gap_2()
.child(sidebar_title("Participants", cx))
.children(participants.iter().map(|pubkey| {
let profile = profile_store.read(cx).get(pubkey);
let name = profile.name();
let picture = profile.picture();
h_flex()
.gap_1()
.items_center()
.child(UserAvatar::new(name.clone()).picture(picture))
.child(div().text_sm().truncate().text_ellipsis().child(name))
.into_any_element()
})),
)
.child(
v_flex()
.gap_2()
.child(sidebar_title("Labels", cx))
.map(|this| {
if labels.is_empty() {
this.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child("None yet."),
)
} else {
this.child(h_flex().gap_1().children({
let mut items = vec![];
for label in labels.iter() {
items.push(
Tag::secondary()
.outline()
.xsmall()
.child(SharedString::from(label)),
);
}
items
}))
}
}),
)
.into_any_element()
}
pub(crate) fn comments_section(store: &Entity<RepoStore>, root: EventId, cx: &App) -> AnyElement {
let store = store.read(cx);
let comments: Vec<&Event> = store.comments_of(&root).collect();
let title = SharedString::from(format!("Discussions {}", comments.len()));
v_flex()
.gap_4()
.child(div().text_xs().font_semibold().child(title))
.children(comments.iter().map(|comment| {
let profile = ProfileStore::global(cx).read(cx).get(&comment.pubkey);
let author = profile.name();
let picture = profile.picture();
let age = relative_time(comment.created_at);
let content = SharedString::from(comment.content.as_str());
v_flex()
.gap_1()
.p_3()
.border_1()
.border_color(cx.theme().border)
.rounded(cx.theme().radius)
.child(
h_flex()
.gap_2()
.text_sm()
.child(
h_flex()
.gap_1()
.child(UserAvatar::new(author.clone()).picture(picture))
.child(author),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child("commented"),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(age)),
),
)
.child(div().text_sm().child(content))
}))
.into_any_element()
}
/// `roots` selects the root's list within the store, issues or pull requests.
pub(crate) fn comment_form(
store: &Entity<RepoStore>,
root: EventId,
roots: fn(&RepoStore) -> &[Event],
comment_input: &Entity<TextareaState>,
button_id: &'static str,
cx: &App,
) -> AnyElement {
let comment_input = comment_input.clone();
let store = store.clone();
v_flex()
.gap_2()
.child(
Textarea::new(&comment_input)
.h_24()
.text_color(cx.theme().muted_foreground)
.bg(cx.theme().muted),
)
.child(
h_flex()
.justify_between()
.child(
h_flex()
.gap_1()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(Icon::new(CustomIconName::Markdown).small())
.child("Markdown is supported"),
)
.child(
Button::new(button_id)
.primary()
.label("Comment")
.tooltip("Post comment")
.on_click(move |_event, window, cx| {
let content = comment_input.read(cx).value().trim().to_string();
if content.is_empty() {
return;
}
let Some(root) = roots(store.read(cx))
.iter()
.find(|event| event.id == root)
.cloned()
else {
return;
};
store.update(cx, |store, cx| {
store.comment(&root, content, cx);
});
comment_input.update(cx, |input, cx| {
input.set_value("", window, cx);
});
}),
),
)
.into_any_element()
}
+696
View File
@@ -0,0 +1,696 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Error;
use dock::{BasePanel, DockArea, Panel, PanelEvent};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Div, EventEmitter, FocusHandle, Focusable, ListAlignment, ListState,
Pixels, Render, SharedString, Stateful, Subscription, Task, WeakEntity, Window, div, list, px,
};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::{ActiveTheme, Icon, IconName, IconNamed, Sizable, StyledExt, h_flex, v_flex};
use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp};
use signed_core::{COVER_NOTE_KIND, InboxItem, InboxReadState, RepoAddr, filters};
use signed_state::{
Backend, BackendEvent, ProfileStore, RefreshGate, RefreshRequest, RepoListStore, query_inbox,
};
use signed_ui::{CountBadge, UserAvatar};
use utils::relative_time;
use super::{RepoItem, open_repo_item};
const LIST_OVERDRAW: Pixels = px(400.);
const MAX_SUB_ACTIVITIES: usize = 5;
struct InboxSection {
/// `None` for items without a repository.
address: Option<RepoAddr>,
unread: usize,
/// Indices into the threads, newest activity first.
entries: Vec<usize>,
/// Timestamp of the newest entry, used to order the sections.
latest: Timestamp,
}
#[derive(Clone, Copy)]
enum InboxRow {
Repo(usize),
Entry(usize, usize),
Empty,
}
pub struct InboxView {
focus_handle: FocusHandle,
dock_area: WeakEntity<DockArea>,
/// One row per thread, merging notifications and own activity, newest first.
threads: Arc<Vec<InboxItem>>,
sections: Arc<Vec<InboxSection>>,
rows: Arc<Vec<InboxRow>>,
unread_count: usize,
/// Copy of the global read state the current lists were derived with.
state: InboxReadState,
state_loaded: bool,
refresh: RefreshGate,
list: ListState,
tasks: Vec<Task<Result<(), Error>>>,
_subscriptions: Vec<Subscription>,
}
impl InboxView {
pub fn new(dock_area: WeakEntity<DockArea>, cx: &mut Context<Self>) -> Self {
let backend = Backend::global(cx);
let inbox = backend.read(cx).inbox();
let repos = RepoListStore::global(cx);
let weak = cx.entity().downgrade();
let list = ListState::new(0, ListAlignment::Top, LIST_OVERDRAW);
let mut subscriptions = vec![];
subscriptions.push(cx.observe(&inbox, |this, _inbox, cx| {
this.sync_state(cx);
}));
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
this.handle_backend_event(event, cx);
}));
// Rebuild when the user's own repositories load or change,
// so a repository without any activity still gets an empty section.
subscriptions.push(cx.observe(&repos, |this, _repos, cx| {
this.rebuild(cx);
cx.notify();
}));
// Derive the sections once the panel exists.
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.sync_state(cx)) {
log::warn!("inbox dropped before bootstrap could run: {error}");
}
});
Self {
focus_handle: cx.focus_handle(),
dock_area,
threads: Arc::new(Vec::new()),
sections: Arc::new(Vec::new()),
rows: Arc::new(Vec::new()),
unread_count: 0,
state: InboxReadState::default(),
state_loaded: false,
refresh: RefreshGate::default(),
list,
tasks: vec![],
_subscriptions: subscriptions,
}
}
pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
let Some(me) = Backend::global(cx).read(cx).current_user() else {
return;
};
let all: Vec<Event> = self
.threads
.iter()
.flat_map(|item| item.events.iter().cloned())
.collect();
let backend = Backend::global(cx);
let inbox = backend.read(cx).inbox();
inbox.update(cx, |inbox, cx| inbox.mark_all_read(&all, me, cx));
}
pub fn sync_state(&mut self, cx: &mut Context<Self>) {
let backend = Backend::global(cx);
let inbox = backend.read(cx).inbox();
let (loaded, state) = {
let inbox = inbox.read(cx);
(inbox.is_loaded(), inbox.state().clone())
};
if !loaded {
let was_present =
self.state_loaded || !self.threads.is_empty() || !self.sections.is_empty();
self.clear();
if was_present {
cx.notify();
}
return;
}
if !self.state_loaded {
self.state_loaded = true;
self.state = state;
self.refresh_initial(cx);
return;
}
if self.state != state {
self.state = state;
self.regroup(cx);
cx.notify();
}
}
fn handle_backend_event(&mut self, event: &BackendEvent, cx: &mut Context<Self>) {
match event {
BackendEvent::NostrUpdate(updates) => {
let relevant = updates.iter().any(|update| {
let is_notification = filters::NOTIFICATION_KINDS.contains(&update.kind);
let is_comment = update.kind == Kind::Comment;
let is_event_deletion = update.kind == Kind::EventDeletion;
let is_request_to_vanish = update.kind == Kind::RequestToVanish;
is_notification || is_comment || is_event_deletion || is_request_to_vanish
});
if relevant {
self.refresh(cx);
}
}
BackendEvent::Synced | BackendEvent::Published(_) => self.refresh(cx),
_ => {}
}
}
fn refresh_initial(&mut self, cx: &mut Context<Self>) {
if self.refresh.running() {
self.refresh.request();
return;
}
self.run_refresh(cx);
}
fn refresh(&mut self, cx: &mut Context<Self>) {
if !self.state_loaded {
return;
}
if self.refresh.request() != RefreshRequest::Schedule {
return;
}
self.run_refresh(cx);
}
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refresh.begin();
let backend = Backend::global(cx);
let Some(me) = backend.read(cx).current_user() else {
self.refresh.abort();
return;
};
let client = backend.read(cx).client();
let state = self.state.clone();
let work = cx.background_spawn(async move { query_inbox(&client, me, &state).await });
self.tasks.push(cx.spawn(async move |this, cx| {
let (threads, unread_count) = match work.await {
Ok(results) => results,
Err(error) => {
log::warn!("inbox refresh failed: {error}");
return this.update(cx, |this, _cx| this.refresh.abort());
}
};
let again = this.update(cx, |this, cx| {
if backend.read(cx).current_user() != Some(me) {
this.refresh.abort();
return false;
}
this.threads = Arc::new(threads);
this.unread_count = unread_count;
this.rebuild(cx);
cx.notify();
this.refresh.finish()
})?;
if again {
this.update(cx, |this, cx| this.refresh(cx))?;
}
Ok(())
}));
}
fn regroup(&mut self, cx: &mut Context<Self>) {
let mut items = (*self.threads).clone();
for item in items.iter_mut() {
item.apply_state(&self.state);
}
self.unread_count = items.iter().filter(|item| item.is_unread()).count();
self.threads = Arc::new(items);
self.rebuild(cx);
}
fn rebuild(&mut self, cx: &mut Context<Self>) {
let backend = Backend::global(cx);
let repo_list = RepoListStore::global(cx);
let mut sections = self.group_sections();
if let Some(me) = backend.read(cx).current_user() {
for announcement in repo_list.read(cx).announcements_of(&me) {
let address = announcement.addr();
let known = sections
.iter()
.any(|section| section.address.as_ref() == Some(&address));
if !known {
sections.push(InboxSection {
address: Some(address),
unread: 0,
entries: Vec::new(),
latest: Timestamp::default(),
});
}
}
}
sections.sort_by_key(|section| std::cmp::Reverse(section.latest));
let rows = self.flatten_rows(&sections);
self.sections = Arc::new(sections);
self.rows = Arc::new(rows);
}
fn group_sections(&self) -> Vec<InboxSection> {
let mut by_repo: HashMap<Option<RepoAddr>, InboxSection> = HashMap::new();
for (ix, item) in self.threads.iter().enumerate() {
if item.archived {
continue;
}
let address = item.address.clone();
let section = by_repo
.entry(address.clone())
.or_insert_with(move || InboxSection {
address,
unread: 0,
entries: Vec::new(),
latest: Timestamp::default(),
});
if item.is_unread() {
section.unread += 1;
}
section.latest = section.latest.max(item.latest_activity());
section.entries.push(ix);
}
let mut sections: Vec<InboxSection> = by_repo.into_values().collect();
for section in &mut sections {
section.entries.sort_by(|a, b| {
self.threads[*b]
.latest_activity()
.cmp(&self.threads[*a].latest_activity())
});
}
sections.sort_by_key(|section| std::cmp::Reverse(section.latest));
sections
}
fn flatten_rows(&self, sections: &[InboxSection]) -> Vec<InboxRow> {
let mut rows = Vec::new();
for (section_ix, section) in sections.iter().enumerate() {
rows.push(InboxRow::Repo(section_ix));
if section.entries.is_empty() {
rows.push(InboxRow::Empty);
continue;
}
rows.extend(
(0..section.entries.len()).map(|entry_ix| InboxRow::Entry(section_ix, entry_ix)),
);
}
rows
}
fn clear(&mut self) {
self.threads = Arc::new(Vec::new());
self.sections = Arc::new(Vec::new());
self.rows = Arc::new(Vec::new());
self.unread_count = 0;
self.state = InboxReadState::default();
self.state_loaded = false;
// Drop any in-flight or pending run belonging to the previous user.
self.refresh = RefreshGate::default();
}
fn open(
&self,
root: EventId,
kind: Option<Kind>,
address: Option<RepoAddr>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(address) = address else {
return;
};
let item = match kind {
Some(Kind::GitIssue) => RepoItem::Issue(root),
Some(Kind::GitPullRequest) => RepoItem::PullRequest(root),
Some(Kind::GitPatch) => RepoItem::Patch,
_ => return,
};
open_repo_item(&self.dock_area, &address, None, item, window, cx);
}
fn render_entry(&self, ix: usize, cx: &Context<Self>) -> AnyElement {
let Some(row) = self.rows.get(ix) else {
return div().into_any_element();
};
match *row {
InboxRow::Empty => empty_section_row(cx),
InboxRow::Repo(section_ix) => {
let Some(section) = self.sections.get(section_ix) else {
return div().into_any_element();
};
repo_header(section, cx)
}
InboxRow::Entry(section_ix, entry_ix) => {
let Some(section) = self.sections.get(section_ix) else {
return div().into_any_element();
};
let Some(&thread_ix) = section.entries.get(entry_ix) else {
return div().into_any_element();
};
let Some(item) = self.threads.get(thread_ix) else {
return div().into_any_element();
};
let root = item.root;
let kind = item.root_event.as_ref().map(|event| event.kind);
let address = section.address.clone();
let first = entry_ix == 0;
let last = entry_ix + 1 == section.entries.len();
thread("inbox-row", ix, item, first, last, cx)
.on_click(cx.listener(move |this, _ev, window, cx| {
this.open(root, kind, address.clone(), window, cx)
}))
.into_any_element()
}
}
}
}
fn repo_name(addr: Option<&RepoAddr>, cx: &App) -> Option<SharedString> {
let repo_list = RepoListStore::global(cx);
let addr = addr?;
repo_list
.read(cx)
.announcements
.iter()
.find(|announcement| announcement.addr() == *addr)
.map(|announcement| announcement.name().map(SharedString::from))
}
fn repo_header(section: &InboxSection, cx: &App) -> AnyElement {
let name =
repo_name(section.address.as_ref(), cx).unwrap_or_else(|| SharedString::from("Untitled"));
h_flex()
.h_12()
.w_full()
.gap_1()
.items_center()
.child(
div()
.min_w_0()
.text_sm()
.whitespace_nowrap()
.text_ellipsis()
.child(name),
)
.when(section.unread > 0, |this| {
this.child(CountBadge::new(section.unread))
})
.into_any_element()
}
fn empty_section_row(cx: &App) -> AnyElement {
h_flex()
.h_12()
.w_full()
.px_3()
.text_xs()
.text_color(cx.theme().secondary_foreground)
.bg(cx.theme().secondary.alpha(0.6))
.rounded(cx.theme().radius)
.child(SharedString::from("No activity yet."))
.into_any_element()
}
fn thread(
prefix: &'static str,
ix: usize,
item: &InboxItem,
first: bool,
last: bool,
cx: &App,
) -> Stateful<Div> {
let title = SharedString::from(item.title());
let unread = item.is_unread();
let backend = Backend::global(cx);
let me = backend.read(cx).current_user();
let mut timeline = v_flex().gap_2().w_full();
for event in item.timeline(MAX_SUB_ACTIVITIES) {
timeline = timeline.child(sub_activity(&event, me, cx));
}
v_flex()
.id((prefix, ix))
.w_full()
.px_3()
.py_2()
.gap_2()
.bg(cx.theme().secondary.alpha(0.6))
.when(first, |this| this.rounded_t(cx.theme().radius))
.when(last, |this| this.rounded_b(cx.theme().radius))
.when(!last, |this| {
this.border_b_1().border_color(cx.theme().background)
})
.hover(|this| this.bg(cx.theme().secondary_hover.alpha(0.8)))
.child(
h_flex()
.gap_2()
.text_sm()
.child(
h_flex()
.size_6()
.flex_shrink_0()
.items_center()
.justify_center()
.child(Icon::new(IconName::Bell)),
)
.child(
div()
.min_w_0()
.whitespace_nowrap()
.text_ellipsis()
.child(title),
)
.child(div().flex_1())
.when(unread, |this| {
this.child(
div()
.flex_shrink_0()
.size_2()
.rounded_full()
.bg(cx.theme().primary),
)
}),
)
.child(timeline)
}
fn sub_activity(event: &Event, me: Option<PublicKey>, cx: &App) -> AnyElement {
let profile_store = ProfileStore::global(cx).read(cx);
let profile = profile_store.get(&event.pubkey);
let name = if Some(event.pubkey) == me {
SharedString::from("You")
} else {
profile.name()
};
h_flex()
.w_full()
.gap_2()
.items_center()
.child(div().w_6().flex_shrink_0())
.child(
h_flex()
.flex_1()
.min_w_0()
.gap_1()
.items_center()
.text_xs()
.child(
UserAvatar::new(name.clone())
.picture(profile.picture())
.xsmall(),
)
.child(name)
.child(SharedString::from(activity_phrase(event.kind)))
.child(div().flex_1())
.child(
div()
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(relative_time(event.created_at))),
),
)
.into_any_element()
}
fn activity_phrase(kind: Kind) -> &'static str {
if kind == COVER_NOTE_KIND {
return "added a note";
}
match kind {
Kind::GitIssue => "opened an issue",
Kind::GitPullRequest => "opened a PR",
Kind::GitPullRequestUpdate => "updated a PR",
Kind::GitPatch => "created a patch",
Kind::Comment => "commented",
Kind::GitStatusOpen => "opened a status",
Kind::GitStatusApplied => "applied a status",
Kind::GitStatusClosed => "closed a status",
Kind::GitStatusDraft => "drafted a status",
_ => "did something",
}
}
fn empty_state(icon: impl IconNamed, message: &str, cx: &App) -> AnyElement {
v_flex()
.w_full()
.flex_1()
.min_h_0()
.items_center()
.justify_center()
.gap_2()
.py_8()
.child(
Icon::new(icon)
.large()
.text_color(cx.theme().muted_foreground),
)
.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(message)),
)
.into_any_element()
}
impl BasePanel for InboxView {
fn panel_name(&self) -> &'static str {
"inbox"
}
}
impl Panel for InboxView {
fn title(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().text_sm().child(SharedString::from("Inbox"))
}
}
impl EventEmitter<PanelEvent> for InboxView {}
impl Focusable for InboxView {
fn focus_handle(&self, _cx: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl Render for InboxView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let rows = self.rows.clone();
if self.list.item_count() != rows.len() {
self.list.reset(rows.len());
}
v_flex()
.image_cache(gpui::retain_all("inbox"))
.size_full()
.gap_2()
.child(
h_flex()
.px_4()
.h_12()
.w_full()
.gap_1()
.items_center()
.child(
div()
.text_sm()
.font_semibold()
.child(SharedString::from("Inbox")),
)
.child(div().flex_1())
.child(
Button::new("mark-all")
.icon(IconName::CircleCheck)
.secondary()
.tooltip("Mark all as read")
.on_click(cx.listener(move |this, _ev, _window, cx| {
this.mark_all_read(cx);
})),
),
)
.child(
div()
.relative()
.flex_1()
.min_h_0()
.px_4()
.when_else(
rows.is_empty(),
|this| {
this.child(empty_state(IconName::Inbox, "You're all caught up.", cx))
},
|this| {
this.child(
list(
self.list.clone(),
cx.processor(|this, ix, _window, cx| this.render_entry(ix, cx)),
)
.size_full()
.min_h_0()
.into_any_element(),
)
},
)
.child(div().h_6().w_full().flex_shrink_0()),
)
}
}
@@ -1,8 +1,8 @@
use dock::{BasePanel, Panel, PanelEvent};
use gpui::prelude::*;
use gpui::{
App, Context, Entity, EventEmitter, FocusHandle, Focusable, Render, SharedString, Window, div,
relative,
App, Context, Entity, EventEmitter, FocusHandle, Focusable, Render, SharedString, Subscription,
Window, div, relative,
};
use gpui_component::input::TextareaState;
use gpui_component::scroll::ScrollableElement;
@@ -13,16 +13,14 @@ use signed_state::{ProfileStore, RepoStore};
use signed_ui::{UserAvatar, placeholder, status_badge};
use utils::relative_time;
use super::helpers::{comment_form, comments_section, issue_roots, sidebar_section};
use crate::views::discussion::{comment_form, comments_section, issue_roots, sidebar_section};
/// Detail panel of a single issue.
pub struct IssueDetailView {
/// Repo store holding the issues and their statuses.
focus_handle: FocusHandle,
store: Entity<RepoStore>,
issue_id: EventId,
/// Input state of the comment textarea.
comment_input: Entity<TextareaState>,
focus_handle: FocusHandle,
_subscription: Subscription,
}
impl IssueDetailView {
@@ -35,11 +33,14 @@ impl IssueDetailView {
let comment_input =
cx.new(|cx| TextareaState::new(window, cx).placeholder("Leave a comment..."));
let subscription = cx.observe(&store, |_this, _store, cx| cx.notify());
Self {
focus_handle: cx.focus_handle(),
store,
issue_id,
comment_input,
_subscription: subscription,
}
}
}
@@ -81,7 +82,12 @@ impl Render for IssueDetailView {
let store = self.store.read(cx);
let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else {
return placeholder("Issue not found", cx);
// The store has not applied its first pass yet, the issue may still arrive.
return if store.loaded {
placeholder("Issue not found", cx)
} else {
placeholder("Loading issue...", cx)
};
};
let (title, author, picture, status, age, issue_id, content) = {
@@ -4,8 +4,8 @@ use assets::CustomIconName;
use dock::{BasePanel, DockArea, Panel, PanelEvent, add_center_panel, panel_handle};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
SharedString, Size, WeakEntity, Window, div, px, size,
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels,
Render, SharedString, Size, Subscription, WeakEntity, Window, div, px, size,
};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
@@ -21,24 +21,21 @@ use signed_state::{ProfileStore, RepoStore};
use signed_ui::{SegmentButton, UserAvatar, placeholder, status_badge};
use utils::relative_time;
use super::issue_detail::IssueDetailView;
pub(super) mod detail;
use self::detail::IssueDetailView;
use super::status_list::{StatusCounts, filter_by_status};
/// Height of one issue row in the virtual list.
const ISSUE_ROW_HEIGHT: f32 = 73.;
/// Status filter of the issues list, chosen via the header's filter buttons.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IssueFilter {
/// Every issue, regardless of status.
All,
/// Issues whose resolved status is [`RepoStatus::Open`].
Open,
/// Issues whose resolved status is [`RepoStatus::Closed`].
Closed,
}
impl IssueFilter {
/// Whether an issue with `status` is included by this filter.
fn matches(self, status: RepoStatus) -> bool {
match self {
Self::All => true,
@@ -50,37 +47,37 @@ impl IssueFilter {
pub struct IssuesView {
focus_handle: FocusHandle,
/// Dock area the issue detail panel is opened in.
dock_area: WeakEntity<DockArea>,
/// Repo store holding the issues and their statuses.
store: Entity<RepoStore>,
/// Display name of the repository, for the panel title.
repo_name: SharedString,
/// Filter selected in the header filter buttons.
filter: IssueFilter,
/// Per-row heights of the virtual list.
item_sizes: Rc<Vec<Size<Pixels>>>,
/// The filtered issue count [`Self::item_sizes`] was built for.
issue_len: usize,
/// Indices into the store's `issues` matching [`Self::filter`].
visible_issues: Vec<usize>,
/// Header counts `(total, open, closed)`, rebuilt with [`Self::visible_issues`].
counts: (usize, usize, usize),
/// Store version and filter the cached rows/counts were built from.
cache_key: Option<(u64, IssueFilter)>,
/// Virtual list state of the issues list.
counts: StatusCounts,
// A filter change notifies even when the visible rows are unchanged,
// e.g. switching between two empty filters.
synced_filter: IssueFilter,
scroll_handle: VirtualListScrollHandle,
_subscription: Subscription,
}
impl IssuesView {
pub fn new(
dock_area: WeakEntity<DockArea>,
store: Entity<RepoStore>,
_window: &mut Window,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let repo_name = store.read(cx).name();
let subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild(cx);
});
cx.defer_in(window, |this, _window, cx| {
this.rebuild(cx);
});
Self {
focus_handle: cx.focus_handle(),
dock_area,
@@ -88,14 +85,46 @@ impl IssuesView {
repo_name,
filter: IssueFilter::Open,
item_sizes: Rc::new(Vec::new()),
issue_len: 0,
visible_issues: Vec::new(),
counts: (0, 0, 0),
cache_key: None,
counts: StatusCounts::default(),
synced_filter: IssueFilter::Open,
scroll_handle: VirtualListScrollHandle::new(),
_subscription: subscription,
}
}
fn rebuild(&mut self, cx: &mut Context<Self>) {
let filter = self.filter;
let (visible_issues, counts) = {
let store = self.store.read(cx);
filter_by_status(
&store.issues,
|issue| store.status_of(issue),
|status| filter.matches(status),
)
};
let filter_changed = self.synced_filter != filter;
let visible_issues_changed = self.visible_issues != visible_issues;
let counts_changed = self.counts != counts;
if !filter_changed && !visible_issues_changed && !counts_changed {
return;
}
self.item_sizes = Rc::new(vec![
size(px(0.), px(ISSUE_ROW_HEIGHT));
visible_issues.len()
]);
self.synced_filter = filter;
self.visible_issues = visible_issues;
self.counts = counts;
cx.notify();
}
/// Open the detail panel of `issue_id` in the dock area.
fn open_issue_detail(
&mut self,
@@ -176,8 +205,7 @@ impl IssuesView {
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
// Counts of the last list rebuild.
let (total, open, closed) = self.counts;
let counts = self.counts;
h_flex()
.px_4()
@@ -193,31 +221,31 @@ impl IssuesView {
.child(
SegmentButton::new("all", "All")
.icon(Icon::new(CustomIconName::GitIssueDone))
.count(total)
.count(counts.total)
.selected(self.filter == IssueFilter::All)
.on_click(cx.listener(|this, _event, _window, cx| {
this.filter = IssueFilter::All;
cx.notify();
this.rebuild(cx);
})),
)
.child(
SegmentButton::new("open", "Open")
.icon(Icon::new(CustomIconName::GitIssueOpen))
.count(open)
.count(counts.open)
.selected(self.filter == IssueFilter::Open)
.on_click(cx.listener(|this, _event, _window, cx| {
this.filter = IssueFilter::Open;
cx.notify();
this.rebuild(cx);
})),
)
.child(
SegmentButton::new("closed", "Closed")
.icon(Icon::new(CustomIconName::GitIssueClosed))
.count(closed)
.count(counts.closed)
.selected(self.filter == IssueFilter::Closed)
.on_click(cx.listener(|this, _event, _window, cx| {
this.filter = IssueFilter::Closed;
cx.notify();
this.rebuild(cx);
})),
),
)
@@ -234,7 +262,6 @@ impl IssuesView {
}
}
/// Open the new issue dialog, a title and a content input.
pub(super) fn open_new_issue_dialog(store: Entity<RepoStore>, window: &mut Window, cx: &mut App) {
let subject = cx.new(|cx| InputState::new(window, cx).placeholder("Issue title"));
let content = cx.new(|cx| TextareaState::new(window, cx).placeholder("Describe the issue..."));
@@ -322,41 +349,7 @@ impl Focusable for IssuesView {
impl Render for IssuesView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let filter = self.filter;
// Rows and counts are rebuilt only when the store refreshed or filter changed.
let version = self.store.read(cx).version();
if self.cache_key != Some((version, filter)) {
let store = self.store.read(cx);
let mut counts = (0usize, 0usize, 0usize);
self.visible_issues = store
.issues
.iter()
.enumerate()
.filter_map(|(ix, issue)| {
let status = store.status_of(issue);
counts.0 += 1;
match status {
RepoStatus::Open => counts.1 += 1,
RepoStatus::Closed => counts.2 += 1,
RepoStatus::Draft | RepoStatus::Applied => {}
}
filter.matches(status).then_some(ix)
})
.collect();
self.counts = counts;
self.cache_key = Some((version, filter));
}
let count = self.visible_issues.len();
// The virtual list's item count comes from `item_sizes`.
// Rebuild it whenever the filtered issue count changes.
if count != self.issue_len {
self.issue_len = count;
self.item_sizes = Rc::new(vec![size(px(0.), px(ISSUE_ROW_HEIGHT)); count]);
}
let sizes = self.item_sizes.clone();
let scroll_handle = self.scroll_handle.clone();
+12 -3
View File
@@ -1,9 +1,18 @@
mod commit_diff;
mod dialog_state;
mod repo_detail;
pub(crate) mod discussion;
mod inbox;
mod issues;
mod pull_requests;
mod repo;
mod repo_list;
mod send_patch;
pub(crate) mod sidebar;
mod status_list;
pub(crate) mod tree;
pub use repo_detail::RepoDetailView;
pub(crate) use repo_detail::open_repo_panel;
pub use inbox::InboxView;
pub use repo::RepoDetailView;
pub(crate) use repo::{RepoItem, open_repo_item, open_repo_panel};
pub use repo_list::RepoListView;
pub use sidebar::SidebarPanel;
@@ -6,7 +6,7 @@ use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
SharedString, Size, Task, WeakEntity, Window, div, px, relative, size,
SharedString, Size, Subscription, WeakEntity, Window, div, px, relative, size,
};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::clipboard::Clipboard;
@@ -20,54 +20,67 @@ use gpui_component::{
ActiveTheme, Sizable, StyledExt, VirtualListScrollHandle, WindowExt, h_flex, v_flex,
v_virtual_list,
};
use nostr::prelude::{Event, EventId, Kind, Nip34Tag};
use signed_core::{activity_subject, pull_request_patch};
use nostr::prelude::{Event, EventId, Kind, Url};
use signed_core::{
RepoAddr, activity_subject, branch_name_of, clone_urls_of, current_commit_of, latest_update,
merge_base_of, pull_request_patch,
};
use signed_git::{FileCommit, patch_commits, patch_diffs};
use signed_state::{Backend, GitStore, ProfileStore, RepoStore};
use signed_state::{Backend, ProfileStore, RepoStore, ensure_repo_mirror};
use signed_ui::{CountBadge, UserAvatar, placeholder, status_badge};
use utils::{relative_time, relative_time_secs};
use super::diff::{CommitDiffView, DiffPane};
use super::helpers::{comment_form, comments_section, pr_roots, sidebar_section};
use crate::views::commit_diff::{CommitDiffView, DiffPane};
use crate::views::discussion::{comment_form, comments_section, pr_roots, sidebar_section};
/// Height of one commit row in the commits tab's virtual list.
const ROW_HEIGHT: f32 = 37.;
/// Shown once the store's first pass is applied and the root PR is still absent.
const NOT_FOUND: &str = "Pull request not found";
/// A store refresh re-binds the panel, and reloads only when these change.
#[derive(Clone, PartialEq, Eq)]
struct PrBinding {
description: String,
patch: String,
tip: Option<String>,
base: Option<String>,
clone_urls: Vec<Url>,
addr: RepoAddr,
has_patch_link: bool,
}
/// Detail panel of a single pull request.
pub struct PullRequestDetailView {
focus_handle: FocusHandle,
/// Dock area where new panels, e.g. commit diffs, are added.
dock_area: WeakEntity<DockArea>,
/// Repo store holding the PR, its status and comments.
store: Entity<RepoStore>,
/// Event id of the root PR event, kind 1618.
/// Updates are revisions.
/// Event id of the root PR event, kind 1618. Updates are revisions.
pr_id: EventId,
/// Input state of the comment textarea.
comment_input: Entity<TextareaState>,
/// Display name of the repository, for panels opened from here.
repo_name: SharedString,
/// Local clone the PR's git changes come from.
worktree: Option<PathBuf>,
/// Root PR's content, shown as plain text.
description: SharedString,
/// Tip commit of the PR, the latest update's `c` tag or the root's.
/// Tip commit of the PR, from the latest update's `c` tag or the root.
current_commit: Option<SharedString>,
/// Commits of the patch series, in patch order, oldest first.
commits: Vec<FileCommit>,
/// The patch is being parsed on a background task.
loading: bool,
error: Option<SharedString>,
/// Active header tab, 0 = Discussion, 1 = Files, 2 = Commits.
/// Root PR inputs the in-flight diff load was started for.
bound: Option<PrBinding>,
/// Generation of the in-flight diff load. Stale results are discarded.
load_generation: u64,
/// 0 = Discussion, 1 = Files, 2 = Commits.
active_tab: usize,
/// Changed-files explorer and per-file diff, like the commit and compare views.
pane: Entity<DiffPane>,
/// Per-row heights of the commits tab's virtual list, built when the patch series loads.
commit_item_sizes: Rc<Vec<Size<Pixels>>>,
/// Virtual list state of the commits tab.
commit_scroll_handle: VirtualListScrollHandle,
/// In-flight tasks, finished tasks are pruned on every push.
tasks: Vec<Task<Result<(), anyhow::Error>>>,
/// The dock caches item panels, so without this observer a panel opened
/// before the store loaded would stay on its placeholder.
_subscription: Subscription,
}
impl PullRequestDetailView {
@@ -84,9 +97,11 @@ impl PullRequestDetailView {
let comment_input =
cx.new(|cx| TextareaState::new(window, cx).placeholder("Leave a comment..."));
let subscription = cx.observe(&store, |this, _store, cx| this.sync(cx));
// Defer loading until the window is ready, like the commit diff view.
cx.defer_in(window, |this, window, cx| {
this.load(window, cx);
cx.defer_in(window, |this, _window, cx| {
this.sync(cx);
});
Self {
@@ -102,67 +117,120 @@ impl PullRequestDetailView {
commits: Vec::new(),
loading: true,
error: None,
bound: None,
load_generation: 0,
active_tab: 0,
pane,
commit_item_sizes: Rc::new(Vec::new()),
commit_scroll_handle: VirtualListScrollHandle::new(),
tasks: Vec::new(),
_subscription: subscription,
}
}
/// Snapshot the PR events from the store.
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.loading = true;
self.error = None;
cx.notify();
/// Snapshot the root PR from the store and reload the diff when it changed.
///
/// Re-runs on construction and on every store refresh. Item panels are
/// cached by the dock, so this is the only way a panel opened before the
/// store's first pass learns about its PR.
fn sync(&mut self, cx: &mut Context<Self>) {
let loaded = self.store.read(cx).loaded;
let cache = GitStore::global(cx).cache().clone();
let (description, patch, current_commit, merge_base, clone_urls, addr, has_patch_link) = {
let binding = {
let store = self.store.read(cx);
let Some(root) = store
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
else {
self.loading = false;
self.error = Some("Pull request not found".into());
cx.notify();
return;
};
let update = latest_update(store.pull_requests.iter(), root);
let tip = update
.and_then(current_commit_of)
.or_else(|| current_commit_of(root));
let base = update
.and_then(merge_base_of)
.or_else(|| merge_base_of(root));
let clone_urls = clone_urls_of(root).or_else(|| {
store.addr().and_then(|addr| {
store
.announcement
.as_ref()
.map(|a| a.clone.iter().map(ToString::to_string).collect())
});
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
.map(|root| {
let update = latest_update(store.pull_requests.iter(), root);
(
root.content.clone(),
pull_request_patch(root, store.patches.iter()),
tip,
base,
clone_urls.unwrap_or_default(),
store.addr().clone(),
root.tags.event_ids().next().is_some(),
)
let tip = update
.and_then(current_commit_of)
.or_else(|| current_commit_of(root));
let base = update
.and_then(merge_base_of)
.or_else(|| merge_base_of(root));
let clone_urls = clone_urls_of(root)
.or_else(|| store.announcement.as_ref().map(|a| a.clone.clone()))
.unwrap_or_default();
PrBinding {
description: root.content.clone(),
patch: pull_request_patch(root, store.patches.iter()),
tip,
base,
clone_urls,
addr: addr.clone(),
has_patch_link: root.tags.event_ids().next().is_some(),
}
})
})
};
self.description = description.into();
let Some(binding) = binding else {
self.sync_missing(loaded, cx);
return;
};
let task = cx.spawn_in(window, async move |this, cx| {
if self.bound.as_ref() == Some(&binding) {
return;
}
self.bound = Some(binding.clone());
self.load_diff(binding, cx);
}
/// The store does not hold the root PR yet, or at all.
///
/// Loading until the first pass is applied, not found afterwards.
fn sync_missing(&mut self, loaded: bool, cx: &mut Context<Self>) {
self.bound = None;
if !loaded {
if !self.loading || self.error.is_some() {
self.loading = true;
self.error = None;
cx.notify();
}
return;
}
if self.error.as_deref() != Some(NOT_FOUND) {
self.loading = false;
self.error = Some(NOT_FOUND.into());
cx.notify();
}
}
/// Load the bound PR's changed files and commits.
///
/// Nostr-backed pull requests parse the patch series, git-backed ones fetch
/// the clone and diff the `merge-base..tip` range.
fn load_diff(&mut self, binding: PrBinding, cx: &mut Context<Self>) {
self.loading = true;
self.error = None;
self.description = binding.description.clone().into();
self.current_commit = binding.tip.clone().map(SharedString::from);
cx.notify();
self.load_generation = self.load_generation.wrapping_add(1);
let generation = self.load_generation;
let PrBinding {
patch,
tip,
base,
clone_urls,
addr,
has_patch_link,
..
} = binding;
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let nostr_diff = cx
.background_spawn({
let patch = patch.clone();
@@ -187,15 +255,14 @@ impl PullRequestDetailView {
let git = if use_nostr {
None
} else {
let cache = cache.clone();
let addr = addr.clone();
let clone_urls = clone_urls.clone();
let base = merge_base.clone();
let tip = current_commit.clone();
let base = base.clone();
let tip = tip.clone();
Some(
cx.background_spawn(async move {
let repo = cache.ensure_clone(&addr, &clone_urls)?;
let repo = ensure_repo_mirror(&addr, &clone_urls)?;
let workdir = repo
.workdir()
@@ -233,10 +300,14 @@ impl PullRequestDetailView {
None => (nostr_diff, nostr_commits, None),
};
this.update_in(cx, |this, _window, cx| {
this.update(cx, |this, cx| {
// A newer binding superseded this load.
if this.load_generation != generation {
return;
}
this.loading = false;
this.worktree = worktree;
this.current_commit = current_commit.map(SharedString::from);
this.commit_item_sizes = Rc::new(vec![size(px(0.), px(ROW_HEIGHT)); commits.len()]);
this.commits = commits;
@@ -255,8 +326,7 @@ impl PullRequestDetailView {
Ok(())
});
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
task.detach();
}
/// Open the diff of `commit_id` in the bottom dock of the area.
@@ -437,9 +507,6 @@ impl PullRequestDetailView {
.into_any_element()
}
/// Full-height Commits tab.
///
/// Every commit of the patch series, or a status message while loading or empty.
fn render_commits_tab(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return v_flex()
@@ -487,9 +554,6 @@ impl PullRequestDetailView {
.into_any_element()
}
/// One row of the commits tab, id, summary, author and time.
///
/// Clicking a row opens the commit's diff in the bottom dock.
fn render_commit_row(
&self,
ix: usize,
@@ -542,7 +606,6 @@ impl PullRequestDetailView {
.into_any_element()
}
/// Always-visible header with a status badge and title, like the issue panel.
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let current_commit = self.current_commit.clone();
let (title, status, branch, author) = {
@@ -644,7 +707,6 @@ impl PullRequestDetailView {
}
}
/// Open the update pull request dialog.
fn open_update_pull_request_dialog(
store: Entity<RepoStore>,
root: Event,
@@ -705,67 +767,6 @@ fn open_update_pull_request_dialog(
});
}
/// The `c` tag of a PR event, the commit the proposal points at.
fn current_commit_of(root: &Event) -> Option<String> {
root.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::CurrentCommit(commit)) => Some(commit.to_string()),
_ => None,
})
}
/// The `merge-base` tag of a PR event, as hex.
///
/// The most recent common ancestor with the target branch.
fn merge_base_of(event: &Event) -> Option<String> {
event
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::MergeBase(commit)) => Some(commit.to_string()),
_ => None,
})
}
/// The `clone` tag of a PR event.
///
/// URLs where the proposed branch can be fetched, or `None` if the PR has none.
fn clone_urls_of(event: &Event) -> Option<Vec<String>> {
event
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Clone(urls)) => Some(urls.iter().map(ToString::to_string).collect()),
_ => None,
})
}
/// The `branch-name` tag of a PR event, if any.
fn branch_name_of(event: &Event) -> Option<String> {
event
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::BranchName(name)) => Some(name),
_ => None,
})
}
/// The latest PR update, kind 1619, revising `root`.
fn latest_update<'a>(events: impl Iterator<Item = &'a Event>, root: &Event) -> Option<&'a Event> {
let root_hex = root.id.to_hex();
events
.filter(|e| e.kind == Kind::GitPullRequestUpdate)
.filter(|e| e.pubkey == root.pubkey)
.filter(|e| {
e.tags
.iter()
.any(|t| t.kind() == "E" && t.content() == Some(root_hex.as_str()))
})
.max_by_key(|e| e.created_at)
}
/// One-line commit metadata for the commits list.
///
/// Author and relative time, whichever is available.
@@ -823,121 +824,3 @@ impl Render for PullRequestDetailView {
})
}
}
#[cfg(test)]
mod tests {
use nostr::prelude::{Tag, *};
use super::*;
const COMMIT_HEX: &str = "1111111111111111111111111111111111111111";
const OTHER_ROOT_HEX: &str = "2222222222222222222222222222222222222222";
fn keys() -> Keys {
Keys::new(
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
.expect("valid secret key"),
)
}
/// Build a signed event with a controlled `created_at`.
fn signed(kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
EventBuilder::new(kind, "")
.tags(tags)
.custom_created_at(Timestamp::from(created_at))
.finalize(&keys())
.expect("signed event")
}
fn pr_root() -> Event {
signed(
Kind::GitPullRequest,
vec![
Tag::parse(["c", COMMIT_HEX]).expect("valid tag"),
Tag::parse(["branch-name", "feature/x"]).expect("valid tag"),
],
100,
)
}
#[test]
fn reads_current_commit_and_branch_name() {
let pr = pr_root();
assert_eq!(current_commit_of(&pr).as_deref(), Some(COMMIT_HEX));
assert_eq!(branch_name_of(&pr).as_deref(), Some("feature/x"));
}
#[test]
fn returns_none_without_pr_tags() {
let pr = signed(Kind::GitPullRequest, vec![], 100);
assert_eq!(current_commit_of(&pr), None);
assert_eq!(branch_name_of(&pr), None);
}
#[test]
fn latest_update_picks_newest_revision_of_the_root() {
let root = pr_root();
let root_hex = root.id.to_hex();
let revision = |created_at: u64| {
signed(
Kind::GitPullRequestUpdate,
vec![Tag::parse(["E", &root_hex]).expect("valid tag")],
created_at,
)
};
// An update revising a different PR must be ignored even though it is newer.
let unrelated = signed(
Kind::GitPullRequestUpdate,
vec![Tag::parse(["E", OTHER_ROOT_HEX]).expect("valid tag")],
999,
);
let events = [unrelated, revision(200), root.clone(), revision(300)];
let latest = latest_update(events.iter(), &root).expect("an update");
assert_eq!(latest.created_at.as_secs(), 300);
assert_eq!(latest.kind, Kind::GitPullRequestUpdate);
}
#[test]
fn latest_update_ignores_other_authors() {
let root = pr_root();
let root_hex = root.id.to_hex();
let other = Keys::new(
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000002")
.expect("valid secret key"),
);
let stranger = EventBuilder::new(Kind::GitPullRequestUpdate, "")
.tags([Tag::parse(["E", &root_hex]).expect("valid tag")])
.custom_created_at(Timestamp::from(999))
.finalize(&other)
.expect("signed event");
// The tip of a PR is only mutable by its author.
// A newer update from anyone else must not win.
assert!(latest_update([&stranger, &root].into_iter(), &root).is_none());
}
#[test]
fn latest_update_ignores_roots_without_revisions() {
let root = pr_root();
assert!(latest_update([&root].into_iter(), &root).is_none());
}
#[test]
fn commit_meta_combines_author_and_time() {
let commit = |author: &str, time: i64| FileCommit {
id: COMMIT_HEX.into(),
summary: "summary".into(),
description: None,
author: author.into(),
time,
};
assert_eq!(commit_meta(&commit("Alice", 0)), "Alice");
assert_eq!(commit_meta(&commit("", 0)), "");
assert!(!commit_meta(&commit("", 1_000_000)).is_empty());
assert!(!commit_meta(&commit("Alice", 1_000_000)).is_empty());
}
}
@@ -4,8 +4,8 @@ use assets::CustomIconName;
use dock::{BasePanel, DockArea, Panel, PanelEvent, add_center_panel, panel_handle};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
SharedString, Size, WeakEntity, Window, div, px, size,
AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels,
Render, SharedString, Size, Subscription, WeakEntity, Window, div, px, size,
};
use gpui_base::Button as BaseButton;
use gpui_component::alert::Alert;
@@ -19,31 +19,27 @@ use signed_state::{ProfileStore, RepoStore};
use signed_ui::{DropdownButton, SegmentButton, UserAvatar, placeholder, status_badge};
use utils::relative_time;
use super::RepoAction;
use super::new_pull_request::open_new_pull_panel;
use super::pull_request_detail::PullRequestDetailView;
pub(super) mod detail;
pub(super) mod new;
use self::detail::PullRequestDetailView;
use self::new::open_new_pull_panel;
use super::send_patch::open_send_patch_panel;
use super::status_list::{StatusCounts, filter_by_status};
use crate::views::repo::RepoAction;
/// Height of one pull request row in the virtual list.
const ROW_HEIGHT: f32 = 73.;
/// Status filter of the pull request list, chosen via the header's filter buttons.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PullRequestFilter {
/// Every pull request, regardless of status.
All,
/// Pull requests whose resolved status is [`RepoStatus::Open`].
Open,
/// Pull requests whose resolved status is [`RepoStatus::Closed`].
Closed,
/// Pull requests whose resolved status is [`RepoStatus::Draft`].
Draft,
/// Pull requests whose resolved status is [`RepoStatus::Applied`].
Merged,
}
impl PullRequestFilter {
/// Whether a pull request with `status` is included by this filter.
fn matches(self, status: RepoStatus) -> bool {
match self {
Self::All => true,
@@ -57,37 +53,38 @@ impl PullRequestFilter {
pub struct PullRequestsView {
focus_handle: FocusHandle,
/// Dock area the detail panels are added to.
dock_area: WeakEntity<DockArea>,
/// Repo store holding the pull requests and their statuses.
store: Entity<RepoStore>,
/// Display name of the repository, for the panel title.
repo_name: SharedString,
/// Filter selected in the header filter buttons.
filter: PullRequestFilter,
/// Per-row heights of the virtual list.
item_sizes: Rc<Vec<Size<Pixels>>>,
/// The filtered pull request count [`Self::item_sizes`] was built for.
pr_len: usize,
/// Indices into the store's `pull_requests` matching [`Self::filter`].
visible_prs: Vec<usize>,
/// Header counts `(total, open, closed, draft, merged)`.
counts: (usize, usize, usize, usize, usize),
/// Store version and filter the cached rows/counts were built from.
cache_key: Option<(u64, PullRequestFilter)>,
/// Virtual list state of the pull requests list.
counts: StatusCounts,
// A filter change notifies even when the visible rows are unchanged,
// e.g. switching between two empty filters.
synced_filter: PullRequestFilter,
scroll_handle: VirtualListScrollHandle,
_subscription: Subscription,
}
impl PullRequestsView {
pub fn new(
dock_area: WeakEntity<DockArea>,
store: Entity<RepoStore>,
_window: &mut Window,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let repo_name = store.read(cx).name();
let subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild(cx);
});
cx.defer_in(window, |this, _window, cx| {
this.rebuild(cx);
});
Self {
focus_handle: cx.focus_handle(),
dock_area,
@@ -95,15 +92,44 @@ impl PullRequestsView {
repo_name,
filter: PullRequestFilter::Open,
item_sizes: Rc::new(Vec::new()),
pr_len: 0,
visible_prs: Vec::new(),
counts: (0, 0, 0, 0, 0),
cache_key: None,
counts: StatusCounts::default(),
synced_filter: PullRequestFilter::Open,
scroll_handle: VirtualListScrollHandle::new(),
_subscription: subscription,
}
}
/// Open the detail panel of `pr_id` in the dock area.
fn rebuild(&mut self, cx: &mut Context<Self>) {
let filter = self.filter;
let (visible_prs, counts) = {
let store = self.store.read(cx);
let roots = store
.pull_requests
.iter()
.filter(|pr| pr.kind == Kind::GitPullRequest);
filter_by_status(
roots,
|pr| store.status_of(pr),
|status| filter.matches(status),
)
};
let filter_changed = self.synced_filter != filter;
if !filter_changed && self.visible_prs == visible_prs && self.counts == counts {
return;
}
self.synced_filter = filter;
self.item_sizes = Rc::new(vec![size(px(0.), px(ROW_HEIGHT)); visible_prs.len()]);
self.visible_prs = visible_prs;
self.counts = counts;
cx.notify();
}
fn open_pull_request_detail(
&mut self,
pr_id: EventId,
@@ -129,9 +155,6 @@ impl PullRequestsView {
});
}
/// Render one row of the pull request list.
///
/// `ix` is the row index, `pr_ix` the index in the store's `pull_requests`.
fn render_row(&self, ix: usize, pr_ix: usize, cx: &mut Context<Self>) -> AnyElement {
let pr = &self.store.read(cx).pull_requests[pr_ix];
let pr_id = pr.id;
@@ -196,8 +219,7 @@ impl PullRequestsView {
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
// Counts of the last list rebuild.
let (total, open, closed, draft, merged) = self.counts;
let counts = self.counts;
h_flex()
.px_4()
@@ -213,51 +235,51 @@ impl PullRequestsView {
.child(
SegmentButton::new("all", "All")
.icon(Icon::new(CustomIconName::GitPullRequest))
.count(total)
.count(counts.total)
.selected(self.filter == PullRequestFilter::All)
.on_click(cx.listener(|this, _event, _window, cx| {
this.filter = PullRequestFilter::All;
cx.notify();
this.rebuild(cx);
})),
)
.child(
SegmentButton::new("open", "Open")
.icon(Icon::new(CustomIconName::GitPullRequest))
.count(open)
.count(counts.open)
.selected(self.filter == PullRequestFilter::Open)
.on_click(cx.listener(|this, _event, _window, cx| {
this.filter = PullRequestFilter::Open;
cx.notify();
this.rebuild(cx);
})),
)
.child(
SegmentButton::new("closed", "Closed")
.icon(Icon::new(CustomIconName::GitPullRequestClosed))
.count(closed)
.count(counts.closed)
.selected(self.filter == PullRequestFilter::Closed)
.on_click(cx.listener(|this, _event, _window, cx| {
this.filter = PullRequestFilter::Closed;
cx.notify();
this.rebuild(cx);
})),
)
.child(
SegmentButton::new("draft", "Draft")
.icon(Icon::new(CustomIconName::GitPullRequestDraft))
.count(draft)
.count(counts.draft)
.selected(self.filter == PullRequestFilter::Draft)
.on_click(cx.listener(|this, _event, _window, cx| {
this.filter = PullRequestFilter::Draft;
cx.notify();
this.rebuild(cx);
})),
)
.child(
SegmentButton::new("merged", "Merged")
.icon(Icon::new(CustomIconName::GitPullRequestMerged))
.count(merged)
.count(counts.applied)
.selected(self.filter == PullRequestFilter::Merged)
.on_click(cx.listener(|this, _event, _window, cx| {
this.filter = PullRequestFilter::Merged;
cx.notify();
this.rebuild(cx);
})),
),
)
@@ -330,55 +352,11 @@ impl Focusable for PullRequestsView {
impl Render for PullRequestsView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let filter = self.filter;
// Rows and counts are rebuilt only when the store refreshed or filter changed.
let version = self.store.read(cx).version();
if self.cache_key != Some((version, filter)) {
let store = self.store.read(cx);
let mut counts = (0usize, 0usize, 0usize, 0usize, 0usize);
self.visible_prs = store
.pull_requests
.iter()
.enumerate()
.filter_map(|(ix, pr)| {
if pr.kind != Kind::GitPullRequest {
return None;
}
let status = store.status_of(pr);
counts.0 += 1;
match status {
RepoStatus::Open => counts.1 += 1,
RepoStatus::Closed => counts.2 += 1,
RepoStatus::Draft => counts.3 += 1,
RepoStatus::Applied => counts.4 += 1,
}
filter.matches(status).then_some(ix)
})
.collect();
self.counts = counts;
self.cache_key = Some((version, filter));
}
let count = self.visible_prs.len();
// The virtual list's item count comes from `item_sizes`.
// Rebuild it whenever the filtered pull request count changes.
if count != self.pr_len {
self.pr_len = count;
self.item_sizes = Rc::new(vec![size(px(0.), px(ROW_HEIGHT)); count]);
}
let sizes = self.item_sizes.clone();
let scroll_handle = self.scroll_handle.clone();
let view = cx.entity().clone();
// Non-fatal warnings and errors of the last action, like creating or updating a PR.
// Shown as dismissible banners above the list.
let (last_error, last_warning) = {
let store = self.store.read(cx);
(store.last_error.clone(), store.last_warning.clone())
@@ -7,7 +7,6 @@ use signed_core::Announcement;
use signed_state::ProfileStore;
use signed_ui::{UserAvatar, middle_truncate};
/// Open the About dialog showing every field of the announcement event.
pub(super) fn open_about_dialog(announcement: Announcement, window: &mut Window, cx: &mut App) {
window.open_dialog(cx, move |dialog, _window, cx| {
let announcement = announcement.clone();
@@ -21,7 +20,6 @@ pub(super) fn open_about_dialog(announcement: Announcement, window: &mut Window,
});
}
/// The announcement's fields as labeled rows.
fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
let mut rows: Vec<AnyElement> = Vec::new();
@@ -30,8 +28,9 @@ fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
text(
announcement
.name
.clone()
.unwrap_or_else(|| SharedString::from("")),
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from("-")),
),
cx,
));
@@ -41,8 +40,9 @@ fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
text(
announcement
.description
.clone()
.unwrap_or_else(|| SharedString::from("")),
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from("-")),
),
cx,
));
@@ -114,7 +114,6 @@ fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
v_flex().gap_3().w_full().children(rows).into_any_element()
}
/// One info row with a small muted label above the value.
fn row(label: &'static str, value: AnyElement, cx: &App) -> AnyElement {
v_flex()
.gap_1()
@@ -130,8 +129,12 @@ fn row(label: &'static str, value: AnyElement, cx: &App) -> AnyElement {
.into_any_element()
}
/// Plain text value, wrapping within the dialog.
fn text(value: SharedString) -> AnyElement {
fn text<T>(value: T) -> AnyElement
where
T: Into<SharedString>,
{
let value = value.into();
div()
.text_sm()
.w_full()
@@ -140,7 +143,6 @@ fn text(value: SharedString) -> AnyElement {
.into_any_element()
}
/// A mono-spaced value with a copy button, for hex identifiers.
fn copy_value(id: &'static str, value: String, cx: &App) -> AnyElement {
h_flex()
.gap_2()
@@ -157,10 +159,6 @@ fn copy_value(id: &'static str, value: String, cx: &App) -> AnyElement {
.into_any_element()
}
/// One row per maintainer with avatar and display name.
/// The display name falls back to a shortened npub.
///
/// A copy button copies the full pubkey.
fn maintainers(maintainers: &[PublicKey], cx: &App) -> AnyElement {
let profile_store = ProfileStore::global(cx);
v_flex()
@@ -190,9 +188,6 @@ fn maintainers(maintainers: &[PublicKey], cx: &App) -> AnyElement {
.into_any_element()
}
/// One row per item of a multi-value tag.
///
/// The value is truncated to a single line, with a copy button for the full value.
fn list(id: &'static str, items: impl IntoIterator<Item = String>, cx: &App) -> AnyElement {
v_flex()
.gap_2()
@@ -0,0 +1,78 @@
use std::sync::Arc;
use dock::{DockArea, add_center_panel, panel_handle};
use gpui::prelude::*;
use gpui::{App, Entity, WeakEntity, Window};
use gpui_base::dock::PanelView;
use nostr::prelude::EventId;
use signed_core::{Announcement, RepoAddr};
use signed_state::RepoStore;
use super::RepoDetailView;
use crate::views::issues::detail::IssueDetailView;
use crate::views::pull_requests::detail::PullRequestDetailView;
/// Open repository as a panel in the dock's center.
pub(crate) fn open_repo_panel(
dock_area: &WeakEntity<DockArea>,
addr: &RepoAddr,
hint: Option<&Announcement>,
window: &mut Window,
cx: &mut App,
) -> Entity<RepoDetailView> {
let detail = cx
.new(|cx| RepoDetailView::new(dock_area.clone(), addr.clone(), hint.cloned(), window, cx));
if let Some(dock_area) = dock_area.upgrade() {
dock_area.update(cx, |dock_area, cx| {
add_center_panel(dock_area, panel_handle(detail.clone()), window, cx);
});
}
detail
}
/// The nostr store of `addr`'s repository, without opening a repository panel.
fn repo_store(addr: &RepoAddr, hint: Option<&Announcement>, cx: &mut App) -> Entity<RepoStore> {
cx.new(|cx| RepoStore::new(addr.clone(), hint.cloned(), cx))
}
/// An item of a repository to open from outside its detail panel.
pub(crate) enum RepoItem {
Issue(EventId),
PullRequest(EventId),
Patch,
}
/// The repository store is built here.
pub(crate) fn open_repo_item(
dock_area: &WeakEntity<DockArea>,
addr: &RepoAddr,
hint: Option<&Announcement>,
item: RepoItem,
window: &mut Window,
cx: &mut App,
) {
let panel: Arc<dyn PanelView> =
match item {
RepoItem::Issue(issue_id) => {
let store = repo_store(addr, hint, cx);
panel_handle(cx.new(|cx| IssueDetailView::new(store, issue_id, window, cx)))
}
RepoItem::PullRequest(pr_id) => {
let store = repo_store(addr, hint, cx);
panel_handle(cx.new(|cx| {
PullRequestDetailView::new(dock_area.clone(), store, pr_id, window, cx)
}))
}
RepoItem::Patch => return,
};
let Some(dock_area) = dock_area.upgrade() else {
return;
};
dock_area.update(cx, |dock_area, cx| {
add_center_panel(dock_area, panel, window, cx);
});
}
@@ -0,0 +1,46 @@
use std::collections::HashSet;
use std::path::PathBuf;
use signed_state::CheckoutStatus;
#[derive(Default)]
pub(super) struct Banners {
dismissed: HashSet<(PathBuf, String)>,
ready_requested: bool,
/// Re-requested only when the announced HEAD or the base default changes.
ready_head: Option<String>,
ready_statuses: Vec<CheckoutStatus>,
push_statuses: Vec<CheckoutStatus>,
}
impl Banners {
pub(super) fn dismissal(&self, status: &CheckoutStatus) -> bool {
self.dismissed
.contains(&(status.path.clone(), status.branch.clone()))
}
pub(super) fn dismiss(&mut self, status: &CheckoutStatus) {
self.dismissed
.insert((status.path.clone(), status.branch.clone()));
}
pub(super) fn ready_requested_at(&self) -> (bool, &Option<String>) {
(self.ready_requested, &self.ready_head)
}
pub(super) fn mark_ready_requested(&mut self, head: Option<String>) {
self.ready_requested = true;
self.ready_head = head;
}
pub(super) fn set_statuses(
&mut self,
ready: Vec<CheckoutStatus>,
push: Vec<CheckoutStatus>,
) -> bool {
let changed = ready != self.ready_statuses || push != self.push_statuses;
self.ready_statuses = ready;
self.push_statuses = push;
changed
}
}
+737
View File
@@ -0,0 +1,737 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Component, Path, PathBuf};
use anyhow::Error;
use gpui::prelude::*;
use gpui::{AnyElement, Context, Entity, Render, SharedString, Task, WeakEntity, Window, div, px};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::input::{Editor, EditorState};
use gpui_component::list::ListItem;
use gpui_component::spinner::Spinner;
use gpui_component::text::{TextView, TextViewState};
use gpui_component::tree::{TreeEntry, TreeState, tree};
use gpui_component::{ActiveTheme, Sizable, StyledExt, h_flex, v_flex};
use signed_git::{FileCommit, WorktreeSnapshot};
use signed_ui::{placeholder, tree_row};
use crate::views::tree::{TreeItemSeed, tree_items};
const TREE_WIDTH: f32 = 240.;
const MAX_PREVIEW_BYTES: usize = 1024 * 1024;
const MAX_PREVIEWED_FILES: usize = 32;
const MAX_PREVIEW_CACHE_BYTES: usize = 8 * 1024 * 1024;
enum FileContent {
Text(String),
Binary,
TooLarge,
Failed(String),
}
struct MarkdownView {
/// `None` means the repository README.
path: Option<SharedString>,
state: Entity<TextViewState>,
/// Hash of the source, so the same document is not re-parsed on a refresh.
source_hash: u64,
}
struct CodeView {
/// Source path, relative to the worktree root.
path: SharedString,
state: Entity<EditorState>,
/// Hash of the source, so the same document is not re-parsed on a refresh.
source_hash: u64,
}
pub(super) struct RepoFilesView {
tree_state: Entity<TreeState>,
worktree: Option<PathBuf>,
worktree_paths: Vec<String>,
md: Option<MarkdownView>,
code: Option<CodeView>,
readme_name: Option<SharedString>,
selected_file: Option<SharedString>,
files: HashMap<String, FileContent>,
file_order: VecDeque<String>,
preview_bytes: usize,
loading_files: HashSet<String>,
commits: HashMap<String, FileCommit>,
pending_commits: Vec<String>,
loading_commits: bool,
tasks: Vec<Task<Result<(), Error>>>,
}
impl RepoFilesView {
pub(super) fn new(cx: &mut Context<Self>) -> Self {
Self {
tree_state: cx.new(|cx| TreeState::new(cx)),
worktree: None,
worktree_paths: Vec::new(),
md: None,
code: None,
readme_name: None,
selected_file: None,
files: HashMap::new(),
file_order: VecDeque::new(),
preview_bytes: 0,
loading_files: HashSet::new(),
commits: HashMap::new(),
pending_commits: Vec::new(),
loading_commits: false,
tasks: Vec::new(),
}
}
pub(super) fn set_worktree(&mut self, path: PathBuf) {
self.worktree = Some(path);
}
pub(super) fn apply_entries(
&mut self,
tree: Vec<TreeItemSeed>,
paths: Vec<String>,
cx: &mut Context<Self>,
) {
self.worktree_paths = paths;
self.tree_state.update(cx, |state, cx| {
state.set_items(tree_items(tree, false), cx);
});
}
/// Point the README pane at `path`/`bytes`, or clear it when absent.
///
/// Returns whether the pane changed.
pub(super) fn set_readme(
&mut self,
path: Option<PathBuf>,
bytes: Option<Vec<u8>>,
cx: &mut Context<Self>,
) -> bool {
let Some((path, bytes)) = path.zip(bytes) else {
let changed = self.readme_name.is_some() || self.md.is_some();
self.readme_name = None;
self.md = None;
return changed;
};
let name: SharedString = path.to_string_lossy().into();
let mut changed = self.readme_name.as_ref() != Some(&name);
self.readme_name = Some(name);
self.load_commit(&path.to_string_lossy(), cx);
if let Ok(text) = String::from_utf8(bytes) {
changed |= self.set_markdown(None, &text, cx);
}
changed
}
/// Drop every cached preview and the README, e.g. on a branch switch.
pub(super) fn clear_previews(&mut self) {
self.selected_file = None;
self.files.clear();
self.file_order.clear();
self.preview_bytes = 0;
self.loading_files.clear();
self.commits.clear();
self.pending_commits.clear();
self.loading_commits = false;
self.md = None;
self.code = None;
self.readme_name = None;
}
/// Refresh after the mirror caught up with the remote.
///
/// Unlike a branch switch this keeps the selection and previews: it rebuilds
/// the tree, drops previews of files the refresh removed and re-renders the
/// README when it is on screen.
///
/// Returns whether the tree, a preview or the README changed.
pub(super) fn catch_up(
&mut self,
snapshot: &WorktreeSnapshot,
tree: Vec<TreeItemSeed>,
paths: Vec<String>,
cx: &mut Context<Self>,
) -> bool {
let mut changed = false;
if paths != self.worktree_paths {
self.apply_entries(tree, paths, cx);
changed = true;
}
let present: HashSet<String> = snapshot
.entries
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
let mut previewed: Vec<String> = Vec::new();
previewed.extend(self.files.keys().cloned());
previewed.extend(self.selected_file.clone().map(|path| path.to_string()));
if let Some(path) = self.md.as_ref().and_then(|md| md.path.clone()) {
previewed.push(path.to_string());
}
if let Some(path) = self.code.as_ref().map(|code| code.path.clone()) {
previewed.push(path.to_string());
}
previewed.sort();
previewed.dedup();
for path in previewed {
if !present.contains(&path) {
self.drop_preview_of(&path);
changed = true;
}
}
if self.selected_file.is_none() {
changed |= self.set_readme(snapshot.readme_path.clone(), snapshot.readme.clone(), cx);
}
changed
}
fn pane_title(&self) -> SharedString {
self.selected_file
.clone()
.or_else(|| self.readme_name.clone())
.unwrap_or_else(|| "Overview".into())
}
fn render_tree_item(
ix: usize,
entry: &TreeEntry,
selected: bool,
view: &WeakEntity<Self>,
) -> ListItem {
let view = view.clone();
let id = entry.item().id.clone();
tree_row(ix, entry, selected, move |window, cx| {
if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| this.open_file(&id, window, cx));
}
})
}
fn render_tree_column(
tree_state: Entity<TreeState>,
view: WeakEntity<Self>,
cx: &mut Context<Self>,
) -> impl IntoElement {
v_flex()
.h_full()
.w(px(TREE_WIDTH))
.p_2()
.flex_none()
.border_r_1()
.border_color(cx.theme().border)
.child(div().flex_1().min_h_0().child(tree(
&tree_state,
move |ix, entry, selected, _window, _cx| {
Self::render_tree_item(ix, entry, selected, &view)
},
)))
}
fn render_content_column(
&self,
pane_title: SharedString,
cx: &mut Context<Self>,
) -> impl IntoElement {
let body: AnyElement = if let Some(path) = self.selected_file.clone() {
match self.files.get(path.as_ref()) {
Some(FileContent::Text(_)) => {
if is_markdown_path(path.as_ref()) {
self.markdown_element(Some(path.as_ref()), cx)
} else {
self.code_element(path.as_ref(), cx)
}
}
Some(FileContent::Binary) => placeholder("Binary file - preview not supported", cx),
Some(FileContent::TooLarge) => placeholder("File is too large to preview", cx),
Some(FileContent::Failed(message)) => placeholder(message, cx),
None => preview_spinner(),
}
} else if self.readme_name.is_some() {
self.markdown_element(None, cx)
} else {
placeholder("No README found", cx)
};
// Latest commit for the current pane, the selected file or the README.
let commit = match &self.selected_file {
Some(path) => self.commits.get(path.as_ref()),
None => self
.readme_name
.as_ref()
.and_then(|name| self.commits.get(name.as_ref())),
};
v_flex()
.flex_1()
.min_w_0()
.h_full()
.child(
h_flex()
.px_3()
.h_9()
.gap_2()
.bg(cx.theme().muted)
.border_b(px(1.))
.border_color(cx.theme().border)
.text_color(cx.theme().muted_foreground)
.child(
div()
.text_xs()
.font_semibold()
.text_ellipsis()
.whitespace_nowrap()
.child(pane_title),
)
.when_some(commit, |this, commit| {
this.child(
h_flex()
.flex_1()
.gap_1()
.child(
Button::new("commit")
.xsmall()
.text()
.label(commit.id.clone()),
)
.child(
div()
.max_w(px(250.))
.text_xs()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
}),
)
.child(div().id("repo-content").flex_1().min_h_0().child(body))
}
fn set_markdown(
&mut self,
path: Option<SharedString>,
text: &str,
cx: &mut Context<Self>,
) -> bool {
let hash = source_hash(text);
if let Some(md) = &self.md
&& md.path == path
&& md.source_hash == hash
{
return false;
}
let state = cx.new(|cx| TextViewState::markdown("", cx));
state.update(cx, |state, cx| state.push_str(text, cx));
self.md = Some(MarkdownView {
path,
state,
source_hash: hash,
});
true
}
fn markdown_element(&self, path: Option<&str>, _cx: &mut Context<Self>) -> AnyElement {
let Some(md) = &self.md else {
return preview_spinner();
};
let ready = match path {
Some(path) => md.path.as_deref() == Some(path),
None => md.path.is_none(),
};
if !ready {
return preview_spinner();
}
TextView::new(&md.state)
.selectable(true)
.scrollable(true)
.p_4()
.text_sm()
.into_any_element()
}
fn set_code(
&mut self,
path: SharedString,
text: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let hash = source_hash(text);
if let Some(code) = &self.code
&& code.path == path
&& code.source_hash == hash
{
return;
}
let language = code_language(path.as_ref()).unwrap_or("text");
let state = cx.new(|cx| {
EditorState::new(window, cx)
.language(language)
.default_value(text)
.line_number(true)
.folding(true)
});
self.code = Some(CodeView {
path,
state,
source_hash: hash,
});
}
fn code_element(&self, path: &str, _cx: &mut Context<Self>) -> AnyElement {
let Some(code) = &self.code else {
return preview_spinner();
};
if code.path.as_ref() != path {
return preview_spinner();
}
Editor::new(&code.state)
.readonly(true)
.bordered(false)
.rounded_none()
.h_full()
.text_sm()
.into_any_element()
}
fn open_file(&mut self, path: &str, window: &mut Window, cx: &mut Context<Self>) {
self.selected_file = Some(path.into());
if self.files.contains_key(path) {
if let Some(FileContent::Text(text)) = self.files.get(path) {
let text = text.clone();
if is_markdown_path(path) {
if self.md.as_ref().map(|md| md.path.as_deref()) != Some(Some(path)) {
self.set_markdown(Some(path.into()), &text, cx);
}
} else if self.code.as_ref().map(|code| code.path.as_str()) != Some(path) {
self.set_code(path.into(), &text, window, cx);
}
}
cx.notify();
return;
}
if self.loading_files.contains(path) {
cx.notify();
return;
}
let rel = Path::new(path);
let unsafe_path = rel.is_absolute()
|| rel.components().any(|c| {
matches!(
c,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
});
let Some(worktree) = self.worktree.clone() else {
return;
};
if unsafe_path {
return;
}
self.loading_files.insert(path.to_string());
let path = path.to_string();
self.load_commit(&path, cx);
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
let path_for_read = path.clone();
let content = cx
.background_spawn(async move {
let full = worktree.join(&path_for_read);
let metadata = match std::fs::metadata(&full) {
Ok(metadata) => metadata,
Err(error) => return Err(anyhow::anyhow!("{}", error)),
};
if metadata.len() > MAX_PREVIEW_BYTES as u64 {
return Ok(FileContent::TooLarge);
}
let bytes = match std::fs::read(&full) {
Ok(bytes) => bytes,
Err(error) => return Err(anyhow::anyhow!("{}", error)),
};
match String::from_utf8(bytes) {
Ok(text) => Ok(FileContent::Text(text)),
Err(_) => Ok(FileContent::Binary),
}
})
.await;
this.update_in(cx, |this, window, cx| {
this.loading_files.remove(&path);
match content {
Ok(kind) => {
if let FileContent::Text(text) = &kind {
if is_markdown_path(&path) {
let same = this.md.as_ref().map(|md| md.path.as_deref())
== Some(Some(path.as_str()));
if !same {
this.set_markdown(Some(path.clone().into()), text, cx);
}
} else {
let same = this.code.as_ref().map(|code| code.path.as_str())
== Some(path.as_str());
if !same {
this.set_code(path.clone().into(), text, window, cx);
}
}
this.preview_bytes += text.len();
}
this.files.insert(path.clone(), kind);
this.file_order.push_back(path);
this.evict_previews();
}
Err(error) => {
this.files
.insert(path, FileContent::Failed(error.to_string()));
}
}
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
fn drop_preview_of(&mut self, path: &str) {
if let Some(FileContent::Text(text)) = self.files.remove(path) {
self.preview_bytes -= text.len();
}
self.commits.remove(path);
if self.selected_file.as_deref() == Some(path) {
self.selected_file = None;
}
if self.md.as_ref().and_then(|md| md.path.as_deref()) == Some(path) {
self.md = None;
}
if self.code.as_ref().map(|code| code.path.as_ref()) == Some(path) {
self.code = None;
}
}
fn evict_previews(&mut self) {
while (self.files.len() > MAX_PREVIEWED_FILES
|| self.preview_bytes > MAX_PREVIEW_CACHE_BYTES)
&& self.file_order.len() > 1
{
let path = self.file_order.pop_front().expect("non-empty");
if Some(path.as_str()) == self.selected_file.as_deref() {
self.file_order.push_back(path);
continue;
}
if let Some(FileContent::Text(text)) = self.files.remove(&path) {
self.preview_bytes -= text.len();
}
if self.md.as_ref().map(|md| md.path.as_deref()) == Some(Some(path.as_str())) {
self.md = None;
}
if self
.code
.as_ref()
.is_some_and(|code| code.path.as_ref() == path.as_str())
{
self.code = None;
}
self.commits.remove(&path);
}
}
fn load_commit(&mut self, path: &str, cx: &mut Context<Self>) {
if self.commits.contains_key(path) || self.pending_commits.iter().any(|p| p == path) {
return;
}
self.pending_commits.push(path.to_string());
if !self.loading_commits {
self.load_commits(cx);
}
}
fn load_commits(&mut self, cx: &mut Context<Self>) {
if self.pending_commits.is_empty() || self.loading_commits {
return;
}
let Some(worktree) = self.worktree.clone() else {
self.pending_commits.clear();
return;
};
self.loading_commits = true;
let paths = std::mem::take(&mut self.pending_commits);
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let rels: Vec<PathBuf> = paths.iter().map(PathBuf::from).collect();
let result = cx
.background_spawn(
async move { signed_git::worktree_last_commits(&worktree, &rels) },
)
.await;
this.update(cx, |this, cx| {
this.loading_commits = false;
if let Ok(found) = result {
for (path, commit) in found {
this.commits
.insert(path.to_string_lossy().into_owned(), commit);
}
}
if !this.pending_commits.is_empty() {
this.load_commits(cx);
}
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
}
impl Render for RepoFilesView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let tree_state = self.tree_state.clone();
let view = cx.entity().downgrade();
let pane_title = self.pane_title();
h_flex()
.flex_1()
.w_full()
.overflow_hidden()
.child(Self::render_tree_column(tree_state, view, cx))
.child(self.render_content_column(pane_title, cx))
}
}
fn source_hash(text: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut hasher);
hasher.finish()
}
fn preview_spinner() -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new().small())
.into_any_element()
}
/// The markdown fence language for a file path, or `None` for plain text.
fn code_language(path: &str) -> Option<&'static str> {
let name = Path::new(path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or_default();
// Some common files are recognized by name rather than extension.
match name {
"Makefile" | "makefile" => return Some("make"),
"CMakeLists.txt" => return Some("cmake"),
_ => {}
}
let ext = Path::new(path).extension()?.to_str()?.to_ascii_lowercase();
Some(match ext.as_str() {
"rs" => "rust",
"toml" => "toml",
"json" | "jsonc" => "json",
"py" => "python",
"js" | "mjs" | "cjs" => "javascript",
"ts" | "mts" | "cts" => "typescript",
"tsx" | "jsx" => "tsx",
"go" => "go",
"c" | "h" => "c",
"cc" | "cpp" | "cxx" | "hh" | "hpp" | "hxx" => "cpp",
"cs" => "csharp",
"java" => "java",
"kt" | "kts" | "ktm" => "kotlin",
"swift" => "swift",
"php" | "phtml" => "php",
"rb" => "ruby",
"sh" | "bash" | "zsh" => "bash",
"yml" | "yaml" => "yaml",
"css" | "scss" | "sass" => "css",
"html" | "htm" => "html",
"lua" => "lua",
"sql" => "sql",
"proto" | "protobuf" => "proto",
"cmake" => "cmake",
"zig" => "zig",
"ex" | "exs" => "elixir",
"graphql" | "gql" => "graphql",
"diff" | "patch" => "diff",
"svelte" => "svelte",
"astro" => "astro",
"scala" => "scala",
_ => return None,
})
}
/// Whether a file path has a markdown extension.
fn is_markdown_path(path: &str) -> bool {
Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| {
matches!(
ext.to_ascii_lowercase().as_str(),
"md" | "markdown" | "mdown" | "mkdn"
)
})
}
+201
View File
@@ -0,0 +1,201 @@
use std::path::PathBuf;
use std::rc::Rc;
use anyhow::Error;
use dock::{DockArea, add_center_panel, panel_handle};
use gpui::prelude::*;
use gpui::{Context, Entity, Pixels, Render, Size, Task, WeakEntity, Window, div, px, size};
use gpui_component::scroll::Scrollbar;
use gpui_component::spinner::Spinner;
use gpui_component::{ActiveTheme, Sizable, VirtualListScrollHandle, v_flex, v_virtual_list};
use signed_git::CommitList;
use signed_state::RepoStore;
use signed_ui::placeholder;
use super::repo_display_name;
use crate::views::commit_diff::{COMMIT_ROW_HEIGHT, CommitDiffView, commit_row};
pub(super) struct RepoHistoryView {
store: Entity<RepoStore>,
dock_area: WeakEntity<DockArea>,
worktree: Option<PathBuf>,
all_commits: Option<CommitList>,
loading_all_commits: bool,
scroll_handle: VirtualListScrollHandle,
item_sizes: Rc<Vec<Size<Pixels>>>,
tasks: Vec<Task<Result<(), Error>>>,
}
impl RepoHistoryView {
pub(super) fn new(store: Entity<RepoStore>, dock_area: WeakEntity<DockArea>) -> Self {
Self {
store,
dock_area,
worktree: None,
all_commits: None,
loading_all_commits: false,
scroll_handle: VirtualListScrollHandle::new(),
item_sizes: Rc::new(Vec::new()),
tasks: Vec::new(),
}
}
pub(super) fn set_worktree(&mut self, path: Option<PathBuf>) {
self.worktree = path;
}
/// Number of commits reachable from HEAD, for the Commits tab badge.
pub(super) fn commit_count(&self) -> Option<usize> {
self.all_commits.as_ref().map(|list| list.total)
}
/// Drop the current list and walk HEAD again.
pub(super) fn reload(&mut self, cx: &mut Context<Self>) {
self.all_commits = None;
self.loading_all_commits = false;
self.load(cx);
}
fn load(&mut self, cx: &mut Context<Self>) {
if self.loading_all_commits || self.all_commits.is_some() {
return;
}
let Some(worktree) = self.worktree.clone() else {
return;
};
self.loading_all_commits = true;
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn(async move { signed_git::worktree_all_commits(&worktree) })
.await;
this.update(cx, |this, cx| {
if let Ok(list) = result {
let count = list.commits.len();
this.item_sizes = Rc::new(vec![size(px(0.), px(COMMIT_ROW_HEIGHT)); count]);
this.all_commits = Some(list);
}
this.loading_all_commits = false;
cx.notify();
})?;
Ok(())
});
self.tasks.push(task);
}
pub(super) fn open_commit_diff(
&mut self,
commit_id: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(worktree) = self.worktree.clone() else {
return;
};
let Some(dock_area) = self.dock_area.upgrade() else {
return;
};
// Same display name as the repo detail panel's title.
let repo_name = repo_display_name(self.store.read(cx));
let panel =
cx.new(|cx| CommitDiffView::new(worktree, repo_name, commit_id.into(), window, cx));
dock_area.update(cx, |dock_area, cx| {
add_center_panel(dock_area, panel_handle(panel), window, cx);
});
}
}
impl Render for RepoHistoryView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(list) = self.all_commits.as_ref() else {
return if self.loading_all_commits {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new().small())
.into_any_element()
} else {
placeholder("Failed to load commits", cx)
};
};
if list.commits.is_empty() {
return placeholder("No commits found", cx);
}
let view = cx.entity().clone();
let sizes = self.item_sizes.clone();
let scroll_handle = self.scroll_handle.clone();
let shown = list.commits.len();
let total = list.total;
v_flex()
.relative()
.flex_1()
.w_full()
.min_h_0()
.child(
v_virtual_list(view, "commits", sizes, move |this, range, _window, cx| {
let view = cx.entity().downgrade();
let commits = this
.all_commits
.as_ref()
.map(|list| list.commits.as_slice())
.unwrap_or(&[]);
range
.map(|ix| {
let id = commits[ix].id.clone();
let view = view.clone();
commit_row(
ix,
&commits[ix],
move |window, cx| {
if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx)
});
}
},
cx,
)
})
.collect()
})
.track_scroll(&scroll_handle)
.size_full(),
)
.when(shown < total, |this| {
this.child(
div()
.py_2()
.w_full()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(format!("Showing {shown} of {total} commits")),
)
})
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(&self.scroll_handle)),
)
.into_any_element()
}
}
@@ -19,10 +19,8 @@ use crate::views::sidebar::grasp_servers::{
GraspServersState, grasp_servers_field, load_user_grasp_servers,
};
/// Shared state for the Init dialog, so async results can be rendered.
pub type InitRepoState = DialogProgress;
/// Open the Init dialog for the local repository at `local_path`.
pub fn open(
local_path: PathBuf,
view: WeakEntity<RepoDetailView>,
@@ -51,7 +49,6 @@ pub fn open(
.placeholder("Short description")
});
// Load the user's grasp servers.
load_user_grasp_servers(grasp_state.clone(), window, cx);
window.open_dialog(cx, move |dialog, _window, _cx| {
@@ -146,9 +143,6 @@ pub fn open(
});
}
/// Run the init flow.
///
/// Closes the dialog and switches the repository into NIP-34 mode on success.
fn init_repository(
local_path: PathBuf,
inputs: (Entity<InputState>, Entity<TextareaState>),
File diff suppressed because it is too large Load Diff
+115
View File
@@ -0,0 +1,115 @@
use gpui::prelude::*;
use gpui::{App, Entity, SharedString, Window};
use gpui_component::combobox::ComboboxState;
use gpui_component::searchable_list::SearchableVec;
pub(super) struct RefSwitcher {
pub(super) branch_select: Entity<ComboboxState<SearchableVec<SharedString>>>,
pub(super) tag_select: Entity<ComboboxState<SearchableVec<SharedString>>>,
ref_branches: Vec<SharedString>,
ref_tags: Vec<SharedString>,
pub(super) switching_ref: bool,
}
impl RefSwitcher {
pub(super) fn new(window: &mut Window, cx: &mut App) -> Self {
let branch_select = cx.new(|cx| {
ComboboxState::new(
SearchableVec::new(Vec::<SharedString>::new()),
Vec::new(),
window,
cx,
)
.searchable(true)
});
let tag_select = cx.new(|cx| {
ComboboxState::new(
SearchableVec::new(Vec::<SharedString>::new()),
Vec::new(),
window,
cx,
)
.searchable(true)
});
Self {
branch_select,
tag_select,
ref_branches: Vec::new(),
ref_tags: Vec::new(),
switching_ref: false,
}
}
pub(super) fn set_branches(
&mut self,
branches: Vec<SharedString>,
selected: Option<SharedString>,
window: &mut Window,
cx: &mut App,
) -> bool {
sync_selector(
&self.branch_select,
&mut self.ref_branches,
branches,
selected,
window,
cx,
)
}
pub(super) fn set_tags(
&mut self,
tags: Vec<SharedString>,
window: &mut Window,
cx: &mut App,
) -> bool {
sync_selector(&self.tag_select, &mut self.ref_tags, tags, None, window, cx)
}
pub(super) fn restore_selection(
&self,
select: &Entity<ComboboxState<SearchableVec<SharedString>>>,
previous: &Option<SharedString>,
window: &mut Window,
cx: &mut App,
) {
select.update(cx, |state, cx| match previous {
Some(value) => state.set_selected_values(std::slice::from_ref(value), window, cx),
None => state.clear_selection(cx),
});
}
}
fn sync_selector(
select: &Entity<ComboboxState<SearchableVec<SharedString>>>,
cached: &mut Vec<SharedString>,
items: Vec<SharedString>,
selected: Option<SharedString>,
window: &mut Window,
cx: &mut App,
) -> bool {
let items_changed = *cached != items;
let selection_changed = selected
.as_ref()
.is_some_and(|value| select.read(cx).selected_value().as_ref() != Some(value));
if !items_changed && !selection_changed {
return false;
}
select.update(cx, |state, cx| {
if items_changed {
state.set_items(SearchableVec::from(items.clone()), window, cx);
}
if let Some(value) = selected
&& (items_changed || selection_changed)
{
state.set_selected_values(std::slice::from_ref(&value), window, cx);
}
});
*cached = items;
true
}
@@ -1,288 +0,0 @@
use gpui::prelude::*;
use gpui::{AnyElement, Context, Entity, SharedString, WeakEntity, Window, div, px};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::input::{Editor, EditorState};
use gpui_component::list::ListItem;
use gpui_component::spinner::Spinner;
use gpui_component::text::{TextView, TextViewState};
use gpui_component::tree::{TreeEntry, TreeState, tree};
use gpui_component::{ActiveTheme, Sizable, StyledExt, h_flex, v_flex};
use signed_ui::{placeholder, tree_row};
use super::RepoDetailView;
use super::helpers::{code_language, is_markdown_path};
/// Width of the file explorer column.
const TREE_WIDTH: f32 = 240.;
/// Files larger than this are not previewed.
pub(super) const MAX_PREVIEW_BYTES: usize = 1024 * 1024;
/// Preview cache caps, a file count and a text byte count.
///
/// The oldest previews are evicted beyond the caps.
pub(super) const MAX_PREVIEWED_FILES: usize = 32;
pub(super) const MAX_PREVIEW_CACHE_BYTES: usize = 8 * 1024 * 1024;
/// Preview state of a browsed file.
pub(super) enum FileContent {
/// Decodable text content.
Text(String),
/// Not valid UTF-8.
Binary,
/// Bigger than [`MAX_PREVIEW_BYTES`].
TooLarge,
/// Reading failed.
Failed(String),
}
/// A markdown document loaded into a persistent [`TextViewState`].
pub(super) struct MarkdownView {
/// Source path, `None` means the repository README.
pub(super) path: Option<SharedString>,
pub(super) state: Entity<TextViewState>,
}
/// A code file loaded into a persistent [`InputState`].
pub(super) struct CodeView {
/// Source path, relative to the worktree root.
pub(super) path: SharedString,
pub(super) state: Entity<EditorState>,
}
/// Spinner shown while a document is being loaded/parsed.
fn preview_spinner() -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new().small())
.into_any_element()
}
impl RepoDetailView {
/// One row of the file tree with icon and name, indented by depth.
fn render_tree_item(
ix: usize,
entry: &TreeEntry,
selected: bool,
view: &WeakEntity<Self>,
) -> ListItem {
let view = view.clone();
let id = entry.item().id.clone();
tree_row(ix, entry, selected, move |window, cx| {
if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| this.open_file(&id, window, cx));
}
})
}
/// Left column showing the file tree.
pub(super) fn render_tree_column(
tree_state: Entity<TreeState>,
view: WeakEntity<Self>,
cx: &mut Context<Self>,
) -> impl IntoElement {
v_flex()
.h_full()
.w(px(TREE_WIDTH))
.p_2()
.flex_none()
.border_r_1()
.border_color(cx.theme().border)
.child(div().flex_1().min_h_0().child(tree(
&tree_state,
move |ix, entry, selected, _window, _cx| {
Self::render_tree_item(ix, entry, selected, &view)
},
)))
}
/// Right column, README, selected file preview or status text.
pub(super) fn render_content_column(
&self,
pane_title: SharedString,
cx: &mut Context<Self>,
) -> impl IntoElement {
let loading = self.loading;
let error = self.error.clone();
let selected_file = self.selected_file.clone();
let body: AnyElement = if loading {
v_flex()
.size_full()
.items_center()
.justify_center()
.gap_2()
.child(Spinner::new().small())
.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child("Cloning repository..."),
)
.into_any_element()
} else if let Some(error) = error {
v_flex()
.size_full()
.items_center()
.justify_center()
.p_4()
.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child(error),
)
.into_any_element()
} else if let Some(path) = selected_file {
match self.files.get(path.as_ref()) {
Some(FileContent::Text(_)) => {
if is_markdown_path(path.as_ref()) {
self.markdown_element(Some(path.as_ref()), cx)
} else {
self.code_element(path.as_ref(), cx)
}
}
Some(FileContent::Binary) => placeholder("Binary file — preview not supported", cx),
Some(FileContent::TooLarge) => placeholder("File is too large to preview", cx),
Some(FileContent::Failed(message)) => placeholder(message, cx),
None => preview_spinner(),
}
} else if self.readme_name.is_some() {
self.markdown_element(None, cx)
} else {
placeholder("No README found", cx)
};
// Latest commit for the current pane, the selected file or the README.
// Computed after the body above, which needs `&mut self`.
let commit = match &self.selected_file {
Some(path) => self.commits.get(path.as_ref()),
None => self
.readme_name
.as_ref()
.and_then(|name| self.commits.get(name.as_ref())),
};
v_flex()
.flex_1()
.min_w_0()
.h_full()
.child(
h_flex()
.px_3()
.h_9()
.gap_2()
.bg(cx.theme().muted)
.border_b(px(1.))
.border_color(cx.theme().border)
.text_color(cx.theme().muted_foreground)
.child(
div()
.text_xs()
.font_semibold()
.text_ellipsis()
.whitespace_nowrap()
.child(pane_title),
)
.when_some(commit, |this, commit| {
this.child(
h_flex()
.flex_1()
.gap_1()
.child(
Button::new("commit")
.xsmall()
.text()
.label(commit.id.clone()),
)
.child(
div()
.max_w(px(250.))
.text_xs()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
}),
)
.child(div().id("repo-content").flex_1().min_h_0().child(body))
}
/// Load `text` into the persistent markdown TextView state.
pub(super) fn set_markdown(
&mut self,
path: Option<SharedString>,
text: &str,
cx: &mut Context<Self>,
) {
let state = cx.new(|cx| TextViewState::markdown("", cx));
state.update(cx, |state, cx| state.push_str(text, cx));
self.md = Some(MarkdownView { path, state });
}
/// The persistent markdown TextView for `path`, where `None` is the README.
///
/// Shows a spinner while the document is being loaded or parsed.
fn markdown_element(&self, path: Option<&str>, _cx: &mut Context<Self>) -> AnyElement {
let Some(md) = &self.md else {
return preview_spinner();
};
let ready = match path {
Some(path) => md.path.as_deref() == Some(path),
None => md.path.is_none(),
};
if !ready {
return preview_spinner();
}
TextView::new(&md.state)
.selectable(true)
.scrollable(true)
.p_4()
.text_sm()
.into_any_element()
}
/// Load `text` into the persistent code editor state for `path`.
///
/// Code editor mode makes the Input render it read-only and highlighted.
pub(super) fn set_code(
&mut self,
path: SharedString,
text: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let language = code_language(path.as_ref()).unwrap_or("text");
let state = cx.new(|cx| {
EditorState::new(window, cx)
.language(language)
.default_value(text)
.line_number(true)
.folding(true)
});
self.code = Some(CodeView { path, state });
}
/// The persistent code editor for `path`, or a spinner while the file loads or parses.
fn code_element(&self, path: &str, _cx: &mut Context<Self>) -> AnyElement {
let Some(code) = &self.code else {
return preview_spinner();
};
if code.path.as_ref() != path {
return preview_spinner();
}
Editor::new(&code.state)
.readonly(true)
.bordered(false)
.rounded_none()
.h_full()
.text_sm()
.into_any_element()
}
}
@@ -1,160 +0,0 @@
use gpui::prelude::*;
use gpui::{AnyElement, App, Context, Window, div, px};
use gpui_component::scroll::Scrollbar;
use gpui_component::spinner::Spinner;
use gpui_component::{ActiveTheme, Sizable, h_flex, v_flex, v_virtual_list};
use signed_git::FileCommit;
use signed_ui::placeholder;
use utils::relative_time_secs;
use super::RepoDetailView;
/// Height of one commit row in the virtual list.
pub(super) const COMMIT_ROW_HEIGHT: f32 = 56.;
pub(super) fn commit_row(
ix: usize,
commit: &FileCommit,
on_click: impl Fn(&mut Window, &mut App) + 'static,
cx: &App,
) -> AnyElement {
h_flex()
.id(ix)
.px_4()
.h(px(COMMIT_ROW_HEIGHT))
.w_full()
.gap_3()
.items_center()
.border_b(px(1.))
.border_color(cx.theme().border)
.hover(|this| this.bg(cx.theme().list_hover))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_0p5()
.justify_center()
.child(
h_flex()
.gap_2()
.items_center()
.overflow_hidden()
.child(
div()
.font_family(cx.theme().mono_font_family.clone())
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(commit.id.clone()),
)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
.child(
h_flex()
.gap_2()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
)
.on_click(move |_event, window, cx| on_click(window, cx))
.into_any_element()
}
impl RepoDetailView {
pub(super) fn render_commits_tab(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(list) = self.all_commits.as_ref() else {
return if self.loading_all_commits {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new().small())
.into_any_element()
} else {
placeholder("Failed to load commits", cx)
};
};
if list.commits.is_empty() {
return placeholder("No commits found", cx);
}
// Copy only the values the element tree needs.
// The list is borrowed by the renderer below instead of cloned per frame.
// A full history can be tens of thousands of commits.
let view = cx.entity().clone();
let sizes = self.item_sizes.clone();
let scroll_handle = self.scroll_handle.clone();
let shown = list.commits.len();
let total = list.total;
v_flex()
.relative()
.flex_1()
.w_full()
.min_h_0()
.child(
v_virtual_list(view, "commits", sizes, move |this, range, _window, cx| {
let view = cx.entity().downgrade();
let commits = this
.all_commits
.as_ref()
.map(|list| list.commits.as_slice())
.unwrap_or(&[]);
range
.map(|ix| {
let id = commits[ix].id.clone();
let view = view.clone();
commit_row(
ix,
&commits[ix],
move |window, cx| {
if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx)
});
}
},
cx,
)
})
.collect()
})
.track_scroll(&scroll_handle)
.size_full(),
)
.when(shown < total, |this| {
// The history is capped.
// Tell the user the list is truncated.
this.child(
div()
.py_2()
.w_full()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(format!("Showing {shown} of {total} commits")),
)
})
.child(
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(&self.scroll_handle)),
)
.into_any_element()
}
}
@@ -1,714 +0,0 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use assets::CustomIconName;
use gpui::prelude::*;
use gpui::{AnyElement, App, Entity, SharedString, div, px};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::combobox::{Caret, ComboboxTriggerContext};
use gpui_component::input::{Textarea, TextareaState};
use gpui_component::menu::PopupMenu;
use gpui_component::searchable_list::SearchableVec;
use gpui_component::tag::Tag;
use gpui_component::tree::TreeItem;
use gpui_component::{ActiveTheme, Icon, Sizable, StyledExt, h_flex, v_flex};
use nostr::nips::nip19::{Nip19Coordinate, ToBech32};
use nostr::prelude::{Event, EventId, PublicKey};
use signed_core::Announcement;
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileDiff};
use signed_state::{ProfileStore, RepoStore};
use signed_ui::{UserAvatar, menu_copy_row, middle_truncate};
use utils::relative_time;
pub(super) struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
id: String,
/// File or directory name.
label: String,
children: Vec<TreeItemSeed>,
}
pub(super) fn tree_items(seeds: Vec<TreeItemSeed>, expand_folders: bool) -> Vec<TreeItem> {
fn convert(seed: TreeItemSeed, expand_folders: bool) -> TreeItem {
let mut item = TreeItem::new(seed.id, seed.label);
if expand_folders && !seed.children.is_empty() {
item = item.expanded(true);
}
item.children = seed
.children
.into_iter()
.map(|seed| convert(seed, expand_folders))
.collect();
item
}
seeds
.into_iter()
.map(|seed| convert(seed, expand_folders))
.collect()
}
/// Build nested tree items from a flat entry list sorted dirs-first.
pub(super) fn build_tree_items(entries: &[PathBuf]) -> Vec<TreeItemSeed> {
// Node indices by full path, so parents resolve in constant time while inserting.
let mut index: HashMap<String, usize> = HashMap::new();
let mut nodes: Vec<(String, String, Vec<usize>)> = Vec::new();
let mut roots: Vec<usize> = Vec::new();
for entry in entries {
let mut parent: Option<usize> = None;
let mut path = String::new();
for part in entry.components() {
let label = part.as_os_str().to_string_lossy().into_owned();
path = if path.is_empty() {
label.clone()
} else {
format!("{path}/{label}")
};
let ix = *index.entry(path.clone()).or_insert_with(|| {
let ix = nodes.len();
nodes.push((path.clone(), label.clone(), Vec::new()));
match parent {
Some(parent) => nodes[parent].2.push(ix),
None => roots.push(ix),
}
ix
});
parent = Some(ix);
}
}
fn assemble(ix: usize, nodes: &[(String, String, Vec<usize>)]) -> TreeItemSeed {
let (id, label, children) = &nodes[ix];
TreeItemSeed {
id: id.clone(),
label: label.clone(),
children: children
.iter()
.map(|child| assemble(*child, nodes))
.collect(),
}
}
roots.iter().map(|root| assemble(*root, &nodes)).collect()
}
/// The markdown fence language for a file path, or `None` for plain text.
pub(super) fn code_language(path: &str) -> Option<&'static str> {
let name = Path::new(path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or_default();
// Some common files are recognized by name rather than extension.
match name {
"Makefile" | "makefile" => return Some("make"),
"CMakeLists.txt" => return Some("cmake"),
_ => {}
}
let ext = Path::new(path).extension()?.to_str()?.to_ascii_lowercase();
Some(match ext.as_str() {
"rs" => "rust",
"toml" => "toml",
"json" | "jsonc" => "json",
"py" => "python",
"js" | "mjs" | "cjs" => "javascript",
"ts" | "mts" | "cts" => "typescript",
"tsx" | "jsx" => "tsx",
"go" => "go",
"c" | "h" => "c",
"cc" | "cpp" | "cxx" | "hh" | "hpp" | "hxx" => "cpp",
"cs" => "csharp",
"java" => "java",
"kt" | "kts" | "ktm" => "kotlin",
"swift" => "swift",
"php" | "phtml" => "php",
"rb" => "ruby",
"sh" | "bash" | "zsh" => "bash",
"yml" | "yaml" => "yaml",
"css" | "scss" | "sass" => "css",
"html" | "htm" => "html",
"lua" => "lua",
"sql" => "sql",
"proto" | "protobuf" => "proto",
"cmake" => "cmake",
"zig" => "zig",
"ex" | "exs" => "elixir",
"graphql" | "gql" => "graphql",
"diff" | "patch" => "diff",
"svelte" => "svelte",
"astro" => "astro",
"scala" => "scala",
_ => return None,
})
}
/// Whether a file path has a markdown extension.
pub(super) fn is_markdown_path(path: &str) -> bool {
Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| {
matches!(
ext.to_ascii_lowercase().as_str(),
"md" | "markdown" | "mdown" | "mkdn"
)
})
}
pub(super) struct ShareTargets {
/// NIP-19 `naddr1...` of the announcement, with its announced relays.
pub(super) naddr: String,
/// Hex ID of the announcement event itself.
pub(super) event_id: String,
/// NIP-34 coordinate `30617:<pubkey>:<repo-id>`.
pub(super) coordinate: String,
/// `https://gitworkshop.dev/<naddr>`
pub(super) gitworkshop: String,
/// `https://ditto.pub/<naddr>`
pub(super) ditto: String,
}
impl ShareTargets {
pub(super) fn from_announcement(announcement: &Announcement) -> Self {
let addr = announcement.addr();
let coordinate = addr.to_string();
let naddr = Nip19Coordinate::new(addr, announcement.relays.iter().cloned())
.to_bech32()
.expect("a complete coordinate always encodes to naddr");
Self {
naddr: naddr.clone(),
event_id: announcement.event_id.to_bech32().unwrap(),
coordinate,
gitworkshop: format!("https://gitworkshop.dev/{naddr}"),
ditto: format!("https://ditto.pub/{naddr}"),
}
}
/// The share dropdown menu, one row per target.
///
/// Each shows a compact label, the copy button and row click copy the full value.
pub(super) fn menu(&self, menu: PopupMenu) -> PopupMenu {
menu.min_w(px(340.))
.item(menu_copy_row(
"copy-gitworkshop",
"GitWorkshop",
truncate_naddr_link(&self.gitworkshop, 4),
self.gitworkshop.clone(),
))
.item(menu_copy_row(
"copy-ditto",
"Ditto",
truncate_naddr_link(&self.ditto, 4),
self.ditto.clone(),
))
.item(menu_copy_row(
"copy-event-id",
"Event ID",
middle_truncate(&self.event_id, 10, 10),
self.event_id.clone(),
))
.item(menu_copy_row(
"copy-coordinate",
"Coordinate",
middle_truncate(&self.coordinate, 10, 10),
self.coordinate.clone(),
))
}
}
/// Shorten an naddr link to `<url>/naddr1...[last tail chars]`.
fn truncate_naddr_link(url: &str, tail: usize) -> String {
let Some(end) = url.find("naddr1").map(|i| i + "naddr1".len()) else {
return url.to_string();
};
if url.len() - end <= tail + 3 {
return url.to_string();
}
format!("{}...{}", &url[..end], &url[url.len() - tail..])
}
/// Width of one line-number gutter in a diff row.
pub(super) const GUTTER_WIDTH: f32 = 44.;
/// Height of one row in a virtual diff list.
pub(super) const DIFF_ROW_HEIGHT: f32 = 20.;
/// One row of a virtual diff list, a hunk header or a line of a hunk.
///
/// Shared by the commit diff and pull request diff viewers.
#[derive(Clone, Copy)]
pub(super) enum DiffRow {
Hunk {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
},
/// Line `line` of hunk `hunk` of the selected file's diff.
Line { hunk: usize, line: usize },
}
/// The rows of `file`'s diff, one header row per hunk then its lines.
pub(super) fn diff_rows(file: &FileDiff) -> Vec<DiffRow> {
let mut rows = Vec::new();
for (hunk_ix, hunk) in file.hunks.iter().enumerate() {
rows.push(DiffRow::Hunk {
old_start: hunk.old_start,
old_lines: hunk.old_lines,
new_start: hunk.new_start,
new_lines: hunk.new_lines,
});
rows.extend((0..hunk.lines.len()).map(|line| DiffRow::Line {
hunk: hunk_ix,
line,
}));
}
rows
}
/// One row of the virtual diff list, a hunk header or a single line.
pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> AnyElement {
match row {
DiffRow::Hunk {
old_start,
old_lines,
new_start,
new_lines,
} => div()
.px_2()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font_family.clone())
.text_xs()
.bg(cx.theme().muted)
.border_y(px(1.))
.border_color(cx.theme().border)
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(format!(
"@@ -{},{} +{},{} @@",
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => render_diff_line(&hunks[hunk].lines[line], cx),
}
}
/// One diff line, old and new line numbers in the gutters.
///
/// The content is tinted by kind, addition, deletion or context.
pub(super) fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement {
let bg = match line.kind {
DiffLineKind::Addition => Some(cx.theme().success.opacity(0.2)),
DiffLineKind::Deletion => Some(cx.theme().danger.opacity(0.2)),
DiffLineKind::Context => None,
};
let gutter = cx.theme().muted_foreground;
// Fixed height and nowrap, the virtual list assumes every row has the same height.
// Long lines are clipped instead of wrapped.
h_flex()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.items_center()
.font_family(cx.theme().mono_font_family.clone())
.text_xs()
.when_some(bg, |this, bg| this.bg(bg))
.child(
div()
.w(px(GUTTER_WIDTH))
.flex_none()
.pr_2()
.text_right()
.text_color(gutter)
.child(line.old.map(|n| n.to_string()).unwrap_or_default()),
)
.child(
div()
.w(px(GUTTER_WIDTH))
.flex_none()
.pr_2()
.text_right()
.text_color(gutter)
.child(line.new.map(|n| n.to_string()).unwrap_or_default()),
)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_color(cx.theme().foreground)
.child(line.text.clone()),
)
.into_any_element()
}
/// Find a tree item by id, searching into nested children.
pub(super) fn find_item<'a>(items: &'a [TreeItem], id: Option<&str>) -> Option<&'a TreeItem> {
let id = id?;
items.iter().find_map(|item| {
if item.id.as_ref() == id {
Some(item)
} else {
find_item(&item.children, Some(id))
}
})
}
/// The root issue events of a repo store, for the shared detail sections.
pub(super) fn issue_roots(store: &RepoStore) -> &[Event] {
&store.issues
}
/// The root pull request events of a repo store, for the shared detail sections.
pub(super) fn pr_roots(store: &RepoStore) -> &[Event] {
&store.pull_requests
}
/// The trigger body of the branch/tag selectors.
///
/// The kind icon, the selection or placeholder, and the caret.
/// `Combobox` replaces its default trigger entirely,
/// the only way to show an icon inside it.
pub(super) fn ref_selector_trigger(
ctx: &ComboboxTriggerContext<SearchableVec<SharedString>>,
icon: CustomIconName,
cx: &App,
) -> AnyElement {
let muted = cx.theme().muted_foreground;
h_flex()
.w_full()
.min_w_0()
.gap_1()
.items_center()
.child(Icon::new(icon).small().flex_shrink_0())
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.text_ellipsis()
.whitespace_nowrap()
.when(ctx.selection().is_empty(), |this| this.text_color(muted))
.child(
ctx.selection()
.first()
.map(|(_, item)| item.clone())
.or_else(|| ctx.placeholder().cloned())
.unwrap_or_default(),
),
)
.child(Caret::new(ctx.size()).text_color(muted))
.into_any_element()
}
/// Section heading of a detail sidebar, shared by the issue and PR panels.
pub(super) fn sidebar_title(text: &str, cx: &App) -> AnyElement {
div()
.text_xs()
.font_semibold()
.text_color(cx.theme().muted_foreground)
.child(text.to_string())
.into_any_element()
}
/// Right sidebar with participants and labels of a root event, issue or PR.
pub(super) fn sidebar_section(
store: &Entity<RepoStore>,
id: EventId,
roots: fn(&RepoStore) -> &[Event],
top_gap: bool,
cx: &App,
) -> AnyElement {
let store = store.read(cx);
let Some(root) = roots(store).iter().find(|event| event.id == id) else {
// The caller bails out when the root is missing.
return div().into_any_element();
};
let profile_store = ProfileStore::global(cx);
// Participants, the root author plus everyone who commented.
let mut participants: Vec<PublicKey> = vec![root.pubkey];
participants.extend(store.comments_of(&root.id).map(|comment| comment.pubkey));
participants.sort_by_key(PublicKey::to_hex);
participants.dedup();
// Labels are NIP-34 `t` hashtag tags on the event.
let labels: Vec<String> = root.tags.hashtags().map(|tag| tag.to_string()).collect();
v_flex()
.w(px(240.))
.h_full()
.flex_none()
.px_4()
.gap_4()
.border_l(px(1.))
.border_color(cx.theme().sidebar_border)
.child(
v_flex()
.when(top_gap, |this| this.mt_4())
.gap_2()
.child(sidebar_title("Participants", cx))
.children(participants.iter().map(|pubkey| {
let profile = profile_store.read(cx).get(pubkey);
let name = profile.name();
let picture = profile.picture();
h_flex()
.gap_1()
.items_center()
.child(UserAvatar::new(name.clone()).picture(picture))
.child(div().text_sm().truncate().text_ellipsis().child(name))
.into_any_element()
})),
)
.child(
v_flex()
.gap_2()
.child(sidebar_title("Labels", cx))
.map(|this| {
if labels.is_empty() {
this.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child("None yet."),
)
} else {
this.child(h_flex().gap_1().children({
let mut items = vec![];
for label in labels.iter() {
items.push(
Tag::secondary()
.outline()
.xsmall()
.child(SharedString::from(label)),
);
}
items
}))
}
}),
)
.into_any_element()
}
/// The comments on a root event, issue or PR, one card per comment.
pub(super) fn comments_section(store: &Entity<RepoStore>, root: EventId, cx: &App) -> AnyElement {
let store = store.read(cx);
let comments: Vec<&Event> = store.comments_of(&root).collect();
let title = SharedString::from(format!("Discussions {}", comments.len()));
v_flex()
.gap_4()
.child(div().text_xs().font_semibold().child(title))
.children(comments.iter().map(|comment| {
let profile = ProfileStore::global(cx).read(cx).get(&comment.pubkey);
let author = profile.name();
let picture = profile.picture();
let age = relative_time(comment.created_at);
let content = SharedString::from(comment.content.as_str());
v_flex()
.gap_1()
.p_3()
.border_1()
.border_color(cx.theme().border)
.rounded(cx.theme().radius)
.child(
h_flex()
.gap_2()
.text_sm()
.child(
h_flex()
.gap_1()
.child(UserAvatar::new(author.clone()).picture(picture))
.child(author),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child("commented"),
)
.child(
div()
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(age)),
),
)
.child(div().text_sm().child(content))
}))
.into_any_element()
}
/// The comment form posting to an issue or PR root event.
///
/// `roots` selects the root's list within the store, issues or pull requests.
pub(super) fn comment_form(
store: &Entity<RepoStore>,
root: EventId,
roots: fn(&RepoStore) -> &[Event],
comment_input: &Entity<TextareaState>,
button_id: &'static str,
cx: &App,
) -> AnyElement {
let comment_input = comment_input.clone();
let store = store.clone();
v_flex()
.gap_2()
.child(
Textarea::new(&comment_input)
.h_24()
.text_color(cx.theme().muted_foreground)
.bg(cx.theme().muted),
)
.child(
h_flex()
.justify_between()
.child(
h_flex()
.gap_1()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(Icon::new(CustomIconName::Markdown).small())
.child("Markdown is supported"),
)
.child(
Button::new(button_id)
.primary()
.label("Comment")
.tooltip("Post comment")
.on_click(move |_event, window, cx| {
let content = comment_input.read(cx).value().trim().to_string();
if content.is_empty() {
return;
}
let Some(root) = roots(store.read(cx))
.iter()
.find(|event| event.id == root)
.cloned()
else {
return;
};
store.update(cx, |store, cx| {
store.comment(&root, content, cx);
});
comment_input.update(cx, |input, cx| {
input.set_value("", window, cx);
});
}),
),
)
.into_any_element()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builds_nested_tree_from_flat_entries() {
let entries = vec![
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("README.md"),
PathBuf::from("docs/guide.md"),
];
let items = build_tree_items(&entries);
// Input order is preserved, dirs-first as produced by worktree_entries.
assert_eq!(items.len(), 3);
assert_eq!(items[0].label, "src");
assert_eq!(items[0].id, "src");
assert_eq!(items[0].children.len(), 1);
assert_eq!(items[0].children[0].label, "lib.rs");
assert_eq!(items[0].children[0].id, "src/lib.rs");
assert_eq!(items[1].label, "README.md");
assert_eq!(items[1].id, "README.md");
assert_eq!(items[2].label, "docs");
assert_eq!(items[2].children[0].label, "guide.md");
assert_eq!(items[2].children[0].id, "docs/guide.md");
}
#[test]
fn tree_builder_handles_deep_nesting() {
let entries = vec![
PathBuf::from("a"),
PathBuf::from("a/b"),
PathBuf::from("a/b/c.txt"),
];
let items = build_tree_items(&entries);
assert_eq!(items.len(), 1);
assert_eq!(items[0].children[0].id, "a/b");
assert_eq!(items[0].children[0].children[0].id, "a/b/c.txt");
}
#[test]
fn tree_builder_merges_shared_prefixes() {
// File children of a directory arrive after other directories' entries.
// The worktree list is dirs-first globally.
// The shared prefix must still resolve to one node.
let entries = vec![
PathBuf::from("a/x.txt"),
PathBuf::from("b/y.txt"),
PathBuf::from("a/z.txt"),
];
let items = build_tree_items(&entries);
assert_eq!(items.len(), 2);
assert_eq!(items[0].label, "a");
assert_eq!(items[0].children.len(), 2);
assert_eq!(items[1].label, "b");
}
#[test]
fn tree_seeds_convert_to_tree_items() {
let entries = vec![
PathBuf::from("src"),
PathBuf::from("src/main.rs"),
PathBuf::from("README.md"),
];
let items: Vec<TreeItem> = tree_items(build_tree_items(&entries), false);
assert_eq!(items.len(), 2);
assert_eq!(items[0].label, "src");
assert_eq!(items[0].children.len(), 1);
assert_eq!(items[0].children[0].label, "main.rs");
}
#[test]
fn code_language_maps_extensions_and_names() {
assert_eq!(code_language("src/main.rs"), Some("rust"));
assert_eq!(code_language("Cargo.toml"), Some("toml"));
assert_eq!(code_language("app.js"), Some("javascript"));
assert_eq!(code_language("index.tsx"), Some("tsx"));
assert_eq!(code_language("Makefile"), Some("make"));
assert_eq!(code_language("CMakeLists.txt"), Some("cmake"));
assert_eq!(code_language("data.csv"), None);
assert_eq!(code_language("LICENSE"), None);
assert_eq!(code_language("README.md"), None);
}
#[test]
fn naddr_link_keeps_url_and_tail() {
assert_eq!(
truncate_naddr_link("https://gitworkshop.dev/naddr1qqqxyzabc1234", 4),
"https://gitworkshop.dev/naddr1...1234"
);
// Without the naddr1 prefix, unchanged.
assert_eq!(
truncate_naddr_link("https://example.com/x", 4),
"https://example.com/x"
);
}
}
+72 -57
View File
@@ -1,3 +1,4 @@
use std::fmt::Display;
use std::rc::Rc;
use assets::CustomIconName;
@@ -5,7 +6,7 @@ use dock::{BasePanel, DockArea, Panel, PanelEvent};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
SharedString, Size, Subscription, WeakEntity, Window, div, px, size,
SharedString, Size, Subscription, WeakEntity, Window, div, px, relative, size,
};
use gpui_component::input::{Input, InputEvent, InputState};
use gpui_component::scroll::Scrollbar;
@@ -23,21 +24,32 @@ use super::open_repo_panel;
const COLUMNS: usize = 2;
const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.;
/// How many of the newest repositories the `Recent` sort shows.
const RECENT_COUNT: usize = 10;
/// Sort of the explore list, chosen via the header's filter buttons.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum RepoFilter {
/// Every repository in the store's default order, newest first.
All,
#[default]
/// Repositories ranked by total issues + pull requests + commits.
Popular,
/// The [`RECENT_COUNT`] newest repositories.
Recent,
}
impl AsRef<str> for RepoFilter {
fn as_ref(&self) -> &str {
match self {
RepoFilter::All => "all",
RepoFilter::Popular => "popular",
RepoFilter::Recent => "recent",
}
}
}
impl Display for RepoFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_ref())
}
}
impl RepoFilter {
/// Indices into the store's `announcements` this filter includes, in display order.
///
@@ -49,6 +61,7 @@ impl RepoFilter {
// Narrow by the search query first.
// Recent then limits the matches and Popular ranks them.
let query = query.trim().to_lowercase();
if !query.is_empty() {
indices.retain(|&ix| {
let announcement = &announcements[ix];
@@ -82,23 +95,18 @@ impl RepoFilter {
}
}
/// Browse all announced repositories.
pub struct RepoListView {
store: Entity<RepoListStore>,
dock_area: WeakEntity<DockArea>,
focus_handle: FocusHandle,
scroll_handle: VirtualListScrollHandle,
/// Sort selected in the header filter buttons.
filter: RepoFilter,
/// Per-row heights of the virtual list.
item_sizes: Rc<Vec<Size<Pixels>>>,
/// Number of rows [`Self::item_sizes`] was built for, the filtered repo count.
repo_len: usize,
/// Indices matching [`Self::filter`] into the store's `announcements`.
visible: Vec<usize>,
/// Search box filtering repositories by name.
search: Entity<InputState>,
/// Rebuilds the visible slice as the search text changes.
_search_subscription: Subscription,
_subscription: Subscription,
}
@@ -111,7 +119,6 @@ impl RepoListView {
) -> Self {
let store = RepoListStore::global(cx);
// Live search over repository names
let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search..."));
let search_subscription = cx.subscribe(&search, |this, _search, event, cx| {
if matches!(event, InputEvent::Change) {
@@ -125,7 +132,11 @@ impl RepoListView {
this.rebuild_rows(cx);
});
let mut this = Self {
cx.defer_in(window, |this, _window, cx| {
this.rebuild_rows(cx);
});
Self {
store,
dock_area,
focus_handle: cx.focus_handle(),
@@ -137,27 +148,19 @@ impl RepoListView {
search,
_search_subscription: search_subscription,
_subscription: subscription,
};
// Seed the rows right away.
// The store may already hold announcements from before the panel opened.
// The first render must not depend on a later store update.
this.rebuild_rows(cx);
this
}
}
/// Rebuild [`Self::visible`] and [`Self::item_sizes`] from the store.
///
/// Uses the store contents, [`Self::filter`] and the search query.
fn rebuild_rows(&mut self, cx: &mut Context<Self>) {
let filter = self.filter;
let query = self.search.read(cx).value();
let store = self.store.read(cx);
self.visible = filter.visible(store, &query);
// Each virtual list row holds `COLUMNS` repo cards.
let rows = self.visible.len().div_ceil(COLUMNS);
if self.repo_len != rows {
self.repo_len = rows;
self.item_sizes = Rc::new(vec![size(px(0.), px(CARD_HEIGHT)); rows]);
@@ -172,7 +175,13 @@ impl RepoListView {
window: &mut Window,
cx: &mut Context<Self>,
) {
open_repo_panel(&self.dock_area, announcement, window, &mut *cx);
open_repo_panel(
&self.dock_area,
&announcement.addr(),
Some(announcement),
window,
cx,
);
}
fn render_card(
@@ -187,12 +196,14 @@ impl RepoListView {
let name = announcement
.name
.clone()
.unwrap_or_else(|| SharedString::from(announcement.id.clone()));
.as_deref()
.map(SharedString::from)
.unwrap_or(SharedString::from(announcement.id.clone()));
let description = announcement
.description
.clone()
.as_deref()
.map(SharedString::from)
.unwrap_or(SharedString::from("No description"));
let activity = last_activity
@@ -213,7 +224,8 @@ impl RepoListView {
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.clone()
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier.clone()));
@@ -305,6 +317,22 @@ impl RepoListView {
.into_any_element()
}
fn render_filter<T>(&self, filter: RepoFilter, label: T, cx: &mut Context<Self>) -> AnyElement
where
T: Into<SharedString>,
{
let active = self.filter == filter;
SegmentButton::new(filter.to_string(), label)
.icon(Icon::new(filter.icon_name()))
.selected(active)
.on_click(cx.listener(move |this, _event, _window, cx| {
this.filter = filter;
this.rebuild_rows(cx);
}))
.into_any_element()
}
fn render_header(&self, count: usize, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.px_4()
@@ -312,18 +340,24 @@ impl RepoListView {
.w_full()
.gap_3()
.child(
h_flex()
.gap_1()
.text_xs()
.child(div().font_semibold().child("Repositories"))
v_flex()
.gap_0p5()
.child(
div()
.w_10()
.min_w_0()
.truncate()
.text_ellipsis()
.font_semibold()
.text_xs()
.line_height(relative(1.2))
.child("Repositories"),
)
.child(
div()
.text_size(px(10.))
.text_color(cx.theme().muted_foreground)
.child(SharedString::from(format!("({count})"))),
.line_height(relative(1.2))
.child(SharedString::from(format!("Total: {count}"))),
),
)
.child(
@@ -339,31 +373,12 @@ impl RepoListView {
.child(
h_flex()
.gap_1()
.child(self.filter_button(RepoFilter::All, "All", cx))
.child(self.filter_button(RepoFilter::Popular, "Popular", cx))
.child(self.filter_button(RepoFilter::Recent, "Recent", cx)),
.child(self.render_filter(RepoFilter::All, "All", cx))
.child(self.render_filter(RepoFilter::Popular, "Popular", cx))
.child(self.render_filter(RepoFilter::Recent, "Recent", cx)),
)
.into_any_element()
}
/// One segmented header filter button, like the issues list's status filter buttons.
fn filter_button(
&self,
filter: RepoFilter,
label: &'static str,
cx: &mut Context<Self>,
) -> AnyElement {
let active = self.filter == filter;
SegmentButton::new(label, label)
.icon(Icon::new(filter.icon_name()))
.selected(active)
.on_click(cx.listener(move |this, _event, _window, cx| {
this.filter = filter;
this.rebuild_rows(cx);
}))
.into_any_element()
}
}
impl BasePanel for RepoListView {
@@ -13,19 +13,12 @@ use signed_state::RepoStore;
pub struct SendPatchView {
focus_handle: FocusHandle,
/// Dock area the panel lives in.
dock_area: WeakEntity<DockArea>,
/// Store of the target repository.
store: Entity<RepoStore>,
/// Display name of the repository, for the panel title.
repo_name: SharedString,
/// Title input, required.
subject: Entity<InputState>,
/// Description input, optional.
description: Entity<TextareaState>,
/// The pasted `git format-patch` output, required.
patch: Entity<TextareaState>,
/// A submit is in flight.
submitting: bool,
/// Error of the last submit attempt, it keeps the panel open.
error: Option<SharedString>,
@@ -61,7 +54,6 @@ impl SendPatchView {
}
}
/// Publish the pull request from the pasted patch.
fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.submitting {
return;
@@ -17,10 +17,9 @@ use super::super::open_repo_panel;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::views::dialog_state::{DialogProgress, error_row};
/// Shared state for the Create Repository dialog, so async results can be rendered.
/// Progress of the create-repository flow, so async results can be rendered.
pub type CreateRepoState = DialogProgress;
/// Open the Create Repository dialog.
pub fn open(dock_area: WeakEntity<DockArea>, window: &mut Window, cx: &mut App) {
let settings = SettingsStore::global(cx);
let default_folder = settings
@@ -151,7 +150,6 @@ pub fn open(dock_area: WeakEntity<DockArea>, window: &mut Window, cx: &mut App)
});
}
/// Pick the repository's storage folder with the platform's native folder picker.
fn choose_folder(folder_input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let handle = window.window_handle();
let folder_input = folder_input.clone();
@@ -186,8 +184,6 @@ fn choose_folder(folder_input: &Entity<InputState>, window: &mut Window, cx: &mu
.detach();
}
/// Run the create-repository flow.
///
/// Opens the new working copy and the repository panel on success.
#[allow(clippy::too_many_arguments)]
fn create_repository(
@@ -250,12 +246,17 @@ fn create_repository(
.detach();
}
/// Open the newly created repository in the dock's center.
fn open_repo(
dock_area: WeakEntity<DockArea>,
announcement: Announcement,
window: &mut Window,
cx: &mut App,
) {
open_repo_panel(&dock_area, &announcement, window, cx);
open_repo_panel(
&dock_area,
&announcement.addr(),
Some(&announcement),
window,
cx,
);
}
@@ -8,20 +8,21 @@ use nostr::prelude::*;
use settings::{DEFAULT_GRASP_SERVERS, GraspServersSettings};
use signed_state::Backend;
use super::{normalize_server, server_host};
/// State of the grasp-server section of a publish dialog, so async results can be rendered.
#[derive(Default)]
pub struct GraspServersState {
/// The user's grasp list of kind `10317` is being loaded.
/// Set while the user's kind `10317` grasp list loads.
pub loading_servers: bool,
pub grasp_servers: Vec<RelayUrl>,
/// Whether the grasp server section is shown. Defaults to shown.
pub servers_enabled: bool,
/// Error of the last grasp-server edit, an invalid relay URL for example.
/// Error from the last grasp-server edit, such as an invalid relay URL.
pub error: Option<SharedString>,
}
impl GraspServersState {
/// Defaults used until the user's grasp list loads, which replaces them when non-empty.
/// Defaults used until the user's grasp list loads and replaces them.
///
/// Persisted settings supply the defaults, an empty list falls back to the built-ins.
pub fn new_default(settings: &GraspServersSettings) -> Self {
@@ -137,7 +138,6 @@ pub fn grasp_servers_field(
}))
}
/// One grasp server row, the host in a tag plus a remove button.
fn render_server_row(
ix: usize,
relay: &RelayUrl,
@@ -157,7 +157,7 @@ fn render_server_row(
.text_color(cx.theme().muted_foreground)
.text_sm()
.rounded(cx.theme().radius)
.child(display_server(relay)),
.child(server_host(relay)),
)
.child(
Button::new(format!("remove-relay:{ix}"))
@@ -176,15 +176,7 @@ fn render_server_row(
)
}
/// The bare host of a grasp server, defaults are entered without a scheme.
fn display_server(relay: &RelayUrl) -> SharedString {
relay
.domain()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(relay.to_string()))
}
/// Parse the relay input, accepting a bare host, and append it to the list.
/// Accepts a bare host as well as a full URL.
fn add_relay(
state: &Entity<GraspServersState>,
input: &Entity<InputState>,
@@ -196,14 +188,8 @@ fn add_relay(
return;
}
let normalized = if value.contains("://") {
value.clone()
} else {
format!("wss://{value}")
};
match RelayUrl::parse(&normalized) {
Ok(relay) => {
match normalize_server(&value) {
Some((_, relay)) => {
state.update(cx, |state, _| {
state.error = None;
if !state.grasp_servers.contains(&relay) {
@@ -212,7 +198,7 @@ fn add_relay(
});
input.update(cx, |input, cx| input.set_value("", window, cx));
}
Err(_) => {
None => {
state.update(cx, |state, _| {
state.error = Some(format!("Invalid grasp server URL: {value}").into());
});
@@ -220,9 +206,9 @@ fn add_relay(
}
}
/// Load the user's grasp list of kind `10317` from the local database.
/// Loads the user's kind `10317` grasp list from the local database.
///
/// It replaces the defaults when it lists any servers.
/// Replaces the defaults when the list is non-empty.
pub fn load_user_grasp_servers(
state: Entity<GraspServersState>,
window: &mut Window,
@@ -1,7 +1,6 @@
use gpui::{App, Window, px};
use gpui_component::WindowExt;
/// Open the Import Identity dialog.
pub fn open(window: &mut Window, cx: &mut App) {
window.open_dialog(cx, move |dialog, _window, _cx| {
dialog.title("Import identity").width(px(400.))
+370 -197
View File
@@ -1,6 +1,7 @@
use std::collections::HashSet;
use std::collections::HashMap;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use assets::CustomIconName;
@@ -10,19 +11,21 @@ use dock::{
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Div, Entity, EventEmitter, FocusHandle, Focusable, ObjectFit, Render,
SharedString, Subscription, WeakEntity, Window, div, img, px, uniform_list,
SharedString, Subscription, WeakEntity, Window, div, img, px, relative, uniform_list, white,
};
use gpui_base::Button as BaseButton;
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::input::InputState;
use gpui_component::{ActiveTheme, Icon, IconName, Sizable, StyledExt, h_flex, v_flex};
use signed_core::{Announcement, identifier_from_name};
use nostr::prelude::RelayUrl;
use signed_core::{Announcement, RepoAddr};
use signed_state::{
Backend, BackendEvent, CheckoutsStore, LocalReposStore, Profile, ProfileStore, RepoListStore,
Backend, BackendEvent, CheckoutsStore, LocalReposStore, Nip34Binding, Nip34Kind, Profile,
ProfileStore, RepoListStore, ResolvedLocalRepo, resolve_local_repos,
};
use signed_ui::{CountBadge, NavItem, PixelAvatar, UserAvatar, title_bar_drag_handlers};
use signed_ui::{NavItem, PixelAvatar, UserAvatar, title_bar_drag_handlers};
use super::{RepoDetailView, RepoListView, open_repo_panel};
use super::{InboxView, RepoDetailView, RepoListView, open_repo_panel};
mod create_repo_dialog;
pub(crate) mod grasp_servers;
@@ -33,114 +36,177 @@ mod settings_dialog;
use self::onboarding_dialog::OnboardingState;
/// Left-dock panel with navigation entries.
/// Entries open content panels in the dock area.
/// The platform that bound a repository, `"nak"` or `"ngit"`.
fn local_platform(binding: &Nip34Binding) -> Option<&'static str> {
let signals = &binding.signals;
if signals.nip34_json || signals.nip34_grasp_remote || signals.nip34_state_refs {
Some("nak")
} else if signals.nostr_repo_config {
Some("ngit")
} else {
None
}
}
pub struct SidebarPanel {
focus_handle: FocusHandle,
dock_area: WeakEntity<DockArea>,
inbox: Option<WeakEntity<InboxView>>,
explore: Option<WeakEntity<RepoListView>>,
logged_in: bool,
/// Repositories the current user announced, listed under the All Repositories heading.
/// Recreated when the signer changes.
my_repos: Option<Entity<RepoListStore>>,
/// Observes the current user's repo store so the list re-renders.
my_repos_subscription: Option<Subscription>,
/// Banner artwork behind the sign-in screen.
/// Picked at random from the bundled `backgrounds/` assets.
banner: SharedString,
/// Observes the local-repository scan so new discoveries re-render.
_local_repos_subscription: Subscription,
/// Observes the checkouts store.
/// Its ready-to-push statuses feed the badges on the user's repo rows.
_checkouts_subscription: Subscription,
_subscription: Subscription,
/// User's announced repositories.
announcements: Arc<Vec<Announcement>>,
/// Local repositories found by the scan that are not announced yet.
local_repos: Arc<Vec<ResolvedLocalRepo>>,
scanning: bool,
/// Unpushed commit counts per announced repository.
unpushed: HashMap<RepoAddr, usize>,
_subscriptions: Vec<Subscription>,
}
impl SidebarPanel {
pub fn new(dock_area: WeakEntity<DockArea>, cx: &mut Context<Self>) -> Self {
let local_repos_store = LocalReposStore::global(cx);
let backend = Backend::global(cx);
let logged_in = backend.read(cx).current_user().is_some();
let repos = RepoListStore::global(cx);
let local = LocalReposStore::global(cx);
let checkouts = CheckoutsStore::global(cx);
let subscription = cx.subscribe(&backend, |this, backend, event, cx| {
match event {
BackendEvent::SignerChanged => {
this.logged_in = backend.read(cx).current_user().is_some();
this.refresh_my_repos(cx);
}
BackendEvent::SignerRequired => {
this.logged_in = false;
this.banner = pick_banner();
this.my_repos = None;
this.my_repos_subscription = None;
}
_ => return,
let mut subscriptions = Vec::new();
// Identity changes swap the whole sidebar between the sign-in screen and the signed-in content.
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
let signer_changed = matches!(event, BackendEvent::SignerChanged);
let signer_required = matches!(event, BackendEvent::SignerRequired);
if !signer_changed && !signer_required {
return;
}
cx.notify();
});
let local_repos_subscription = cx.observe(&local_repos_store, |_, _, cx| {
cx.notify();
});
if signer_required {
this.banner = pick_banner();
cx.notify();
}
let checkouts_store = CheckoutsStore::global(cx);
let checkouts_subscription = cx.observe(&checkouts_store, |_, _, cx| {
cx.notify();
});
if this.refresh(cx) || signer_required {
cx.notify();
}
}));
let mut panel = Self {
subscriptions.push(cx.observe(&repos, |this, _repos, cx| {
if this.refresh(cx) {
cx.notify();
}
}));
subscriptions.push(cx.observe(&local, |this, _local, cx| {
if this.refresh(cx) {
cx.notify();
}
}));
// Push statuses are recomputed in the background, so only the badge counts change.
subscriptions.push(cx.observe(&checkouts, |this, _checkouts, cx| {
if this.refresh_unpushed(cx) {
cx.notify();
}
}));
Self {
focus_handle: cx.focus_handle(),
dock_area,
logged_in,
inbox: None,
explore: None,
my_repos: None,
my_repos_subscription: None,
banner: pick_banner(),
_local_repos_subscription: local_repos_subscription,
_checkouts_subscription: checkouts_subscription,
_subscription: subscription,
announcements: Arc::new(Vec::new()),
local_repos: Arc::new(Vec::new()),
scanning: false,
unpushed: HashMap::new(),
_subscriptions: subscriptions,
}
}
fn refresh(&mut self, cx: &mut Context<Self>) -> bool {
let backend = Backend::global(cx);
let user = backend.read(cx).current_user();
let (announcements, local_repos, scanning) = {
let repo_list = RepoListStore::global(cx);
let repo_list = repo_list.read(cx);
let announcements = user
.as_ref()
.map(|user| repo_list.announcements_of(user))
.unwrap_or_default();
let local = LocalReposStore::global(cx);
let local = local.read(cx);
let local_repos =
resolve_local_repos(&local.repos, &repo_list.announcements, &announcements);
(announcements, local_repos, local.scanning)
};
if logged_in {
panel.refresh_my_repos(cx);
let announcements_changed = *self.announcements != announcements;
let local_changed = *self.local_repos != local_repos;
let scanning_changed = self.scanning != scanning;
self.announcements = Arc::new(announcements);
self.local_repos = Arc::new(local_repos);
self.scanning = scanning;
if announcements_changed {
self.request_push_watches(cx);
self.unpushed.clear();
}
panel
announcements_changed || local_changed || scanning_changed
}
/// Recreate the store listing the current user's repositories.
/// Watch each repository for unpushed local work.
fn refresh_my_repos(&mut self, cx: &mut Context<Self>) {
self.my_repos_subscription = None;
fn refresh_unpushed(&mut self, cx: &mut Context<Self>) -> bool {
let checkouts = CheckoutsStore::global(cx);
let mut unpushed = HashMap::with_capacity(self.announcements.len());
let backend = Backend::global(cx);
let author = backend.read(cx).current_user();
self.my_repos = author.map(|author| cx.new(|cx| RepoListStore::new(Some(author), cx)));
if let Some(store) = self.my_repos.as_ref() {
self.my_repos_subscription = Some(cx.observe(store, |_this, store, cx| {
cx.notify();
// These are the signed-in user's own repositories.
// Request their ready-to-push statuses, deduplicated per repository.
// The rows carry a badge while local work is unpushed.
let addrs: Vec<_> = store
.read(cx)
.announcements
.iter()
.map(|a| a.addr())
.collect();
let checkouts = CheckoutsStore::global(cx);
checkouts.update(cx, |checkouts, cx| {
for addr in addrs {
checkouts.request_push_statuses(&addr, cx);
}
});
}));
for announcement in self.announcements.iter() {
let addr = announcement.addr();
let count = checkouts.read(cx).unpushed(&addr);
if count > 0 {
unpushed.insert(addr, count);
}
}
if unpushed == self.unpushed {
return false;
}
self.unpushed = unpushed;
true
}
fn request_push_watches(&self, cx: &mut Context<Self>) {
let checkouts = CheckoutsStore::global(cx);
checkouts.update(cx, |checkouts, cx| {
for announcement in self.announcements.iter() {
checkouts.request_push_statuses(&announcement.addr(), cx);
}
});
}
pub fn open_inbox(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.inbox.as_ref().and_then(WeakEntity::upgrade).is_some() {
return;
}
let panel = cx.new(|cx| InboxView::new(self.dock_area.clone(), cx));
self.inbox = Some(panel.downgrade());
self.dock_area
.update(cx, |dock_area, cx| {
add_center_panel(dock_area, panel_handle(panel), window, cx);
})
.ok();
}
/// Open the Explore repository list panel in the dock area's center.
/// No-op if it is already open.
pub fn open_explore(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self
.explore
@@ -154,12 +220,13 @@ impl SidebarPanel {
let panel = cx.new(|cx| RepoListView::new(self.dock_area.clone(), window, cx));
self.explore = Some(panel.downgrade());
let _ = self.dock_area.update(cx, |dock_area, cx| {
add_center_panel(dock_area, panel_handle(panel), window, cx);
});
self.dock_area
.update(cx, |dock_area, cx| {
add_center_panel(dock_area, panel_handle(panel), window, cx);
})
.ok();
}
/// Show the Onboarding dialog.
fn open_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let name_input = cx.new(|cx| InputState::new(window, cx).placeholder("Enter desired name"));
let pass_input = cx.new(|cx| {
@@ -177,41 +244,97 @@ impl SidebarPanel {
onboarding_dialog::open(name_input, pass_input, repass_input, state, window, cx);
}
/// Show the Create Repository dialog.
fn open_create_repo(&mut self, window: &mut Window, cx: &mut Context<Self>) {
create_repo_dialog::open(self.dock_area.clone(), window, cx);
}
/// Open a repository's detail view in the dock's center.
fn open_repo(
&mut self,
announcement: &Announcement,
window: &mut Window,
cx: &mut Context<Self>,
) {
open_repo_panel(&self.dock_area, announcement, window, &mut *cx);
open_repo_panel(
&self.dock_area,
&announcement.addr(),
Some(announcement),
window,
&mut *cx,
);
}
/// Open a local repository's detail view in the dock's center.
/// The detail view offers to publish it to NIP-34.
fn open_local_repo(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
fn open_local_repo(
&mut self,
path: PathBuf,
nip34: Option<Nip34Binding>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let detail =
cx.new(|cx| RepoDetailView::new_local(self.dock_area.clone(), path, window, cx));
let _ = self.dock_area.update(cx, |dock_area, cx| {
add_center_panel(dock_area, panel_handle(detail), window, cx);
});
cx.new(|cx| RepoDetailView::new_local(self.dock_area.clone(), path, nip34, window, cx));
self.add_detail_panel(detail, window, cx);
}
/// The All Repositories section of the sidebar.
/// A header with the create button above the current user's repositories.
/// Rendered lazily through a [`uniform_list`].
/// Followed by local git repositories from the startup scan.
fn render_my_repos(&self, cx: &mut Context<Self>) -> impl IntoElement {
let store = self.my_repos.as_ref();
let local = LocalReposStore::global(cx);
let local_repos = local.read(cx).repos.clone();
let scanning = local.read(cx).scanning;
/// A local repository whose binding matches an announcement opens as the announced repository.
fn open_local_announced(
&mut self,
announcement: Announcement,
path: PathBuf,
window: &mut Window,
cx: &mut Context<Self>,
) {
let detail = cx.new(|cx| {
RepoDetailView::new_local_announced(
self.dock_area.clone(),
announcement,
path,
window,
cx,
)
});
self.add_detail_panel(detail, window, cx);
}
/// A local repository opens as the announced repository
/// when its binding matches one, and as a local-only repository otherwise.
fn open_local_entry(
&mut self,
entry: ResolvedLocalRepo,
window: &mut Window,
cx: &mut Context<Self>,
) {
let ResolvedLocalRepo {
path,
nip34,
announcement,
} = entry;
if let Some(announcement) = announcement {
self.open_local_announced(announcement, path, window, cx);
return;
}
self.open_local_repo(path, nip34, window, cx);
}
fn add_detail_panel(
&mut self,
detail: Entity<RepoDetailView>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.dock_area
.update(cx, |dock_area, cx| {
add_center_panel(dock_area, panel_handle(detail), window, cx);
})
.ok();
}
fn render_repos(&self, cx: &mut Context<Self>) -> impl IntoElement {
let announcements = self.announcements.clone();
let local_repos = self.local_repos.clone();
let scanning = self.scanning;
v_flex()
.px_2()
@@ -258,57 +381,36 @@ impl SidebarPanel {
),
),
)
.when_some(store, |builder, store| {
let announcements = store.read(cx).announcements.clone();
// Local repositories already published to NIP-34 appear above.
// Hide them from the local section here.
// Matched by the identifier derived from the directory name.
// Same derivation as the init dialog's default name.
let announced_ids: HashSet<String> =
announcements.iter().map(|a| a.id.clone()).collect();
let local_repos: Vec<PathBuf> = local_repos
.iter()
.filter(|path| {
let Some(name) = path.file_name() else {
return true;
};
!announced_ids.contains(&identifier_from_name(&name.to_string_lossy()))
})
.cloned()
.collect();
// One merged list, the user's NIP-34 repositories first.
// Local repositories discovered by the scan follow.
.map(|this| {
// The merged list: NIP-34 repositories first, then discovered local repositories.
let total = announcements.len() + local_repos.len();
if total == 0 {
builder.child(
this.child(
div()
.flex_1()
.px_2()
.py_1()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child(if scanning {
"Scanning for local repositories…"
} else {
"No repositories yet"
.map(|this| {
if scanning {
this.child("Scanning for local repositories…")
} else {
this.child("No repositories yet")
}
}),
)
} else {
builder.child(
this.child(
uniform_list(
"repos",
total,
cx.processor(move |this, range: Range<usize>, _window, cx| {
cx.processor(move |this, range: Range<usize>, _, cx| {
range
.map(|ix| {
this.render_repo_row_at(
&announcements,
&local_repos,
ix,
cx,
)
.into_any_element()
this.render_repo_at(&announcements, &local_repos, ix, cx)
.into_any_element()
})
.collect()
}),
@@ -320,11 +422,10 @@ impl SidebarPanel {
})
}
/// One row of the merged sidebar list, a NIP-34 or a local repository.
fn render_repo_row_at(
fn render_repo_at(
&self,
announcements: &[Announcement],
local_repos: &[PathBuf],
local_repos: &[ResolvedLocalRepo],
ix: usize,
cx: &mut Context<Self>,
) -> AnyElement {
@@ -335,9 +436,9 @@ impl SidebarPanel {
}
let local_ix = ix - announcements.len();
let path = &local_repos[local_ix];
let entry = &local_repos[local_ix];
self.render_local_row(path, cx).into_any_element()
self.render_local_row(entry, cx).into_any_element()
}
fn render_repo_row(
@@ -345,26 +446,32 @@ impl SidebarPanel {
announcement: &Announcement,
cx: &mut Context<Self>,
) -> impl IntoElement {
let name = announcement
.name
.clone()
.unwrap_or_else(|| SharedString::from(announcement.id.clone()));
let name = announcement.name().map(SharedString::from);
let avatar = PixelAvatar::new(format!("{}:{}", announcement.owner, announcement.id));
// Badge with the unpushed commit count of the repository's local checkouts.
// The commits are ready to push to the grasp servers.
let unpushed: usize = CheckoutsStore::global(cx)
.read(cx)
.push_statuses_of(&announcement.addr())
.iter()
.map(|status| status.ahead as usize)
.sum();
let announcement = announcement.clone();
let mut row = NavItem::new(format!("my-repo:{}", announcement.id), name, avatar);
let unpushed = self
.unpushed
.get(&announcement.addr())
.copied()
.unwrap_or(0);
let mut row = NavItem::new(format!("repo:{}", announcement.id), name, avatar);
if unpushed > 0 {
row = row.suffix(CountBadge::new(unpushed));
row = row.suffix(
v_flex()
.flex_shrink_0()
.size_4()
.items_center()
.justify_center()
.rounded_full()
.line_height(relative(1.))
.bg(cx.theme().red_light)
.text_color(white())
.text_size(px(8.))
.child(SharedString::from(unpushed.to_string())),
);
}
row.on_click(
@@ -372,37 +479,60 @@ impl SidebarPanel {
)
}
/// One local repository row, a deterministic pixel avatar seeded from the path.
/// The directory name and a warning suffix, the repo is not yet set up for NIP-34.
/// Clicking opens the detail view, which offers to initialize it.
fn render_local_row(&self, path: &Path, cx: &mut Context<Self>) -> impl IntoElement {
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
let path = path.to_path_buf();
fn render_local_row(
&self,
entry: &ResolvedLocalRepo,
cx: &mut Context<Self>,
) -> impl IntoElement {
let name = entry.name();
let avatar = local_avatar(entry, cx);
NavItem::new(
format!("local-repo:{}", path.display()),
name,
PixelAvatar::new(path.to_string_lossy()),
)
.suffix(
Icon::new(IconName::TriangleAlert)
.small()
.text_color(cx.theme().warning),
)
.on_click(cx.listener(move |this, _ev, window, cx| {
this.open_local_repo(path.clone(), window, cx);
}))
let id = format!("local-repo:{}", entry.path.display());
let entry = entry.clone();
let suffix: AnyElement = match entry.nip34.as_ref() {
Some(binding) => {
let (label, tooltip) = match binding.kind {
Nip34Kind::Initialized => {
let platform = local_platform(binding).unwrap_or("Grasp");
let tooltip = match platform {
"nak" => "Initialized with nak",
"ngit" => "Initialized with ngit",
_ => "Initialized for NIP-34",
};
(platform, tooltip)
}
Nip34Kind::Cloned => ("Cloned", "Cloned buts not initialized"),
Nip34Kind::ToolingOnly => ("Tooling", "Grasp tooling only"),
};
Button::new(id.clone())
.xsmall()
.child(div().text_size(px(10.)).child(label))
.tooltip(tooltip)
.secondary()
.into_any_element()
}
None => Button::new(id.clone())
.xsmall()
.icon(IconName::TriangleAlert)
.tooltip("Not published yet")
.ghost()
.into_any_element(),
};
NavItem::new(id, name, avatar)
.suffix(suffix)
.on_click(cx.listener(move |this, _ev, window, cx| {
this.open_local_entry(entry.clone(), window, cx);
}))
}
/// Show the Import Identity dialog.
fn open_import(&mut self, window: &mut Window, cx: &mut Context<Self>) {
import_dialog::open(window, cx);
}
/// Render the user avatar and name in the sidebar, inside the titlebar drag area.
/// The user avatar and name, wired into the titlebar drag area.
fn render_user(
&self,
profile: &Profile,
@@ -432,8 +562,7 @@ impl SidebarPanel {
)
}
/// Sign-in placeholder shown while logged out.
/// Banner artwork behind a scrim keeps the CTA buttons readable in both themes.
/// Shown while no identity is signed in.
fn render_sign_in(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
v_flex()
.size_full()
@@ -503,6 +632,50 @@ impl SidebarPanel {
}
}
/// Normalize a user-typed grasp server, adding a `wss://` scheme when none is given.
///
/// Returns the text to store and the parsed relay URL, or `None` when it is not a valid relay URL.
pub(super) fn normalize_server(input: &str) -> Option<(String, RelayUrl)> {
let text = if input.contains("://") {
input.to_owned()
} else {
format!("wss://{input}")
};
RelayUrl::parse(&text).ok().map(|relay| (text, relay))
}
/// The host of a relay URL, which is what the server lists show; the scheme is implied.
pub(super) fn server_host(relay: &RelayUrl) -> SharedString {
relay
.domain()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(relay.to_string()))
}
/// The repository's pixel avatar, with the bound owner's avatar at its bottom right.
fn local_avatar(entry: &ResolvedLocalRepo, cx: &App) -> AnyElement {
let avatar = PixelAvatar::new(entry.path.to_string_lossy());
let Some(owner) = entry.nip34.as_ref().and_then(|binding| binding.owner) else {
return avatar.into_any_element();
};
let store = ProfileStore::global(cx);
let profile = store.read(cx).get(&owner);
div()
.relative()
.child(avatar)
.child(
div().absolute().bottom_neg_0p5().right_neg_0p5().child(
UserAvatar::new(profile.name())
.picture(profile.picture())
.size(px(14.)),
),
)
.into_any_element()
}
fn pick_banner() -> SharedString {
let num = SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -539,10 +712,6 @@ impl Focusable for SidebarPanel {
impl Render for SidebarPanel {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if !self.logged_in {
return self.render_sign_in(window, cx);
}
let backend = Backend::global(cx);
let profile_store = ProfileStore::global(cx);
@@ -551,10 +720,14 @@ impl Render for SidebarPanel {
.current_user()
.map(|public_key| profile_store.read(cx).get(&public_key));
if profile.is_none() {
return self.render_sign_in(window, cx);
}
v_flex()
.image_cache(gpui::retain_all("sidebar"))
.size_full()
.justify_between()
.image_cache(gpui::retain_all("sidebar"))
.bg(cx.theme().sidebar)
.text_color(cx.theme().sidebar_foreground)
.child(
@@ -573,7 +746,7 @@ impl Render for SidebarPanel {
.child(
NavItem::new("inbox", "Inbox", Icon::new(IconName::Inbox).small())
.on_click(cx.listener(|this, _ev, window, cx| {
this.open_explore(window, cx)
this.open_inbox(window, cx)
})),
)
.child(
@@ -597,7 +770,7 @@ impl Render for SidebarPanel {
)),
),
)
.child(self.render_my_repos(cx)),
.child(self.render_repos(cx)),
)
.child(
v_flex()
@@ -9,10 +9,9 @@ use signed_state::Backend;
use crate::views::dialog_state::{DialogProgress, error_row};
/// Shared state for the Onboarding dialog, so async results can be rendered.
/// Progress of the onboarding flow, so async results can be rendered.
pub type OnboardingState = DialogProgress;
/// Open the Onboarding dialog for creating a new identity.
pub fn open(
name_input: Entity<InputState>,
pass_input: Entity<InputState>,
@@ -10,16 +10,14 @@ use signed_state::Backend;
use crate::views::dialog_state::{DialogProgress, error_row};
/// Shared state for the passphrase dialog, so async results can be rendered.
/// State of the passphrase dialog, so async results can be rendered.
#[derive(Default)]
pub struct PassphraseState {
/// Progress of the unlock flow.
pub progress: DialogProgress,
/// Keeps the Enter-to-submit subscription alive while the dialog is open.
_enter_subscription: Option<Subscription>,
}
/// Open the dialog asking for the passphrase that protects the stored identity.
pub fn open(window: &mut Window, cx: &mut App) {
let pass_input = cx.new(|cx| {
InputState::new(window, cx)
@@ -30,7 +28,7 @@ pub fn open(window: &mut Window, cx: &mut App) {
let handle = window.window_handle();
let state = cx.new(|_| PassphraseState::default());
// Enter in the passphrase field submits, same as the Unlock button.
// Enter in the passphrase field submits, like the Unlock button.
let enter_pass_input = pass_input.clone();
let enter_state = state.clone();
let enter_subscription = cx.subscribe(&pass_input, move |_input, event, cx| {
@@ -95,7 +93,6 @@ pub fn open(window: &mut Window, cx: &mut App) {
});
}
/// Submit the passphrase to the backend.
fn unlock(
pass_input: &Entity<InputState>,
state: &Entity<PassphraseState>,
@@ -18,11 +18,12 @@ use gpui_component::{
ActiveTheme, IconName, IndexPath, Sizable, Theme, ThemeMode, ThemeRegistry, WindowExt, h_flex,
v_flex,
};
use nostr::prelude::RelayUrl;
use settings::{AppearanceMode, Settings, SettingsStore};
use signed_ui::{SelectOption, setting_block, setting_row};
/// The index of `value` in `options`, for seeding a [`SelectState`].
use super::{normalize_server, server_host};
/// Looks up the option index used to seed a [`SelectState`].
fn selected_index(options: &[SelectOption], value: &str) -> Option<IndexPath> {
options
.iter()
@@ -30,7 +31,7 @@ fn selected_index(options: &[SelectOption], value: &str) -> Option<IndexPath> {
.map(|row| IndexPath::default().row(row))
}
/// The light and dark themes registered in the theme registry.
/// Registered themes split into light and dark options, light first.
fn theme_options(cx: &App) -> (Vec<SelectOption>, Vec<SelectOption>) {
let registry = ThemeRegistry::global(cx);
let mut light = Vec::new();
@@ -48,7 +49,7 @@ fn theme_options(cx: &App) -> (Vec<SelectOption>, Vec<SelectOption>) {
(light, dark)
}
/// Stateful controls of the settings dialog, created once when it opens.
/// Created once when the dialog opens, so control state survives re-renders.
struct SettingsControls {
appearance: Entity<SelectState<Vec<SelectOption>>>,
light_theme: Entity<SelectState<Vec<SelectOption>>>,
@@ -58,9 +59,9 @@ struct SettingsControls {
radius: Entity<InputState>,
radius_lg: Entity<InputState>,
grasp_server_input: Entity<InputState>,
/// The effective default create-repository folder, shown in the disabled input.
/// The effective create-repository folder, shown in a disabled input.
default_folder: Entity<InputState>,
/// Keeps the control subscriptions alive for the dialog's lifetime.
/// Keeps the control subscriptions alive while the dialog is open.
_subscriptions: Vec<Subscription>,
}
@@ -264,31 +265,19 @@ impl SettingsControls {
}
}
/// Open the Settings dialog.
pub fn open(window: &mut Window, cx: &mut App) {
let controls = Rc::new(SettingsControls::new(window, cx));
let store = SettingsStore::global(cx);
let window_handle = window.window_handle();
let store_subscription = cx.observe(&store, move |_, cx| {
window_handle
.update(cx, |_, window, _| window.refresh())
.ok();
});
let dialog_state = Rc::new((controls, store_subscription));
window.open_dialog(cx, move |dialog, _window, cx| {
let dialog_state = dialog_state.clone();
let controls = controls.clone();
dialog
.title("Settings")
.width(px(650.))
.h(px(560.))
.child(settings_view(&dialog_state.0, cx))
.child(settings_view(&controls, cx))
});
}
/// The settings content, one section per related setting.
/// Sections are divided by horizontal separator lines.
fn settings_view(controls: &SettingsControls, cx: &mut App) -> impl IntoElement {
let store = SettingsStore::global(cx);
let settings = store.read(cx).settings().clone();
@@ -306,7 +295,6 @@ fn settings_view(controls: &SettingsControls, cx: &mut App) -> impl IntoElement
.child(repositories_section(&settings, controls, cx))
}
/// How the app picks its appearance.
fn appearance_section(controls: &SettingsControls, cx: &App) -> impl IntoElement {
v_flex().w_full().gap_3().child(setting_row(
cx,
@@ -316,7 +304,6 @@ fn appearance_section(controls: &SettingsControls, cx: &App) -> impl IntoElement
))
}
/// Theme configuration, the registry theme names plus tweaks the app customizes at startup.
fn theme_section(settings: &Settings, controls: &SettingsControls, cx: &App) -> impl IntoElement {
v_flex()
.gap_3()
@@ -387,7 +374,7 @@ fn theme_section(settings: &Settings, controls: &SettingsControls, cx: &App) ->
))
}
/// Default grasp servers offered until the user publishes a kind `10317` grasp list.
/// Default grasp servers, used until the user's kind `10317` grasp list loads.
fn grasp_servers_section(
settings: &Settings,
controls: &SettingsControls,
@@ -403,7 +390,6 @@ fn grasp_servers_section(
))
}
/// The editable list of default grasp servers plus an add-relay input.
/// Styled like the grasp-server section of the publish dialogs.
fn grasp_server_editor(
servers: &[String],
@@ -468,17 +454,14 @@ fn grasp_server_editor(
)
}
/// The bare host of a grasp server, defaults are entered without a scheme.
/// Matches how the publish dialogs display servers.
/// Shows only the host, since grasp servers are entered without a scheme.
fn display_server(server: &str) -> SharedString {
RelayUrl::parse(server)
.ok()
.and_then(|relay| relay.domain().map(|domain| domain.to_owned()))
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(server.to_owned()))
match normalize_server(server) {
Some((_, relay)) => server_host(&relay),
None => SharedString::from(server.to_owned()),
}
}
/// Local repository scanning and the create-repository dialog default folder.
fn repositories_section(
settings: &Settings,
controls: &SettingsControls,
@@ -503,7 +486,6 @@ fn repositories_section(
))
}
/// The editable list of scan directories plus an add-directory button.
/// Styled like the grasp-server list.
fn scan_paths_editor(scan_paths: &[PathBuf], cx: &App) -> impl IntoElement {
v_flex()
@@ -556,7 +538,6 @@ fn scan_paths_editor(scan_paths: &[PathBuf], cx: &App) -> impl IntoElement {
)
}
/// The default-folder selector, a disabled input plus a picker button.
/// Matches the create-repository dialog.
fn folder_selector(controls: &SettingsControls) -> impl IntoElement {
let default_folder = controls.default_folder.clone();
@@ -580,21 +561,15 @@ fn folder_selector(controls: &SettingsControls) -> impl IntoElement {
)
}
/// Parse the server input and append it to the default grasp servers.
/// A bare host is accepted.
/// Accepts a bare host as well as a full URL.
fn add_server(input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let value = input.read(cx).value().trim().to_owned();
if value.is_empty() {
return;
}
let normalized = if value.contains("://") {
value
} else {
format!("wss://{value}")
};
if RelayUrl::parse(&normalized).is_err() {
let Some((normalized, _)) = normalize_server(&value) else {
return;
}
};
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
@@ -613,7 +588,6 @@ fn add_server(input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
input.update(cx, |input, cx| input.set_value("", window, cx));
}
/// Prompt for directories to add to the local-repository scan.
fn add_scan_path(cx: &mut App) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
@@ -650,8 +624,7 @@ fn add_scan_path(cx: &mut App) {
.detach();
}
/// Prompt for the Create Repository dialog's default folder.
/// Remember it in the settings and show it in the disabled input.
/// Persists the choice and reflects it in the disabled input.
fn choose_default_folder(default_folder: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let handle = window.window_handle();
let default_folder = default_folder.clone();
@@ -685,9 +658,7 @@ fn choose_default_folder(default_folder: &Entity<InputState>, window: &mut Windo
.detach();
}
/// Wire a number input to the settings.
/// Step actions clamp and persist the value.
/// Typed changes parse, clamp and persist.
/// Step actions clamp and persist the value; typed changes parse, clamp and persist.
fn wire_number_input(
state: &Entity<InputState>,
subscriptions: &mut Vec<Subscription>,
@@ -760,7 +731,6 @@ fn wire_number_input(
}));
}
/// Apply the persisted appearance to the live theme.
fn apply_appearance(appearance: AppearanceMode, cx: &mut App) {
match appearance {
AppearanceMode::System => Theme::sync_system_appearance(None, cx),
@@ -769,7 +739,6 @@ fn apply_appearance(appearance: AppearanceMode, cx: &mut App) {
}
}
/// Re-apply the persisted theme configuration to the live theme.
fn apply_theme(cx: &mut App) {
let store = SettingsStore::global(cx);
let settings = store.read(cx).settings().theme.clone();
+45
View File
@@ -0,0 +1,45 @@
use nostr::prelude::Event;
use signed_core::RepoStatus;
/// Root events counted by their resolved status.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct StatusCounts {
pub(crate) total: usize,
pub(crate) open: usize,
pub(crate) closed: usize,
pub(crate) draft: usize,
pub(crate) applied: usize,
}
impl StatusCounts {
fn record(&mut self, status: RepoStatus) {
self.total += 1;
match status {
RepoStatus::Open => self.open += 1,
RepoStatus::Closed => self.closed += 1,
RepoStatus::Draft => self.draft += 1,
RepoStatus::Applied => self.applied += 1,
}
}
}
/// Indices of `roots` whose status `keep` accepts, counting every root's status.
pub(crate) fn filter_by_status<'a>(
roots: impl IntoIterator<Item = &'a Event>,
status_of: impl Fn(&Event) -> RepoStatus,
keep: impl Fn(RepoStatus) -> bool,
) -> (Vec<usize>, StatusCounts) {
let mut counts = StatusCounts::default();
let visible = roots
.into_iter()
.enumerate()
.filter_map(|(index, root)| {
let status = status_of(root);
counts.record(status);
keep(status).then_some(index)
})
.collect();
(visible, counts)
}
+153
View File
@@ -0,0 +1,153 @@
use std::collections::HashMap;
use std::path::PathBuf;
use gpui_component::tree::TreeItem;
pub(crate) struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
pub(crate) id: String,
pub(crate) label: String,
pub(crate) children: Vec<TreeItemSeed>,
}
pub(crate) fn tree_items(seeds: Vec<TreeItemSeed>, expand_folders: bool) -> Vec<TreeItem> {
fn convert(seed: TreeItemSeed, expand_folders: bool) -> TreeItem {
let mut item = TreeItem::new(seed.id, seed.label);
if expand_folders && !seed.children.is_empty() {
item = item.expanded(true);
}
item.children = seed
.children
.into_iter()
.map(|seed| convert(seed, expand_folders))
.collect();
item
}
seeds
.into_iter()
.map(|seed| convert(seed, expand_folders))
.collect()
}
/// Build nested tree items from a flat entry list sorted dirs-first.
pub(crate) fn build_tree_items(entries: &[PathBuf]) -> Vec<TreeItemSeed> {
// Node indices by full path, so parents resolve in constant time while inserting.
let mut index: HashMap<String, usize> = HashMap::new();
let mut nodes: Vec<(String, String, Vec<usize>)> = Vec::new();
let mut roots: Vec<usize> = Vec::new();
for entry in entries {
let mut parent: Option<usize> = None;
let mut path = String::new();
for part in entry.components() {
let label = part.as_os_str().to_string_lossy().into_owned();
path = if path.is_empty() {
label.clone()
} else {
format!("{path}/{label}")
};
let ix = *index.entry(path.clone()).or_insert_with(|| {
let ix = nodes.len();
nodes.push((path.clone(), label.clone(), Vec::new()));
match parent {
Some(parent) => nodes[parent].2.push(ix),
None => roots.push(ix),
}
ix
});
parent = Some(ix);
}
}
fn assemble(ix: usize, nodes: &[(String, String, Vec<usize>)]) -> TreeItemSeed {
let (id, label, children) = &nodes[ix];
TreeItemSeed {
id: id.clone(),
label: label.clone(),
children: children
.iter()
.map(|child| assemble(*child, nodes))
.collect(),
}
}
roots.iter().map(|root| assemble(*root, &nodes)).collect()
}
/// Sorted relative paths of a worktree snapshot.
///
/// Compared against the `worktree_paths` of a repository panel to skip
/// rebuilding the explorer when a refresh left the worktree unchanged.
pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
let mut paths: Vec<String> = entries
.iter()
.map(|path| path.to_string_lossy().into_owned())
.collect();
paths.sort();
paths
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builds_nested_tree_from_flat_entries() {
let entries = vec![
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("README.md"),
PathBuf::from("docs/guide.md"),
];
let items = build_tree_items(&entries);
// Input order is preserved, dirs-first as produced by worktree_entries.
assert_eq!(items.len(), 3);
assert_eq!(items[0].label, "src");
assert_eq!(items[0].id, "src");
assert_eq!(items[0].children.len(), 1);
assert_eq!(items[0].children[0].label, "lib.rs");
assert_eq!(items[0].children[0].id, "src/lib.rs");
assert_eq!(items[1].label, "README.md");
assert_eq!(items[1].id, "README.md");
assert_eq!(items[2].label, "docs");
assert_eq!(items[2].children[0].label, "guide.md");
assert_eq!(items[2].children[0].id, "docs/guide.md");
}
#[test]
fn tree_builder_handles_deep_nesting() {
let entries = vec![
PathBuf::from("a"),
PathBuf::from("a/b"),
PathBuf::from("a/b/c.txt"),
];
let items = build_tree_items(&entries);
assert_eq!(items.len(), 1);
assert_eq!(items[0].children[0].id, "a/b");
assert_eq!(items[0].children[0].children[0].id, "a/b/c.txt");
}
#[test]
fn tree_builder_merges_shared_prefixes() {
// File children of a directory arrive after other directories' entries.
// The worktree list is dirs-first globally.
// The shared prefix must still resolve to one node.
let entries = vec![
PathBuf::from("a/x.txt"),
PathBuf::from("b/y.txt"),
PathBuf::from("a/z.txt"),
];
let items = build_tree_items(&entries);
assert_eq!(items.len(), 2);
assert_eq!(items[0].label, "a");
assert_eq!(items[0].children.len(), 2);
assert_eq!(items[1].label, "b");
}
}
+34 -52
View File
@@ -1,28 +1,22 @@
use dock::{DockArea, DockEvent, DockLayout, DockPlacement, SignedDockSkin, panel_handle};
use gpui::prelude::*;
use gpui::{Context, Entity, KeyBinding, Render, Subscription, Window, actions, div, px};
use gpui::{Context, Entity, Render, Subscription, Window, div, px};
use gpui_component::{Root, StyledExt, Theme};
use gpui_fps::{FpsMonitor, FpsOverlay};
use settings::{AppearanceMode, SettingsStore};
use signed_state::{Backend, BackendEvent};
use crate::views::SidebarPanel;
use crate::views::sidebar::passphrase_dialog;
actions!(workspace, [ToggleMonitor]);
pub struct Workspace {
dock: Entity<DockArea>,
fps: Entity<FpsMonitor>,
/// Debug HUD, toggled with `cmd-shift-f`.
show_fps: bool,
_subscriptions: Vec<Subscription>,
_passphrase_subscription: Subscription,
}
impl Workspace {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let fps = cx.new(|cx| FpsMonitor::new(window, cx).continuous(false));
cx.bind_keys([KeyBinding::new("cmd-shift-f", ToggleMonitor, None)]);
let backend = Backend::global(cx);
let settings = SettingsStore::global(cx);
let dock = cx.new(|cx| {
let skin = SignedDockSkin::new(cx);
@@ -33,20 +27,15 @@ impl Workspace {
let sidebar = cx.new(|cx| SidebarPanel::new(weak_dock.clone(), cx));
let weak_sidebar = sidebar.downgrade();
dock.update(cx, |dock_area, cx| {
dock_area.set_dock(
DockPlacement::Left,
DockLayout::tabs().panel_view(panel_handle(sidebar), cx),
window,
cx,
);
dock_area.set_dock_size(DockPlacement::Left, px(240.), window, cx);
});
let mut subscriptions = vec![];
if settings.read(cx).settings().appearance == AppearanceMode::System {
subscriptions.push(cx.observe_window_appearance(window, |_this, window, cx| {
Theme::sync_system_appearance(Some(window), cx);
}));
}
// A bottom or right dock whose last panel was dragged away is removed entirely.
let dock_for_pruning = dock.clone();
subscriptions.push(cx.subscribe_in(
&dock,
window,
@@ -54,9 +43,9 @@ impl Workspace {
if !matches!(event, DockEvent::LayoutChanged) {
return;
}
let dock = dock_for_pruning.clone();
let weak = weak_dock.clone();
cx.spawn_in(window, async move |_, window| {
dock.update_in(window, |area, window, cx| {
weak.update_in(window, |area, window, cx| {
for placement in [DockPlacement::Bottom, DockPlacement::Right] {
if area.is_empty(placement, cx) {
area.remove_dock(placement, window, cx);
@@ -69,28 +58,34 @@ impl Workspace {
},
));
subscriptions.push(cx.observe_window_appearance(window, |_this, window, cx| {
Theme::sync_system_appearance(Some(window), cx);
}));
let backend = Backend::global(cx);
// Ask for the passphrase when the stored identity is NIP-49 encrypted.
let passphrase_subscription =
window.subscribe(&backend, cx, |_backend, event, window, cx| {
subscriptions.push(cx.subscribe_in(
&backend,
window,
|_this, _state, event, window, cx| {
if matches!(event, BackendEvent::PassphraseRequired) {
passphrase_dialog::open(window, cx);
}
},
));
cx.defer_in(window, move |this, window, cx| {
// The event may have fired before this window existed.
// Fall back to the backend state in that case.
if backend.read(cx).passphrase_required() {
passphrase_dialog::open(window, cx);
}
this.dock.update(cx, |dock_area, cx| {
dock_area.set_dock(
DockPlacement::Left,
DockLayout::tabs().panel_view(panel_handle(sidebar), cx),
window,
cx,
);
dock_area.set_dock_size(DockPlacement::Left, px(240.), window, cx);
});
// The event may have fired before this window existed.
// Fall back to the backend state in that case.
if backend.read(cx).passphrase_required() {
passphrase_dialog::open(window, cx);
}
// Open the explore panel after the sidebar has been initialized.
cx.defer_in(window, move |_, window, cx| {
weak_sidebar
.update(cx, |this, cx| {
this.open_explore(window, cx);
@@ -100,10 +95,7 @@ impl Workspace {
Self {
dock,
show_fps: cfg!(debug_assertions),
fps,
_subscriptions: subscriptions,
_passphrase_subscription: passphrase_subscription,
}
}
}
@@ -115,21 +107,11 @@ impl Render for Workspace {
div()
.id("workspace")
.on_action(
cx.listener(|this: &mut Self, _ev: &ToggleMonitor, _window, cx| {
this.show_fps = !this.show_fps;
cx.notify();
}),
)
.v_flex()
.size_full()
.relative()
.child(self.dock.clone())
// Notifications
.children(notification_layer)
// Modals
.children(dialog_layer)
// On top of everything, so it stays readable while debugging.
.when(self.show_fps, |this| this.child(FpsOverlay::new(&self.fps)))
}
}
+18
View File
@@ -8,6 +8,24 @@ publish.workspace = true
name = "signed"
path = "src/main.rs"
[package.metadata.packager]
name = "Signed"
product-name = "Signed"
description = "Nostr Git client for browsing repositories and collaborating"
identifier = "su.reya.signed"
category = "DeveloperTool"
version = "0.1.0-alpha"
out-dir = "../dist"
before-packaging-command = "cargo build --release"
resources = ["Cargo.toml", "src"]
icons = [
"resources/32x32.png",
"resources/128x128.png",
"resources/128x128@2x.png",
"resources/icon.icns",
"resources/icon.ico",
]
[dependencies]
assets = { path = "../crates/assets" }
paths = { path = "../crates/paths" }
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Some files were not shown because too many files have changed in this diff Show More