10 Commits
Author SHA1 Message Date
reya 0c6d700395 refactor 2026-08-06 14:52:43 +07:00
reya 6d5d154486 update sidebar 2026-08-06 14:21:03 +07:00
reya 627abbdcaf add create new identity 2026-08-06 14:02:16 +07:00
reya a97dfac23f . 2026-08-05 17:07:50 +07:00
reya 6b13d8a8f7 add workspace 2026-08-05 11:07:12 +07:00
reya 8de6018e28 update nostr connect 2026-08-05 10:37:33 +07:00
reya ed93d81a26 sync all repos 2026-08-05 10:20:12 +07:00
reya 2ec7d14c33 use negentropy sync 2026-08-05 10:08:01 +07:00
reya fdf74327bb update repo list 2026-08-05 09:24:46 +07:00
reya f497279886 add basic repo browser 2026-08-05 09:03:42 +07:00
283 changed files with 5711 additions and 55525 deletions
-173
View File
@@ -1,173 +0,0 @@
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.info/"
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
@@ -1,32 +0,0 @@
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
+1 -20
View File
@@ -1,20 +1 @@
# Generated by Cargo
# will have compiled files and executables
debug/
target/
dist/
# Snap and Flatpak local build output
/snap
/info.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
/target
-173
View File
@@ -1,173 +0,0 @@
# 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.
* Keep doc comments and comments simple, one line, straightforward, and unbloated.
* Prefer implementing functionality in existing files unless it is a new logical component. Avoid creating many small files.
* Prefer `impl` blocks over standalone functions: place functionality as methods or associated functions on the relevant type, extending the type's existing `impl` block instead of creating a duplicate one in another file.
* Do not wrap clients or SDK dependencies in project structs or pass-through helper functions, call their methods directly where needed. Extract a helper only when it holds real logic that is used in more than one place.
* Bind a global store handle to a local before using it (`let state = GlobalState::global(cx);` then `state.update(...)`) instead of chaining on `CheckoutsStore::global(cx)` inline.
* 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)`.
Prefer keeping a task in a field over `.detach()` when the work belongs to a view or store. A detached task outlives the view that started it (for example, a repository panel the user has closed), while a task stored in a field is cancelled when that struct drops. A finished `Task` held in a container is not reaped by GPUI - it stays alive until its handle is dropped - so if the container can accumulate many runs, either drop the finished handles before pushing a new one, or hold a single `Option<Task<_>>` and replace it.
## 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.
## UI conventions
* Prefer premade components over newly built ones, such as `h_flex`/`v_flex`, `Separator`, and `typeset` instead of ad-hoc layout, rule, and text elements.
* Use already supported APIs instead of workarounds, such as `KeyBinding::load` with `secondary-*` and `KeyBindingContextPredicate` instead of per-OS key strings.
* Use `uniform_list` for scrollable, uniform-height rows. Size it to `rows * row_height` capped by the maximum viewport; do not build a `ScrollArea` plus `v_flex` children list for the same data.
* Reuse semantic theme tokens. Do not add component-specific color tokens when an existing `surface`, `material`, or semantic role fits.
## 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.
GPUI also tracks the entities a window reads while rendering. When an entity notifies, every view that read that entity during the previous frame is rerendered automatically.
* A view that reads an entity in render (e.g. `state.read(cx).profile(...)`) does not need `cx.observe(&entity, ...)` to pick up its changes - the read itself is the dependency. Reserve `cx.observe` and `cx.subscribe` for when the view must run logic in response to a change (rebuild derived state, re-query, dedupe), not to trigger a re-render.
* Notify the narrowest entity holding the change. Notifying a global store rerenders every view that ever read it; notifying a per-panel entity rerenders only the panels reading it.
* This works with cached panels (`panel.cached(...)`): a cached subtree repaints when the view it belongs to is invalidated.
## 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.
# Commits
* Never commit changes before the user has reviewed them. Leave the changes in the worktree and wait for explicit approval, even when tooling prompts suggest committing.
# 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, `workspace: 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
```
-90
View File
@@ -1,90 +0,0 @@
# Changelog
## v0.2.0 - 2026/10/21
### Added
- Follow the operating system's native theme on macOS, Windows and Linux (KDE, GNOME), applying the OS colors, fonts, radii and accessibility preferences.
- Add an identity import dialog, importing an existing identity by pasting its `nsec` secret key (encrypted with a new passphrase), NIP-49 `ncryptsec` (unlocked with its passphrase), or `bunker://` NIP-46 URI
- Add a dropdown menu on the signed-in user button in the sidebar
- Add sign-out feature, confirmed by an alert dialog before deleting the stored session credential
- Add a quit action, bound to `secondary-q` (cmd on macOS, ctrl on others)
- Allow choosing the default branch when publishing a repository
- Detect when local commits are not on Nostr yet, showing an unsynced count badge on sidebar repository rows and a Sync now banner on the repository view
- Add a step-by-step push checklist while publishing and syncing a repository
- Add a `Reset remote to local` action that republishes the mirror and deletes grasp refs the mirror does not have
### Changed
- Use the built-in light/dark syntax highlighting palette instead of the Signed palette bundled in `signed.json` when the native theme is active
- Increase the default theme corner radii from 2 to 4 and large radii from 6 to 8
- Surface backend errors as error notifications in the workspace instead of silently dropping them
- Break ties in repository activity lists by event id, so same-second events order deterministically
- Restructure the backend around domain types: git operations behind a `Repo` type, the grasp push pipeline behind `GraspPush`, nostr connectivity behind `NostrBackend`, and shared helpers consolidated into `utils`
- Fetch the logged-in user's grasp list, code follows, followed repositories, contacts, profile metadata, mute list, and blossom servers via gossip at login instead of the bootstrap relays
- Connect to grasp relays and load the inbox only after the user's grasp list event arrives
- Refresh the checkouts store only when the checkouts settings change
- Restructure the core crate into focused modules for announcements, pull requests, git events, inbox, and upstream state
- Publish nostr events directly through the client with relay acceptance required, removing the grasp push helper and its per-server retry loop so failures surface immediately
- Poll the repository sync drift check every 180 seconds instead of 60
- Track sync status per view instead of globally
- Merge the `PixelAvatar` into the `Avatar` component. Seed user pixel avatars from the public key instead of the display name, so avatars stay stable when a user renames
### Fixed
- Fix the repository view refreshing its mirror from the network while a push is in progress, so the refresh no longer races the push
- Fix opening a repository failing with a `destination already exists` error when two loads raced to clone its mirror, clones are now serialized and later loads reuse the finished clone
- Fix a repository never opening again after an interrupted clone left an unusable mirror directory behind, which is now removed and re-cloned
- Fix signing in with a `bunker://` URI silently generating a new identity instead of erroring when its master key cannot be parsed
- Fix repository sync failing with `state event in purgatory ... doesn't match push` when grasp servers hold branches or tags the local repository lacks
- Fix sync failing with `could not fetch refs/tags/...^{}` on repositories with annotated tags, where the peel entries `git ls-remote` reports for annotated tags were mistaken for missing refs
### Removed
- Remove the light/dark theme pickers and the font size, corner radius, focus ring and shadow settings from the settings dialog; colors and geometry now come from the native theme
- Remove dead code: the unused `login`/`logout` family, the unwired `SyncProgress` pipeline, `merge_pull_request`, inbox mark-read/archive APIs and the wasm32-only code paths
## v0.2.0-alpha - 2026/09/27
### Added
- Show an avatar in each panel's tab, using the repository owner's profile picture when set and a pixel avatar otherwise
- Add a Tab Bar setting to hide the previous/next tab buttons, hidden by default
- Add an Event Fetching Strategy setting, fetching a repository's activity from its announced relays only (Curated) or from every maintainer's relays as well (Uncensored, the default)
### Changed
- Migrate the GPUI foundation to the published `gpui-pre` crates and GPUI Kit 0.6, off the zed and gpui-component git pins
- Use the pixel avatar as the single fallback for a missing picture, sized and rounded to match the other avatars
- Redesign the dock tab bar, using muted grey active tab, added close buttons, double-click to zoom, and removed panel toolbar
- Connect to bootstrap relays on demand instead of at startup
- Fetch profile metadata in batches of 100 authors, applying every requested profile in a single database query
- Prefetch the 500 most recent profiles at startup instead of 200
### Fixed
- Render every avatar at one consistent size, where a surrounding border had shrunk pictures by two pixels and the pixel avatar ignored an explicit size
- Date repositories from their repository state event, so the explore list and open repository views show the latest push instead of the announcement date
- Fix background tasks outliving their view, so a closed repository panel or pull request view stops fetching and publishing on its own
### Removed
- Remove cover note support, the kind-1624 GitWorkshop and `ngit` extension outside the NIP-34
## v0.1.0-alpha - 2026/09/14
Initial alpha release.
### Added
- Create and unlock a passphrase-protected Nostr identity
- Browse and search NIP-34 repositories with All, Popular and Recent filters
- Scan local Git repositories and detect their NIP-34 and GRASP bindings
- Create, publish, clone and open repositories
- Repository view with files, commit history, branches and tags
- Colour-coded commit diffs
- Issues and pull requests with discussions
- Send patches and push branches
- Inbox for repository activity
- Settings for appearance, theme, GRASP servers and repository scan paths
- Release and packaging infrastructure
Generated
+3099 -2012
View File
File diff suppressed because it is too large Load Diff
+22 -18
View File
@@ -4,27 +4,33 @@ members = ["crates/*", "desktop"]
default-members = ["desktop"]
[workspace.package]
version = "0.2.0"
version = "1.0.0"
edition = "2024"
publish = false
[workspace.dependencies]
# GPUI
gpui = { git = "https://github.com/zed-industries/zed" }
gpui_platform = { git = "https://github.com/zed-industries/zed", features = ["font-kit"] }
gpui_platform = { git = "https://github.com/zed-industries/zed", features = ["font-kit", "x11", "wayland"] }
gpui_linux = { git = "https://github.com/zed-industries/zed" }
gpui_windows = { git = "https://github.com/zed-industries/zed" }
gpui_macos = { git = "https://github.com/zed-industries/zed" }
gpui_tokio = { git = "https://github.com/zed-industries/zed" }
reqwest_client = { git = "https://github.com/zed-industries/zed" }
settings = { path = "crates/settings" }
signed_app = { path = "crates/signed_app" }
gpui-component = { git = "https://github.com/longbridge/gpui-component" }
nostr = { git = "https://github.com/rust-nostr/nostr", features = ["nip59", "nip49", "nip44", "os-rng"] }
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" }
nostr-blossom = { git = "https://github.com/rust-nostr/nostr" }
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" }
nostr = { git = "https://github.com/rust-nostr/nostr", rev = "d0a1d67d3c9e5cf9710807a6a414c155a5f47215", features = ["nip59", "nip49", "nip44"] }
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr", rev = "d0a1d67d3c9e5cf9710807a6a414c155a5f47215" }
nostr-memory = { git = "https://github.com/rust-nostr/nostr", rev = "d0a1d67d3c9e5cf9710807a6a414c155a5f47215" }
nostr-blossom = { git = "https://github.com/rust-nostr/nostr", rev = "d0a1d67d3c9e5cf9710807a6a414c155a5f47215" }
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr", rev = "d0a1d67d3c9e5cf9710807a6a414c155a5f47215" }
nostr-connect = { git = "https://github.com/rust-nostr/nostr", rev = "d0a1d67d3c9e5cf9710807a6a414c155a5f47215" }
nostr-sdk = { git = "https://github.com/rust-nostr/nostr", rev = "d0a1d67d3c9e5cf9710807a6a414c155a5f47215" }
gix = { version = "0.88", default-features = false, features = ["sha1", "blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation", "status"] }
gix = { version = "0.86", default-features = false, features = ["sha1", "blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation"] }
chrono = { version = "0.4.38", features = ["wasmbind"] }
smol = "2"
futures = "0.3"
flume = { version = "0.11.1", default-features = false, features = ["async", "select"] }
@@ -36,22 +42,20 @@ log = "0.4"
anyhow = "1.0.44"
webbrowser = "1.0.4"
tracing-subscriber = { version = "0.3.18", features = ["fmt"] }
tracing = "0.1"
errno = { version = "0.3.14", default-features = false }
instant = "0.1"
[patch.crates-io]
# Use stacker's psm version which may have better WASM support
psm = { git = "https://github.com/rust-lang/stacker", branch = "master" }
[profile.release]
strip = true
opt-level = "z"
lto = true
codegen-units = 1
panic = "unwind"
panic = "abort"
[profile.profiling]
inherits = "release"
debug = true
[workspace.lints.clippy]
all = "deny"
perf = "deny"
unwrap_used = "deny"
-1
View File
@@ -1 +0,0 @@
allow-unwrap-in-tests = true
View File
-19
View File
@@ -1,19 +0,0 @@
[package]
name = "metadata"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
signed_state = { path = "../signed_state" }
utils = { path = "../utils" }
nostr-sdk.workspace = true
flume.workspace = true
futures.workspace = true
anyhow.workspace = true
gpui.workspace = true
log.workspace = true
[lints]
workspace = true
-9
View File
@@ -1,9 +0,0 @@
mod profile;
use gpui::{App, AppContext};
pub use profile::{Profile, ProfileDirectory, ProfileEvent, ProfileStore};
/// Initialize the global profile store.
pub fn init(cx: &mut App) {
ProfileStore::set_global(cx.new(ProfileStore::new), cx);
}
-374
View File
@@ -1,374 +0,0 @@
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
use flume::Sender;
use gpui::{
App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Subscription, Task,
};
use nostr_sdk::prelude::*;
use signed_state::{Backend, BackendEvent, sync_bootstrap_only};
use utils::shorten_pubkey;
const BATCH_TIMEOUT: Duration = Duration::from_millis(500);
const REQUEST_CHUNK: usize = 100;
#[derive(Debug, Clone)]
pub struct Profile {
public_key: PublicKey,
metadata: Metadata,
}
impl Profile {
pub fn new(public_key: PublicKey, metadata: Metadata) -> Self {
Self {
public_key,
metadata,
}
}
pub fn public_key(&self) -> PublicKey {
self.public_key
}
pub fn metadata(&self) -> &Metadata {
&self.metadata
}
// Falls back to `name`, then a shortened npub.
pub fn name(&self) -> SharedString {
if let Some(display_name) = self.metadata.display_name.as_ref()
&& !display_name.is_empty()
{
return SharedString::from(display_name.trim().to_owned());
}
if let Some(name) = self.metadata.name.as_ref()
&& !name.is_empty()
{
return SharedString::from(name.trim().to_owned());
}
SharedString::from(shorten_pubkey(self.public_key))
}
pub fn picture(&self) -> Option<SharedString> {
self.metadata
.picture
.as_ref()
.filter(|p| !p.is_empty())
.map(|p| SharedString::from(p.clone()))
}
/// The newest profile per author from metadata events.
fn latest_profiles(events: impl IntoIterator<Item = Event>) -> Vec<Self> {
let mut latest: HashMap<PublicKey, (Timestamp, Metadata)> = HashMap::new();
for event in events {
match latest.get(&event.pubkey) {
Some((created_at, _)) if *created_at >= event.created_at => {}
_ => {
let metadata = Metadata::from_json(&event.content).unwrap_or_default();
latest.insert(event.pubkey, (event.created_at, metadata));
}
}
}
latest
.into_iter()
.map(|(public_key, (_, metadata))| Profile::new(public_key, metadata))
.collect()
}
}
/// Metadata for these authors may have changed in the local database.
#[derive(Debug, Clone)]
pub enum ProfileEvent {
Updated(Vec<PublicKey>),
}
/// Batches metadata requests into relay syncs feeding the local database.
pub struct ProfileStore {
in_flight: RefCell<HashSet<PublicKey>>,
sender: Sender<PublicKey>,
_task: Task<Result<(), anyhow::Error>>,
_subscription: Subscription,
}
struct GlobalProfileStore(Entity<ProfileStore>);
impl Global for GlobalProfileStore {}
impl EventEmitter<ProfileEvent> for ProfileStore {}
impl ProfileStore {
pub(crate) fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalProfileStore>().0.clone()
}
pub(crate) fn set_global(entity: Entity<Self>, cx: &mut App) {
cx.set_global(GlobalProfileStore(entity));
}
pub(crate) fn new(cx: &mut Context<Self>) -> Self {
let backend = Backend::global(cx);
let client = backend.read(cx).client();
let (sender, receiver) = flume::unbounded::<PublicKey>();
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
if let BackendEvent::ProfileUpdates(authors) = event {
this.emit_updated(authors.clone(), cx);
}
});
let task = cx.spawn(async move |this, cx| {
let mut batch: HashSet<PublicKey> = HashSet::new();
loop {
match receiver.recv_async().await {
Ok(public_key) => {
batch.insert(public_key);
}
Err(_) => return Ok(()),
}
// The channel has no async timeout, race the receive against a timer.
let deadline = Instant::now() + BATCH_TIMEOUT;
loop {
let now = Instant::now();
if now >= deadline {
break;
}
let timer = cx.background_executor().timer(deadline - now);
futures::pin_mut!(timer);
let recv = receiver.recv_async();
futures::pin_mut!(recv);
match futures::future::select(recv, timer).await {
futures::future::Either::Left((Ok(public_key), _)) => {
batch.insert(public_key);
}
futures::future::Either::Left((Err(_), _)) => return Ok(()),
futures::future::Either::Right(_) => break,
}
}
let authors: Vec<PublicKey> = batch.drain().collect();
for chunk in authors.chunks(REQUEST_CHUNK) {
let opts = SyncOptions::default();
let filter = Filter::new()
.kind(Kind::Metadata)
.authors(chunk.iter().copied());
if let Err(e) = sync_bootstrap_only(&client, filter, opts).await {
log::warn!("profile fetch failed: {e}");
}
}
// Emit even when the sync failed, the database may hold newer data.
this.update(cx, |this, cx| {
this.emit_updated(authors, cx);
})?;
}
});
Self {
in_flight: RefCell::new(HashSet::new()),
sender,
_task: task,
_subscription: subscription,
}
}
/// Queue a batched relay sync for keys without one in flight.
pub fn fetch(&self, keys: impl IntoIterator<Item = PublicKey>) {
let mut queue = Vec::new();
{
let mut in_flight = self.in_flight.borrow_mut();
for key in keys {
if in_flight.insert(key) {
queue.push(key);
}
}
}
for public_key in queue {
if let Err(e) = self.sender.send(public_key) {
log::warn!("failed to queue profile fetch: {e}");
}
}
}
// Releases the in-flight keys so future fetches can be queued again.
fn emit_updated(&mut self, authors: Vec<PublicKey>, cx: &mut Context<Self>) {
if authors.is_empty() {
return;
}
{
let mut in_flight = self.in_flight.borrow_mut();
for author in &authors {
in_flight.remove(author);
}
}
cx.emit(ProfileEvent::Updated(authors));
}
}
/// Profile cache bound to one panel or screen.
pub struct ProfileDirectory {
profiles: HashMap<PublicKey, Profile>,
pending: RefCell<HashSet<PublicKey>>,
tasks: Vec<Task<()>>,
_subscriptions: Vec<Subscription>,
}
impl ProfileDirectory {
pub fn new(cx: &mut App) -> Entity<Self> {
let store = ProfileStore::global(cx);
cx.new(|cx| {
let subscription =
cx.subscribe(&store, |this: &mut Self, _store, event, cx| match event {
ProfileEvent::Updated(authors) => this.refresh(authors, cx),
});
Self {
profiles: HashMap::new(),
pending: RefCell::new(HashSet::new()),
tasks: Vec::new(),
_subscriptions: vec![subscription],
}
})
}
/// Resolve keys from the local database, queue the rest for a relay sync.
pub fn track<K>(&mut self, keys: K, cx: &mut Context<Self>)
where
K: IntoIterator<Item = PublicKey>,
{
let missing: Vec<PublicKey> = keys
.into_iter()
.filter(|key| {
!self.profiles.contains_key(key)
&& !self.with_pending(|pending| pending.contains(key))
})
.collect();
if missing.is_empty() {
return;
}
self.load(missing, true, cx);
}
/// The profile for a key, or a placeholder that queues a relay sync.
pub fn profile(&self, public_key: &PublicKey, cx: &App) -> Profile {
if let Some(profile) = self.profiles.get(public_key) {
return profile.clone();
}
if self.with_pending(|pending| pending.insert(*public_key)) {
let store = ProfileStore::global(cx);
store.read(cx).fetch([*public_key]);
}
Profile::new(*public_key, Metadata::default())
}
/// Refreshes profiles for keys that are already tracked.
fn refresh(&mut self, authors: &[PublicKey], cx: &mut Context<Self>) {
let tracked: Vec<PublicKey> = authors
.iter()
.copied()
.filter(|key| {
self.profiles.contains_key(key)
|| self.with_pending(|pending| pending.contains(key))
})
.collect();
if tracked.is_empty() {
return;
}
self.load(tracked, false, cx);
}
/// Loads profiles from the local database, queueing a relay sync for any missing keys.
fn load(&mut self, keys: Vec<PublicKey>, queue_sync: bool, cx: &mut Context<Self>) {
// Accept events that arrive while the database query is running.
self.with_pending(|pending| {
pending.extend(keys.iter().copied());
});
let backend = Backend::global(cx);
let client = backend.read(cx).client();
let query_keys = keys.clone();
let work = cx.background_spawn(async move {
let authors = query_keys.iter().copied();
let filter = Filter::new().kind(Kind::Metadata).authors(authors);
let events = client.database().query(filter).await?;
Ok::<_, anyhow::Error>(Profile::latest_profiles(events))
});
self.tasks.push(cx.spawn(async move |this, cx| {
let loaded = work.await;
this.update(cx, |this, cx| {
let remaining = match loaded {
Ok(profiles) => {
let found: HashSet<PublicKey> =
profiles.iter().map(Profile::public_key).collect();
this.insert_loaded(profiles, cx);
keys.into_iter()
.filter(|key| !found.contains(key))
.collect()
}
Err(e) => {
log::warn!("failed to load profiles from the database: {e}");
keys
}
};
if queue_sync && !remaining.is_empty() {
let store = ProfileStore::global(cx);
store.read(cx).fetch(remaining);
}
})
.ok();
}));
}
// Inserts database results, replacing anything loaded earlier.
fn insert_loaded(&mut self, profiles: Vec<Profile>, cx: &mut Context<Self>) {
let mut inserted = false;
for profile in profiles {
let public_key = profile.public_key();
self.profiles.insert(public_key, profile);
self.with_pending(|pending| pending.remove(&public_key));
inserted = true;
}
if inserted {
cx.notify();
}
}
fn with_pending<R, T>(&self, then: T) -> R
where
T: FnOnce(&mut HashSet<PublicKey>) -> R,
{
let mut pending = self.pending.borrow_mut();
then(&mut pending)
}
}
-3
View File
@@ -6,6 +6,3 @@ publish.workspace = true
[dependencies]
dirs = "6"
[lints]
workspace = true
+88 -27
View File
@@ -1,16 +1,23 @@
//! Paths to locations used by Signed.
//!
//! Follows the same pattern as Zed's `paths` crate: platform-correct base
//! directories, resolved once and cached, with an optional custom data dir
//! override for portable/dev installs.
use std::path::PathBuf;
use std::sync::OnceLock;
/// The application name.
///
/// It derives the platform-specific data, config and cache directory paths.
/// The application name, used to derive 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.
/// Lowercased form of [`APP_NAME`], for use in XDG-style paths on
/// Linux/FreeBSD and the macOS `~/.config` fallback.
pub const APP_NAME_LOWERCASE: &str = "signed";
/// A custom data directory override, set only by [`set_custom_data_dir`].
static CUSTOM_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();
/// The resolved data directory.
/// On macOS, this is `~/Library/Application Support/Signed`.
/// On Linux/FreeBSD, this is `$XDG_DATA_HOME/signed`.
@@ -23,27 +30,38 @@ static CURRENT_DATA_DIR: OnceLock<PathBuf> = OnceLock::new();
/// On Windows, this is `%APPDATA%\Signed`.
static CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
fn home_dir() -> PathBuf {
/// 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.
/// Sets a custom directory for all user data, overriding the default data
/// directory. Must be called before any other path operation. The directory
/// is created if it doesn't exist and canonicalized to an absolute path.
///
/// 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())
/// # Panics
///
/// Panics if called after [`data_dir`] or [`config_dir`] was initialized, or
/// if the directory cannot be created/canonicalized.
pub fn set_custom_data_dir(dir: &str) -> &'static PathBuf {
if CURRENT_DATA_DIR.get().is_some() || CONFIG_DIR.get().is_some() {
panic!("set_custom_data_dir called after data_dir or config_dir was initialized");
}
/// 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())
CUSTOM_DATA_DIR.get_or_init(|| {
let path = PathBuf::from(dir);
std::fs::create_dir_all(&path).expect("failed to create custom data directory");
path.canonicalize()
.expect("failed to canonicalize custom data directory")
})
}
fn config_dir() -> &'static PathBuf {
/// Returns the path to the configuration directory.
pub fn config_dir() -> &'static PathBuf {
CONFIG_DIR.get_or_init(|| {
if cfg!(target_os = "windows") {
if let Some(custom_dir) = CUSTOM_DATA_DIR.get() {
custom_dir.join("config")
} else if cfg!(target_os = "windows") {
dirs::config_dir()
.expect("failed to determine RoamingAppData directory")
.join(APP_NAME)
@@ -60,9 +78,12 @@ fn config_dir() -> &'static PathBuf {
})
}
fn data_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") {
if let Some(custom_dir) = CUSTOM_DATA_DIR.get() {
custom_dir.clone()
} else if cfg!(target_os = "macos") {
home_dir()
.join("Library/Application Support")
.join(APP_NAME)
@@ -83,23 +104,63 @@ fn data_dir() -> &'static PathBuf {
})
}
/// Returns the path to the nostr database directory, LMDB.
/// Returns the path to the cache directory.
pub fn cache_dir() -> &'static PathBuf {
static CACHE_DIR: OnceLock<PathBuf> = OnceLock::new();
CACHE_DIR.get_or_init(|| {
if cfg!(target_os = "macos") {
dirs::cache_dir()
.expect("failed to determine caches directory")
.join(APP_NAME)
} else if cfg!(target_os = "windows") {
dirs::cache_dir()
.expect("failed to determine LocalAppData directory")
.join(APP_NAME)
} else if cfg!(any(target_os = "linux", target_os = "freebsd")) {
if let Ok(flatpak_xdg_cache) = std::env::var("FLATPAK_XDG_CACHE_HOME") {
flatpak_xdg_cache.into()
} else {
dirs::cache_dir().expect("failed to determine XDG_CACHE_HOME directory")
}
.join(APP_NAME_LOWERCASE)
} else {
home_dir().join(".cache").join(APP_NAME_LOWERCASE)
}
})
}
/// Returns the path to the logs directory.
pub fn logs_dir() -> &'static PathBuf {
static LOGS_DIR: OnceLock<PathBuf> = OnceLock::new();
LOGS_DIR.get_or_init(|| {
if cfg!(target_os = "macos") {
home_dir().join("Library/Logs").join(APP_NAME)
} else {
data_dir().join("logs")
}
})
}
/// Returns the path to the nostr database directory (LMDB).
pub fn nostr_dir() -> &'static PathBuf {
static NOSTR_DIR: OnceLock<PathBuf> = OnceLock::new();
NOSTR_DIR.get_or_init(|| data_dir().join("nostr"))
}
/// 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.
/// Returns the path to the local git clone cache (grasp mirrors).
pub fn repos_dir() -> &'static PathBuf {
static REPOS_DIR: OnceLock<PathBuf> = OnceLock::new();
REPOS_DIR.get_or_init(|| std::env::temp_dir().join(APP_NAME_LOWERCASE).join("repos"))
REPOS_DIR.get_or_init(|| data_dir().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"))
}
/// Returns the path to the `keymap.json` file.
pub fn keymap_file() -> &'static PathBuf {
static KEYMAP_FILE: OnceLock<PathBuf> = OnceLock::new();
KEYMAP_FILE.get_or_init(|| config_dir().join("keymap.json"))
}
-18
View File
@@ -1,18 +0,0 @@
[package]
name = "settings"
description = "Persisted application settings for Signed."
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
paths = { path = "../paths" }
gpui.workspace = true
serde.workspace = true
serde_json.workspace = true
anyhow.workspace = true
log.workspace = true
[lints]
workspace = true
-5
View File
@@ -1,5 +0,0 @@
mod settings;
mod store;
pub use settings::*;
pub use store::*;
-165
View File
@@ -1,165 +0,0 @@
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
/// 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",
];
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AppearanceMode {
#[default]
System,
Light,
Dark,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EventFetchingStrategy {
/// Only the relays declared in the repository announcement.
Curated,
/// Repository relays plus every maintainer's NIP-65 relays.
#[default]
Uncensored,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GraspServersSettings {
/// Servers offered while the user has not published a grasp list, kind `10317`.
pub default_servers: Vec<String>,
}
impl Default for GraspServersSettings {
fn default() -> Self {
Self {
default_servers: DEFAULT_GRASP_SERVERS
.iter()
.map(|server| (*server).to_owned())
.collect(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct LocalReposSettings {
/// The directories scanned for local git repositories,
/// Defaults:
///
/// - `~/Desktop`
/// - `~/Documents`
pub scan_paths: Vec<PathBuf>,
}
impl Default for LocalReposSettings {
fn default() -> Self {
Self {
scan_paths: vec![paths::desktop_dir(), paths::documents_dir()],
}
}
}
/// A remembered association between a local checkout folder and an announced repository,
/// recorded when the user clones a repository or picks a folder in the New PR panel.
///
/// The panel can then prefill the folder later without asking again.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct CheckoutRecord {
pub path: PathBuf,
/// Repository address as a string, `30617:<pubkey>:<id>`.
pub addr: String,
/// Unix seconds of the last use, for freshest-first ordering.
pub last_used: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CheckoutsSettings {
/// The latest use of a path and repo pair replaces the older record.
pub records: Vec<CheckoutRecord>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct CreateRepositorySettings {
/// The folder the create-repository dialog defaults to, the user's Desktop when unset.
pub default_folder: Option<PathBuf>,
}
/// The complete set of persisted application settings.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
pub appearance: AppearanceMode,
pub event_fetching: EventFetchingStrategy,
pub grasp_servers: GraspServersSettings,
pub local_repos: LocalReposSettings,
pub checkouts: CheckoutsSettings,
pub create_repository: CreateRepositorySettings,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn json_roundtrip_preserves_everything() {
let settings = Settings {
appearance: AppearanceMode::Dark,
event_fetching: EventFetchingStrategy::Curated,
create_repository: CreateRepositorySettings {
default_folder: Some(PathBuf::from("/tmp/repos")),
},
..Default::default()
};
let json = serde_json::to_string(&settings).unwrap();
let parsed: Settings = serde_json::from_str(&json).unwrap();
assert_eq!(parsed, settings);
}
#[test]
fn partial_json_merges_with_defaults() {
let settings: Settings = serde_json::from_str(
r#"{"appearance": "dark", "grasp_servers": {"default_servers": []}}"#,
)
.unwrap();
assert_eq!(settings.appearance, AppearanceMode::Dark);
assert_eq!(settings.grasp_servers.default_servers, Vec::<String>::new());
// Unset fields fall back to their defaults, including the fetching strategy.
assert_eq!(settings.event_fetching, EventFetchingStrategy::Uncensored);
assert_eq!(settings.local_repos, LocalReposSettings::default());
assert_eq!(settings.create_repository.default_folder, None);
}
#[test]
fn legacy_theme_keys_are_ignored() {
let settings: Settings = serde_json::from_str(
r#"{"appearance": "light", "theme": {"radius": 8.0}, "tab_bar": {"hide_navigation_buttons": false}}"#,
)
.unwrap();
assert_eq!(settings.appearance, AppearanceMode::Light);
assert_eq!(
settings,
Settings {
appearance: AppearanceMode::Light,
..Default::default()
}
);
}
#[test]
fn event_fetching_uses_snake_case() {
let json = serde_json::to_string(&EventFetchingStrategy::Curated).unwrap();
assert_eq!(json, r#""curated""#);
let parsed: EventFetchingStrategy = serde_json::from_str(r#""uncensored""#).unwrap();
assert_eq!(parsed, EventFetchingStrategy::Uncensored);
}
}
-156
View File
@@ -1,156 +0,0 @@
use std::path::{Path, PathBuf};
use anyhow::Result;
use gpui::{App, Context, Entity, Global};
use crate::Settings;
struct GlobalSettingsStore(Entity<SettingsStore>);
impl Global for GlobalSettingsStore {}
/// The application settings,
/// loaded from disk at startup and saved whenever they change.
///
/// Installed as a global by the app so any part of the UI can read and edit them.
pub struct SettingsStore {
path: PathBuf,
settings: Settings,
}
impl SettingsStore {
/// Retrieve the global settings store, created at startup by the app.
pub fn global(cx: &App) -> Entity<Self> {
cx.global::<GlobalSettingsStore>().0.clone()
}
/// Retrieve the global settings store if one has been installed.
pub fn try_global(cx: &App) -> Option<Entity<Self>> {
cx.try_global::<GlobalSettingsStore>()
.map(|store| store.0.clone())
}
pub fn set_global(entity: Entity<Self>, cx: &mut App) {
cx.set_global(GlobalSettingsStore(entity));
}
/// Load the settings from `path`,
/// falls back to defaults when the file is missing or unreadable.
///
/// Missing keys merge with the defaults,
/// older settings files keep working as new settings are added.
pub fn new(path: impl AsRef<Path>, _cx: &mut Context<Self>) -> Self {
Self {
path: path.as_ref().to_path_buf(),
settings: Self::load(path.as_ref()),
}
}
/// A snapshot of the current settings.
pub fn settings(&self) -> &Settings {
&self.settings
}
/// Mutate the settings, persist them to disk, and notify observers.
pub fn edit(&mut self, f: impl FnOnce(&mut Settings), cx: &mut Context<Self>) {
f(&mut self.settings);
if let Err(err) = self.save() {
log::error!(
"failed to save settings to {}: {err:#}",
self.path.display()
);
}
cx.notify();
}
/// Read the settings file, merging any missing fields with the defaults.
fn load(path: &Path) -> Settings {
match std::fs::read_to_string(path) {
Ok(contents) => match serde_json::from_str::<Settings>(&contents) {
Ok(settings) => settings,
Err(err) => {
log::error!(
"failed to parse settings file {}: {err}; using defaults",
path.display()
);
Settings::default()
}
},
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Settings::default(),
Err(err) => {
log::error!(
"failed to read settings file {}: {err}; using defaults",
path.display()
);
Settings::default()
}
}
}
/// Write the settings to disk, replacing the file atomically.
fn save(&self) -> Result<()> {
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?;
}
let json = serde_json::to_string_pretty(&self.settings)?;
let tmp = self.path.with_extension("json.tmp");
std::fs::write(&tmp, json)?;
// `rename` cannot replace an existing file on Windows.
if cfg!(target_os = "windows") && self.path.exists() {
std::fs::remove_file(&self.path)?;
}
std::fs::rename(&tmp, &self.path)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
static TEST_FILE_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// A unique, temporary settings path for one test.
fn temp_settings_path() -> PathBuf {
let n = TEST_FILE_COUNTER.fetch_add(1, Ordering::SeqCst);
std::env::temp_dir().join(format!(
"signed-settings-test-{}-{n}.json",
std::process::id()
))
}
fn cleanup(path: &Path) {
let _ = std::fs::remove_file(path);
let _ = std::fs::remove_file(path.with_extension("json.tmp"));
}
#[test]
fn missing_file_loads_defaults() {
let path = temp_settings_path();
cleanup(&path);
let settings = SettingsStore::load(&path);
assert_eq!(settings, Settings::default());
cleanup(&path);
}
#[test]
fn save_and_load_roundtrip() {
let path = temp_settings_path();
cleanup(&path);
let mut expected = Settings::default();
expected.create_repository.default_folder = Some(PathBuf::from("/tmp/repos"));
let store = SettingsStore {
path: path.clone(),
settings: expected.clone(),
};
store.save().unwrap();
assert_eq!(SettingsStore::load(&path), expected);
cleanup(&path);
}
}
-25
View File
@@ -1,25 +0,0 @@
[package]
name = "signed_app"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
metadata = { path = "../metadata" }
paths = { path = "../paths" }
settings = { path = "../settings" }
signed_core = { path = "../signed_core" }
signed_git = { path = "../signed_git" }
signed_nostr = { path = "../signed_nostr" }
signed_state = { path = "../signed_state" }
utils = { path = "../utils" }
gpui.workspace = true
ui = { path = "../ui" }
nostr.workspace = true
anyhow.workspace = true
futures.workspace = true
log.workspace = true
[lints]
workspace = true
-17
View File
@@ -1,17 +0,0 @@
use gpui::App;
use settings::{AppearanceMode, Settings};
use ui::theme::{ThemeVariant, follow_system, set_mode_override};
/// Applies the persisted light/dark/system preference to the kit theme.
pub fn apply_appearance(settings: &Settings, cx: &mut App) {
apply_appearance_mode(settings.appearance, cx);
}
/// Applies one appearance mode to the kit theme.
pub fn apply_appearance_mode(mode: AppearanceMode, cx: &mut App) {
match mode {
AppearanceMode::System => follow_system(cx),
AppearanceMode::Light => set_mode_override(Some(ThemeVariant::Light), cx),
AppearanceMode::Dark => set_mode_override(Some(ThemeVariant::Dark), cx),
}
}
-177
View File
@@ -1,177 +0,0 @@
pub mod helpers;
mod placeholder;
mod sign_in;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, Styled as _, Subscription, Window, div,
};
use helpers::apply_appearance;
use settings::SettingsStore;
use signed_state::{Backend, BackendEvent};
use ui::common::h_flex;
use ui::icons::IconRole;
use ui::layout::panel::PanelRow;
use ui::layout::shell::Shell;
use ui::layout::titlebar::Titlebar;
use ui::theme::ActiveTheme as _;
use ui::toast::{Toast, Toasts};
use crate::app::placeholder::PlaceholderView;
use crate::app::sign_in::SignedOutView;
use crate::explore::ExploreView;
use crate::identity::passphrase::PassphraseDialog;
use crate::shared::log_dropped;
use crate::titlebar::{
CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository, TitlebarView,
bind_repository_shortcuts,
};
use crate::workspace::Workspace;
pub struct AppRoot {
workspace: Entity<Workspace>,
titlebar: Entity<TitlebarView>,
toasts: Entity<Toasts>,
sign_in: Entity<SignedOutView>,
empty: Entity<PlaceholderView>,
passphrase: Option<Entity<PassphraseDialog>>,
_subscriptions: Vec<Subscription>,
}
impl AppRoot {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
bind_repository_shortcuts(cx);
let workspace = cx.new(|_| Workspace::new());
let titlebar = cx.new(|cx| TitlebarView::new(workspace.downgrade(), window, cx));
let toasts = cx.new(|_| Toasts::default());
let sign_in = cx.new(|_| SignedOutView::new());
let empty = cx.new(|_| PlaceholderView::new("Select a repository"));
let backend = Backend::global(cx);
let settings = SettingsStore::global(cx);
let mut subscriptions = Vec::new();
subscriptions.push(cx.subscribe_in(
&backend,
window,
|this, backend, event, window, cx| match event {
BackendEvent::PassphraseRequired => {
this.open_passphrase(cx);
}
BackendEvent::Error(message) => {
this.toasts.update(cx, |toasts, cx| {
toasts.push(Toast::new(message.clone()).icon(IconRole::Warning), cx);
});
}
BackendEvent::SignerChanged => {
this.workspace.update(cx, |workspace, cx| {
workspace.clear(cx);
});
if backend.read(cx).current_user().is_some() {
ExploreView::open(&this.workspace.downgrade(), window, cx);
}
}
_ => {}
},
));
subscriptions.push(cx.observe(&settings, |_this, store, cx| {
let settings = store.read(cx).settings().clone();
apply_appearance(&settings, cx);
}));
let app = cx.entity().downgrade();
window.defer(cx, move |_window, cx| {
if backend.read(cx).passphrase_required() {
log_dropped(app.update(cx, |this, cx| this.open_passphrase(cx)));
}
});
Self {
workspace,
titlebar,
toasts,
sign_in,
empty,
passphrase: None,
_subscriptions: subscriptions,
}
}
fn open_passphrase(&mut self, cx: &mut Context<Self>) {
self.passphrase = Some(PassphraseDialog::new(cx));
cx.notify();
}
}
impl Render for AppRoot {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let backend = Backend::global(cx);
let signed_in = backend.read(cx).current_user().is_some();
let titlebar_view = self.titlebar.read(cx);
let workspace = self.workspace.read(cx);
let main = workspace.active_main();
let prefix = h_flex()
.gap_1()
.child(titlebar_view.render_new_repository())
.child(titlebar_view.render_explore())
.child(titlebar_view.repository_switcher());
let tab_bar = h_flex()
.gap_1()
.when_some(titlebar_view.render_repo_tabs(workspace), |bar, tabs| {
bar.child(tabs)
});
div()
.relative()
.size_full()
.font_family(cx.theme().ui_font())
.text_color(cx.theme().colors.foreground)
.key_context(REPOSITORY_KEY_CONTEXT)
.on_action(cx.listener(|this, action: &SwitchRepository, window, cx| {
this.titlebar.update(cx, |titlebar, cx| {
titlebar.activate_shortcut(action.index, window, cx);
});
}))
.on_action(cx.listener(|this, _: &CreateRepository, window, cx| {
this.titlebar.update(cx, |titlebar, cx| {
titlebar.create_repository(window, cx);
});
}))
.child(
Shell::new("signed-shell")
.titlebar(
Titlebar::new("signed-titlebar")
.prefix(prefix)
.tab_bar(tab_bar)
.when_some(titlebar_view.render_user_menu(cx), |titlebar, menu| {
titlebar.suffix(menu)
}),
)
.panel(
PanelRow::new("signed-panel")
.when_some(main.as_ref(), |row, main| {
row.main(main.clone()).when(workspace.has_details(), |row| {
row.split(self.workspace.clone())
})
})
.when(!main.is_some() && signed_in, |row| {
row.main(self.empty.clone())
})
.when(!main.is_some() && !signed_in, |row| {
row.main(self.sign_in.clone())
}),
)
.toasts(self.toasts.clone()),
)
.child(titlebar_view.palette())
.children(titlebar_view.dialogs())
.when_some(self.passphrase.clone(), |el, view| el.child(view))
}
}
-30
View File
@@ -1,30 +0,0 @@
use gpui::{
App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use ui::empty_state::EmptyState;
use ui::layout::panel::Panel;
/// A tab that stands in for a screen that is not ported yet.
pub struct PlaceholderView {
title: SharedString,
}
impl PlaceholderView {
pub fn new(title: impl Into<SharedString>) -> Self {
Self {
title: title.into(),
}
}
}
impl Panel for PlaceholderView {
fn title(&self, _cx: &App) -> SharedString {
self.title.clone()
}
}
impl Render for PlaceholderView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(EmptyState::new(self.title.clone()))
}
}
-70
View File
@@ -1,70 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, Styled as _,
Window, div,
};
use ui::button::{Button, ButtonVariant};
use ui::common::{StyledExt as _, v_flex};
use ui::layout::panel::Panel;
use crate::identity::import::ImportDialog;
use crate::identity::onboarding::OnboardingDialog;
pub struct SignedOutView {
onboarding: Option<Entity<OnboardingDialog>>,
import: Option<Entity<ImportDialog>>,
}
impl SignedOutView {
pub fn new() -> Self {
Self {
onboarding: None,
import: None,
}
}
fn open_onboarding(&mut self, cx: &mut Context<Self>) {
self.onboarding = Some(OnboardingDialog::new(cx));
cx.notify();
}
fn open_import(&mut self, cx: &mut Context<Self>) {
self.import = Some(ImportDialog::new(cx));
cx.notify();
}
}
impl Panel for SignedOutView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Signed")
}
}
impl Render for SignedOutView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.gap_4()
.child(div().text_2xl().font_semibold().child("Signed"))
.child(
v_flex()
.gap_1()
.w_48()
.child(
Button::new("onboarding")
.label("Join now")
.on_click(cx.listener(|this, _, _, cx| this.open_onboarding(cx))),
)
.child(
Button::new("import")
.label("Import identity")
.variant(ButtonVariant::Secondary)
.on_click(cx.listener(|this, _, _, cx| this.open_import(cx))),
),
)
.when_some(self.onboarding.clone(), |el, view| el.child(view))
.when_some(self.import.clone(), |el, view| el.child(view))
}
}
-184
View File
@@ -1,184 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
StatefulInteractiveElement as _, Styled as _, WeakEntity, div, px,
};
use metadata::ProfileDirectory;
use signed_core::Announcement;
use signed_state::{RepoListStore, Timestamp};
use ui::avatar::Avatar;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
use crate::repo::actions::open_repo_panel;
use crate::repo::helpers::announcement_display_name;
use crate::workspace::Workspace;
const RECENT_COUNT: usize = 10;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(super) enum RepoFilter {
#[default]
All,
Recent,
}
impl RepoFilter {
/// Indices into the store's `announcements` this filter includes, in display order.
pub(super) fn visible(self, store: &RepoListStore, query: &str) -> Vec<usize> {
let announcements = &store.announcements;
let mut indices: Vec<usize> = (0..announcements.len()).collect();
let query = query.trim().to_lowercase();
if !query.is_empty() {
indices.retain(|&ix| {
let announcement = &announcements[ix];
let name = announcement.name.as_deref().unwrap_or(&announcement.id);
name.to_lowercase().contains(&query)
});
}
match self {
Self::All => {}
Self::Recent => indices.truncate(RECENT_COUNT),
}
indices
}
}
pub(super) fn render_card(
ix: usize,
announcement: &Announcement,
last_activity: Option<Timestamp>,
announcements: &[Announcement],
directory: &Entity<ProfileDirectory>,
workspace: &WeakEntity<Workspace>,
cx: &mut gpui::App,
) -> AnyElement {
let owner = directory.read(cx).profile(&announcement.owner, cx);
let owner_name = owner.name();
let workspace = workspace.clone();
let announcement = announcement.clone();
let name = announcement_display_name(&announcement);
let description = announcement
.description
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from("No description"));
let activity = last_activity
.map(relative_time)
.map(|label| SharedString::from(format!("Updated {label}")))
.unwrap_or_default();
let fork_label: Option<SharedString> = announcement.upstream.as_ref().and_then(|upstream| {
let addr = upstream.addr.as_ref()?;
let name = announcements
.iter()
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()));
Some(SharedString::from(format!("forked from {name}")))
});
v_flex()
.id(ix)
.flex_1()
.h_full()
.min_w_0()
.px_3()
.rounded(cx.theme().radius.control)
.border_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
h_flex()
.h_10()
.gap_2()
.child(
div()
.min_w_0()
.text_sm()
.font_semibold()
.whitespace_nowrap()
.text_ellipsis()
.child(name),
)
.when_some(fork_label, |this, label| {
this.child(
h_flex()
.gap_1()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.whitespace_nowrap()
.child(
Icon::named(IconRole::GitBranch)
.size(px(12.))
.color(cx.theme().colors.muted_foreground),
)
.child(label),
)
}),
)
.child(
div()
.h_16()
.min_w_0()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.line_clamp(2)
.child(description),
)
.child(
h_flex()
.h_12()
.gap_2()
.overflow_hidden()
.child(
h_flex()
.gap_2()
.child(
Avatar::new(announcement.owner)
.name(owner_name.clone())
.picture(owner.picture())
.small(),
)
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.whitespace_nowrap()
.child(owner_name),
),
)
.child(
h_flex()
.flex_1()
.justify_end()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.whitespace_nowrap()
.child(activity),
),
)
.on_click(move |_, window, cx| {
open_repo_panel(
&workspace,
&announcement.addr(),
Some(&announcement),
window,
cx,
);
})
.into_any_element()
}
-264
View File
@@ -1,264 +0,0 @@
mod helpers;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ListAlignment, ListState,
ParentElement as _, Render, SharedString, Styled as _, Subscription, WeakEntity, Window, div,
list, px,
};
use helpers::{RepoFilter, render_card};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_state::RepoListStore;
use ui::common::{h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent};
use ui::layout::panel::Panel;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _;
use crate::shared::panels;
use crate::workspace::Workspace;
const COLUMNS: usize = 2;
// Name row, avatar strip, meta row, and their borders and gaps, in px.
const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.;
pub struct ExploreView {
store: Entity<RepoListStore>,
workspace: WeakEntity<Workspace>,
scroll_handle: ListState,
filter: RepoFilter,
/// Indices matching [`Self::filter`] into the store's `announcements`.
visible: Vec<usize>,
search: Entity<InputState>,
/// Profiles for the card owners.
directory: Entity<ProfileDirectory>,
_search_subscription: Subscription,
_store_subscription: Subscription,
}
impl ExploreView {
/// The identifier of the explore panel in the workspace; shown as its tab label.
pub(crate) const PANEL_ID: &'static str = "Explore";
/// Opens the explore panel in the main panel, reusing it when it is already cached.
pub(crate) fn open(workspace: &WeakEntity<Workspace>, window: &mut Window, cx: &mut App) {
panels::open_primary(
workspace,
Self::PANEL_ID,
{
let workspace = workspace.clone();
move |_, cx| cx.new(|cx| Self::new(workspace.clone(), cx))
},
window,
cx,
);
}
pub fn new(workspace: WeakEntity<Workspace>, cx: &mut Context<Self>) -> Self {
let store = RepoListStore::global(cx);
let directory = ProfileDirectory::new(cx);
let weak = cx.entity().downgrade();
let search = InputState::new(cx);
let search_subscription = cx.subscribe(&search, |this, _search, event, cx| {
if matches!(event, InputStateEvent::TextChanged) {
this.rebuild_rows(cx);
}
});
let store_subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild_rows(cx);
});
cx.defer(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| this.rebuild_rows(cx)) {
log::warn!("failed to load explore rows: {error}");
}
});
Self {
store,
workspace,
scroll_handle: ListState::new(1, ListAlignment::Top, px(320.)),
filter: RepoFilter::default(),
visible: Vec::new(),
search,
directory,
_search_subscription: search_subscription,
_store_subscription: store_subscription,
}
}
fn rebuild_rows(&mut self, cx: &mut Context<Self>) {
let filter = self.filter;
let query = self.search.read(cx).value().to_string();
let store = self.store.read(cx);
self.visible = filter.visible(store, &query);
let owners: Vec<PublicKey> = self
.visible
.iter()
.filter_map(|ix| store.announcements.get(*ix))
.map(|announcement| announcement.owner)
.collect();
self.directory.update(cx, |directory, cx| {
directory.track(owners, cx);
});
self.scroll_handle.reset(self.item_count());
cx.notify();
}
/// Header row, plus one row per card row, or the empty state when nothing matches.
fn item_count(&self) -> usize {
if self.visible.is_empty() {
2
} else {
self.visible.len().div_ceil(COLUMNS) + 1
}
}
fn render_header(
search: Entity<InputState>,
filter: RepoFilter,
weak: WeakEntity<Self>,
cx: &App,
) -> AnyElement {
let muted = cx.theme().colors.muted_foreground;
div()
.relative()
.h_96()
.w_full()
.child(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.px_4()
.child(
div().w_full().max_w(px(480.)).child(
Input::new("explore-search", search)
.placeholder("Search...")
.fully_rounded(true)
.prefix(Icon::named(IconRole::Search).small().color(muted)),
),
),
)
.child(
div().absolute().left_0().bottom_0().pl_4().pb_4().child(
Segmented::new("explore-filter", filter)
.options(vec![
SegmentedOption::new(RepoFilter::All, "All")
.icon(Icon::named(IconRole::Grid).small().color(muted)),
SegmentedOption::new(RepoFilter::Recent, "Recent")
.icon(Icon::named(IconRole::Clock).small().color(muted)),
])
.on_change(move |filter, _, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.filter = filter;
this.rebuild_rows(cx);
}) {
log::warn!("failed to change explore filter: {error}");
}
}),
),
)
.into_any_element()
}
}
impl Panel for ExploreView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Explore")
}
fn prefix(&self, cx: &App) -> Option<AnyElement> {
Some(
Icon::named(IconRole::Grid)
.small()
.color(cx.theme().colors.muted_foreground)
.into_any_element(),
)
}
}
impl Render for ExploreView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let store = self.store.read(cx);
let announcements = store.announcements.clone();
let last_activity = store.last_activity.clone();
let visible = self.visible.clone();
let directory = self.directory.clone();
let workspace = self.workspace.clone();
let has_repos = !visible.is_empty();
let search = self.search.clone();
let filter = self.filter;
let weak = cx.entity().downgrade();
let scroll_handle = self.scroll_handle.clone();
div()
.relative()
.size_full()
.child(
list(self.scroll_handle.clone(), move |item, _, cx| {
if item == 0 {
return Self::render_header(search.clone(), filter, weak.clone(), cx);
}
if !has_repos {
return v_flex()
.w_full()
.h(px(320.))
.items_center()
.justify_center()
.child(EmptyState::new("No repositories match your search"))
.into_any_element();
}
let row = item - 1;
let mut cards = Vec::with_capacity(COLUMNS);
for col in 0..COLUMNS {
let Some(&ix) = visible.get(row * COLUMNS + col) else {
break;
};
let Some(announcement) = announcements.get(ix) else {
break;
};
let activity = last_activity.get(&announcement.addr()).copied();
cards.push(render_card(
ix,
announcement,
activity,
&announcements,
&directory,
&workspace,
cx,
));
}
h_flex()
.w_full()
.h(px(CARD_HEIGHT))
.gap_3()
.px_4()
.pt_4()
.children(cards)
.into_any_element()
})
.size_full(),
)
.child(crate::shared::widgets::scroll_overlay(
"explore-scroll",
scroll_handle,
))
}
}
-65
View File
@@ -1,65 +0,0 @@
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
};
use signed_state::Backend;
use ui::button::{Button, ButtonVariant};
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::theme::ActiveTheme as _;
pub struct ExitDialog {
handle: DialogHandle,
}
impl ExitDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
cx.new(|_| Self {
handle: DialogHandle::new(true),
})
}
}
impl Render for ExitDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone();
Dialog::new("exit-dialog")
.handle(self.handle.clone())
.title("Exit Signed?")
.content(|_, cx| {
v_flex()
.child(
div().text_base()
.text_color(cx.theme().colors.muted_foreground)
.child(
"You will be signed out on this device and will need to sign in again on the next session.",
),
)
.into_any_element()
})
.actions(move |_, _| {
let cancel_close = cancel_close.clone();
let confirm_close = confirm_close.clone();
let cancel: AnyElement = Button::new("cancel-exit")
.label("Cancel")
.variant(ButtonVariant::Secondary)
.on_click(move |_, _, cx| cancel_close.close(cx))
.into_any_element();
let exit: AnyElement = Button::new("confirm-exit")
.label("Exit")
.variant(ButtonVariant::Destructive)
.on_click(move |_, _, cx| {
let backend = Backend::global(cx);
backend.update(cx, |backend, cx| backend.sign_out(cx));
confirm_close.close(cx);
})
.into_any_element();
vec![cancel, exit]
})
}
}
-363
View File
@@ -1,363 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Task, Window, div, px,
};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState, InputStateEvent};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row, run_dialog_task_with};
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Stage {
#[default]
Credential,
/// An `nsec` was entered; ask for a passphrase to encrypt it with.
Encrypt,
/// An `ncryptsec` was entered; ask for its passphrase to decrypt it.
Decrypt,
}
/// The credential entered on the first step.
enum Credential {
Nsec(String),
Ncryptsec(String),
Bunker(String),
}
impl Credential {
fn parse(input: &str) -> Option<Self> {
let input = input.trim();
if input.starts_with("nsec1") {
Some(Self::Nsec(input.to_owned()))
} else if input.starts_with("ncryptsec1") {
Some(Self::Ncryptsec(input.to_owned()))
} else if input.starts_with("bunker://") {
Some(Self::Bunker(input.to_owned()))
} else {
None
}
}
}
/// State of the import dialog, so the current step and async results can be rendered.
#[derive(Default)]
pub struct ImportState {
stage: Stage,
credential: String,
progress: DialogProgress,
}
pub struct ImportDialog {
handle: DialogHandle,
secret_input: Entity<InputState>,
pass_input: Entity<InputState>,
repass_input: Entity<InputState>,
state: Entity<ImportState>,
_subscriptions: Vec<Subscription>,
}
impl ImportDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
let handle = DialogHandle::new(true);
let state = cx.new(|_| ImportState::default());
let secret_input = InputState::new(cx);
let pass_input = InputState::builder().password().build(cx);
let repass_input = InputState::builder().password().build(cx);
cx.new(|cx| {
let mut subscriptions = Vec::new();
for input in [&secret_input, &pass_input, &repass_input] {
let secret_input = secret_input.clone();
let pass_input = pass_input.clone();
let repass_input = repass_input.clone();
let state = state.clone();
let handle = handle.clone();
subscriptions.push(cx.subscribe(input, move |_this, _input, event, cx| {
if matches!(event, InputStateEvent::Submitted) {
submit(
&secret_input,
&pass_input,
&repass_input,
&state,
&handle,
cx,
);
}
}));
}
Self {
handle,
secret_input,
pass_input,
repass_input,
state,
_subscriptions: subscriptions,
}
})
}
}
impl Render for ImportDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let state = self.state.clone();
let secret_input = self.secret_input.clone();
let pass_input = self.pass_input.clone();
let repass_input = self.repass_input.clone();
let action_state = state.clone();
let action_secret = secret_input.clone();
let action_pass = pass_input.clone();
let action_repass = repass_input.clone();
let action_close = self.handle.clone();
Dialog::new("import-dialog")
.handle(self.handle.clone())
.min_width(px(520.))
.title("Import identity")
.content(move |_window, cx| {
let state = state.read(cx);
let stage = state.stage;
let description = match stage {
Stage::Credential => {
"Paste the secret key or bunker URI of an existing identity."
}
Stage::Encrypt => "Choose a passphrase to encrypt your key on this device.",
Stage::Decrypt => "Enter the passphrase used to encrypt this key.",
};
let form = match stage {
Stage::Credential => v_flex().gap_3().child(
Field::new("secret-field", "Secret key or bunker URI")
.child(Input::new("secret-input", secret_input.clone())),
),
Stage::Encrypt => v_flex()
.gap_3()
.child(
Field::new("passphrase-field", "Passphrase")
.child(Input::new("passphrase-input", pass_input.clone())),
)
.child(
Field::new("repeat-field", "Repeat passphrase")
.child(Input::new("repeat-input", repass_input.clone())),
),
Stage::Decrypt => v_flex().gap_3().child(
Field::new("passphrase-field", "Passphrase")
.child(Input::new("passphrase-input", pass_input.clone())),
),
};
v_flex()
.gap_3()
.child(
div()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child(description),
)
.child(form)
.when_some(error_row(&state.progress.error, cx), |el, error| {
el.child(error)
})
.into_any_element()
})
.actions(move |_, cx| {
let state = action_state.read(cx);
let busy = state.progress.busy;
let label = match state.stage {
Stage::Credential => "Continue",
Stage::Encrypt => "Import identity",
Stage::Decrypt => "Unlock",
};
let secret = action_secret.clone();
let pass = action_pass.clone();
let repass = action_repass.clone();
let state = action_state.clone();
let handle = action_close.clone();
let import: AnyElement = Button::new("import-identity")
.label(label)
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
submit(&secret, &pass, &repass, &state, &handle, cx);
})
.into_any_element();
vec![import]
})
}
}
fn submit(
secret_input: &Entity<InputState>,
pass_input: &Entity<InputState>,
repass_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
if state.read(cx).progress.busy {
return;
}
match state.read(cx).stage {
Stage::Credential => start_import(secret_input, state, handle, cx),
Stage::Encrypt => import_nsec(pass_input, repass_input, state, handle, cx),
Stage::Decrypt => import_ncryptsec(pass_input, state, handle, cx),
}
}
/// Parses the entered credential and either moves to the passphrase step or connects to a bunker.
fn start_import(
secret_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let credential = match Credential::parse(secret_input.read(cx).value()) {
Some(credential) => credential,
None => {
state.update(cx, |state, cx| {
state
.progress
.fail("Enter an nsec, ncryptsec or bunker:// URI");
cx.notify();
});
return;
}
};
match credential {
Credential::Nsec(secret) => {
state.update(cx, |state, cx| {
state.credential = secret;
state.stage = Stage::Encrypt;
state.progress.error = None;
cx.notify();
});
}
Credential::Ncryptsec(secret) => {
state.update(cx, |state, cx| {
state.credential = secret;
state.stage = Stage::Decrypt;
state.progress.error = None;
cx.notify();
});
}
Credential::Bunker(uri) => {
state.update(cx, |state, cx| {
state.progress.begin();
cx.notify();
});
let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.import_bunker(&uri, cx));
finish_import(task, state, handle, cx);
}
}
}
/// Encrypts the entered `nsec` with the passphrase and signs in with it.
fn import_nsec(
pass_input: &Entity<InputState>,
repass_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let backend = Backend::global(cx);
let nsec = state.read(cx).credential.clone();
let pass = pass_input.read(cx).value().to_string();
let repass = repass_input.read(cx).value().to_string();
if pass.is_empty() {
state.update(cx, |state, cx| {
state.progress.fail("Passphrase must not be empty");
cx.notify();
});
return;
}
if pass != repass {
state.update(cx, |state, cx| {
state.progress.fail("Passphrases do not match");
cx.notify();
});
return;
}
state.update(cx, |state, cx| {
state.progress.begin();
cx.notify();
});
let task = backend.update(cx, |backend, cx| backend.import_nsec(&nsec, &pass, cx));
finish_import(task, state, handle, cx);
}
/// Decrypts the entered `ncryptsec` with the passphrase and signs in with it.
fn import_ncryptsec(
pass_input: &Entity<InputState>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let backend = Backend::global(cx);
let ncryptsec = state.read(cx).credential.clone();
let pass = pass_input.read(cx).value().to_string();
if pass.is_empty() {
state.update(cx, |state, cx| {
state.progress.fail("Passphrase must not be empty");
cx.notify();
});
return;
}
state.update(cx, |state, cx| {
state.progress.begin();
cx.notify();
});
let task = backend.update(cx, |backend, cx| {
backend.import_ncryptsec(&ncryptsec, &pass, cx)
});
finish_import(task, state, handle, cx);
}
/// Runs the import task to completion, closing the dialog on success.
fn finish_import<T: 'static>(
task: Task<Result<T, anyhow::Error>>,
state: &Entity<ImportState>,
handle: &DialogHandle,
cx: &mut App,
) {
let handle = handle.clone();
let state = state.clone();
run_dialog_task_with(
task,
cx,
move |_, cx| cx.update(|cx| handle.close(cx)),
move |error, cx| {
state.update(cx, |state, cx| {
state.progress.fail(error.to_string());
cx.notify();
});
},
);
}
-4
View File
@@ -1,4 +0,0 @@
pub mod exit;
pub mod import;
pub mod onboarding;
pub mod passphrase;
@@ -1,125 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div, px,
};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row, run_dialog_task};
pub struct OnboardingDialog {
handle: DialogHandle,
name_input: Entity<InputState>,
pass_input: Entity<InputState>,
repass_input: Entity<InputState>,
state: Entity<DialogProgress>,
}
impl OnboardingDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
let state = cx.new(|_| DialogProgress::default());
let name_input = InputState::new(cx);
let pass_input = InputState::builder().password().build(cx);
let repass_input = InputState::builder().password().build(cx);
cx.new(|_| Self {
handle: DialogHandle::new(true),
name_input,
pass_input,
repass_input,
state,
})
}
fn create_identity(&mut self, cx: &mut Context<Self>) {
if self.state.read(cx).busy {
return;
}
let name = self.name_input.read(cx).value().to_string();
let pass = self.pass_input.read(cx).value().to_string();
let repass = self.repass_input.read(cx).value().to_string();
if pass != repass {
self.state.update(cx, |state, cx| {
state.fail("Passphrases do not match");
cx.notify();
});
return;
}
self.state.update(cx, |state, cx| {
state.begin();
cx.notify();
});
let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.create_identity(&name, &pass, cx));
run_dialog_task(task, &self.state, &self.handle, cx);
}
}
impl Render for OnboardingDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let name_input = self.name_input.clone();
let pass_input = self.pass_input.clone();
let repass_input = self.repass_input.clone();
let state = self.state.clone();
let action_state = state.clone();
let this = cx.entity().downgrade();
Dialog::new("onboarding-dialog")
.handle(self.handle.clone())
.min_width(px(520.))
.title("Create identity")
.content(move |_window, cx| {
let progress = state.read(cx);
v_flex()
.gap_3()
.child(
div()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child("Set up your Signed identity to get started."),
)
.child(
Field::new("name-field", "Name")
.description("Max 255 characters")
.child(Input::new("name-input", name_input.clone())),
)
.child(
Field::new("passphrase-field", "Passphrase")
.child(Input::new("passphrase-input", pass_input.clone())),
)
.child(
Field::new("repeat-field", "Repeat passphrase")
.child(Input::new("repeat-input", repass_input.clone())),
)
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let this = this.clone();
let create: AnyElement = Button::new("create-identity")
.label("Create new identity")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.create_identity(cx)),
);
})
.into_any_element();
vec![create]
})
}
}
@@ -1,118 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Subscription, Window, px,
};
use signed_state::Backend;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState, InputStateEvent};
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task};
pub struct PassphraseDialog {
handle: DialogHandle,
pass_input: Entity<InputState>,
state: Entity<DialogProgress>,
_enter_subscription: Subscription,
}
impl PassphraseDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
let state = cx.new(|_| DialogProgress::default());
let pass_input = InputState::builder().password().build(cx);
cx.new(|cx| {
let enter_subscription =
cx.subscribe(&pass_input, |this: &mut Self, _input, event, cx| {
if matches!(event, InputStateEvent::Submitted) {
this.unlock(cx);
}
});
Self {
handle: DialogHandle::new(true),
pass_input,
state,
_enter_subscription: enter_subscription,
}
})
}
fn unlock(&mut self, cx: &mut Context<Self>) {
if self.state.read(cx).busy {
return;
}
let pass = self.pass_input.read(cx).value().to_string();
if pass.is_empty() {
self.state.update(cx, |state, cx| {
state.fail("Passphrase must not be empty");
cx.notify();
});
return;
}
self.state.update(cx, |state, cx| {
state.begin();
cx.notify();
});
let backend = Backend::global(cx);
let task = backend.update(cx, |backend, cx| backend.restore_with_passphrase(&pass, cx));
run_dialog_task(task, &self.state, &self.handle, cx);
}
}
impl Render for PassphraseDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let pass_input = self.pass_input.clone();
let state = self.state.clone();
let action_state = state.clone();
let this = cx.entity().downgrade();
Dialog::new("passphrase-dialog")
.handle(self.handle.clone())
.close_on_escape(false)
.close_on_backdrop(false)
.min_width(px(420.))
.title("Unlock your identity")
.content(move |_window, cx| {
let progress = state.read(cx);
v_flex()
.gap_3()
.child(
Field::new(
"passphrase-field",
"Enter the passphrase used to encrypt this identity.",
)
.child(Input::new("passphrase-input", pass_input.clone())),
)
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.when_some(push_steps_row(&progress.push_steps, cx), |el, steps| {
el.child(steps)
})
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let this = this.clone();
let unlock: AnyElement = Button::new("unlock")
.label("Unlock")
.icon(Icon::named(IconRole::Unlock))
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.unlock(cx)));
})
.into_any_element();
vec![unlock]
})
}
}
-166
View File
@@ -1,166 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
SharedString, Stateful, Styled as _, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Event, Kind, PublicKey};
use ui::avatar::Avatar;
use ui::badge::Badge;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
pub fn repo_header(id: SharedString, name: SharedString, unread: usize) -> AnyElement {
h_flex()
.h_12()
.w_full()
.gap_2()
.child(
div()
.min_w_0()
.text_base()
.whitespace_nowrap()
.text_ellipsis()
.child(name),
)
.when(unread > 0, |this| {
this.child(Badge::new(id.clone(), unread.to_string()))
})
.into_any_element()
}
pub fn empty_section_row(cx: &App) -> AnyElement {
h_flex()
.h_12()
.w_full()
.px_3()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.bg(cx.theme().colors.secondary)
.rounded(cx.theme().radius.control)
.child(SharedString::from("No activity yet."))
.into_any_element()
}
#[allow(clippy::too_many_arguments)]
pub fn thread(
prefix: &'static str,
ix: usize,
title: SharedString,
unread: bool,
first: bool,
last: bool,
events: Vec<Event>,
me: Option<PublicKey>,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> Stateful<Div> {
let mut timeline = v_flex().gap_2().w_full();
for event in events {
timeline = timeline.child(sub_activity(&event, me, directory, cx));
}
v_flex()
.id((prefix, ix))
.w_full()
.px_3()
.py_2()
.gap_2()
.bg(cx.theme().colors.secondary)
.when(first, |this| this.rounded_t(cx.theme().radius.control))
.when(last, |this| this.rounded_b(cx.theme().radius.control))
.when(!last, |this| {
this.border_b_1().border_color(cx.theme().colors.background)
})
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
h_flex()
.gap_2()
.text_base()
.child(
h_flex()
.size_6()
.flex_shrink_0()
.items_center()
.justify_center()
.child(
Icon::named(IconRole::Inbox)
.small()
.color(cx.theme().colors.muted_foreground),
),
)
.child(
div()
.min_w_0()
.whitespace_nowrap()
.text_ellipsis()
.child(title),
)
.child(div().flex_1())
.when(unread, |this| {
this.child(
ui::status_dot::StatusDot::new(("inbox-unread", ix))
.variant(ui::status_dot::StatusDotVariant::Accent),
)
}),
)
.child(timeline)
}
fn sub_activity(
event: &Event,
me: Option<PublicKey>,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let profile = directory.read(cx).profile(&event.pubkey, cx);
let name = if Some(event.pubkey) == me {
SharedString::from("You")
} else {
profile.name()
};
h_flex()
.w_full()
.gap_2()
.child(div().w_6().flex_shrink_0())
.child(
h_flex()
.flex_1()
.min_w_0()
.gap_1()
.text_xs()
.child(
Avatar::new(event.pubkey)
.name(name.clone())
.picture(profile.picture())
.small(),
)
.child(name)
.child(SharedString::from(activity_phrase(event.kind)))
.child(div().flex_1())
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(relative_time(event.created_at))),
),
)
.into_any_element()
}
fn activity_phrase(kind: Kind) -> &'static str {
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",
}
}
-496
View File
@@ -1,496 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity,
Window, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp};
use signed_core::{InboxItem, InboxReadState, RepoAddr};
use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, RepoListStore};
use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::Button;
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
mod helpers;
use helpers::{empty_section_row, repo_header, thread};
use crate::repo::actions::{RepoItem, open_repo_item};
use crate::repo::helpers::announcement_display_name;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace;
const MAX_SUB_ACTIVITIES: usize = 5;
#[derive(Clone, Copy)]
enum InboxRow {
Repo(usize),
Entry(usize, usize),
Empty,
}
struct InboxSection {
address: Option<RepoAddr>,
unread: usize,
entries: Vec<usize>,
latest: Timestamp,
}
pub struct InboxView {
workspace: WeakEntity<Workspace>,
threads: Arc<Vec<InboxItem>>,
sections: Arc<Vec<InboxSection>>,
rows: Arc<Vec<InboxRow>>,
state: InboxReadState,
state_loaded: bool,
refresh: RefreshGate,
tasks: Vec<Task<Result<(), Error>>>,
directory: Entity<ProfileDirectory>,
/// The last refresh failure, shown inline until the next refresh succeeds.
error: Option<SharedString>,
_subscriptions: Vec<Subscription>,
}
impl InboxView {
pub fn new(workspace: WeakEntity<Workspace>, 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 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);
}));
subscriptions.push(cx.observe(&repos, |this, _repos, cx| {
this.rebuild(cx);
cx.notify();
}));
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 {
workspace,
threads: Arc::new(Vec::new()),
sections: Arc::new(Vec::new()),
rows: Arc::new(Vec::new()),
state: InboxReadState::default(),
state_loaded: false,
refresh: RefreshGate::default(),
tasks: vec![],
directory: ProfileDirectory::new(cx),
error: None,
_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::RepoUpdates(_) | BackendEvent::Synced => 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 || self.refresh.request() != RefreshRequest::Schedule {
return;
}
self.run_refresh(cx);
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn run_refresh(&mut self, cx: &mut Context<Self>) {
self.refresh.begin();
let backend = Backend::global(cx);
let (me, client) = {
let backend = backend.read(cx);
(backend.current_user(), backend.client())
};
let Some(me) = me else {
self.refresh.abort();
return;
};
let state = self.state.clone();
let work = cx.background_spawn(async move { Inbox::query(&client, me, &state).await });
self.push_task(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.error = Some(error.to_string().into());
this.refresh.abort();
cx.notify();
});
}
};
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.error = None;
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.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);
let mut keys: Vec<PublicKey> = self
.threads
.iter()
.flat_map(|item| item.events.iter().map(|event| event.pubkey))
.collect();
keys.sort_by_key(PublicKey::to_hex);
keys.dedup();
self.directory
.update(cx, |directory, cx| directory.track(keys, cx));
}
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.state = InboxReadState::default();
self.state_loaded = false;
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.workspace, &address, None, item, window, cx);
}
fn render_entry(&self, ix: usize, cx: &mut 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();
};
let name = repo_name(section.address.as_ref(), cx);
let id = SharedString::from(format!(
"inbox-unread:{}",
section
.address
.as_ref()
.map(ToString::to_string)
.unwrap_or_default()
));
repo_header(id, name, section.unread)
}
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();
let me = Backend::global(cx).read(cx).current_user();
thread(
"inbox-row",
ix,
SharedString::from(item.title()),
item.is_unread(),
first,
last,
item.timeline(MAX_SUB_ACTIVITIES),
me,
&self.directory,
cx,
)
.on_click(cx.listener(move |this, _ev, window, cx| {
this.open(root, kind, address.clone(), window, cx)
}))
.into_any_element()
}
}
}
}
impl Panel for InboxView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Inbox")
}
}
impl Render for InboxView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let rows = self.rows.clone();
let mut children = Vec::with_capacity(rows.len());
for ix in 0..rows.len() {
children.push(self.render_entry(ix, cx));
}
v_flex()
.size_full()
.child(
h_flex()
.px_4()
.h_12()
.w_full()
.gap_2()
.child(
div()
.text_sm()
.font_semibold()
.child(SharedString::from("Inbox")),
)
.child(div().flex_1())
.child(
Button::new("mark-all")
.icon(Icon::named(IconRole::Check))
.label("Mark all read")
.on_click(cx.listener(|this, _, _, cx| this.mark_all_read(cx))),
),
)
.when_some(self.error.clone(), |this, error| {
let weak = cx.entity().downgrade();
this.child(
Alert::new("inbox-error")
.severity(AlertSeverity::Danger)
.title("Inbox")
.message(error)
.style(AlertStyle::Inline)
.on_dismiss(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.error = None;
cx.notify();
}) {
log::warn!("failed to dismiss inbox error: {error}");
}
}),
)
})
.child(
div()
.relative()
.flex_1()
.min_h_0()
.px_4()
.child(if rows.is_empty() {
empty_state("You're all caught up.")
} else {
ScrollArea::new("inbox-scroll")
.flex_1()
.child(v_flex().gap_2().py_2().children(children))
.into_any_element()
}),
)
.into_any_element()
}
}
fn repo_name(addr: Option<&RepoAddr>, cx: &App) -> SharedString {
let Some(addr) = addr else {
return SharedString::from("Untitled");
};
RepoListStore::global(cx)
.read(cx)
.announcements
.iter()
.find(|announcement| announcement.addr() == *addr)
.map(announcement_display_name)
.unwrap_or_else(|| SharedString::from("Untitled"))
}
-210
View File
@@ -1,210 +0,0 @@
use gpui::{
App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,
ScrollHandle, SharedString, Styled as _, Subscription, Window, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::EventId;
use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::input::InputState;
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::theme::ActiveTheme as _;
use utils::relative_time;
use crate::issues::helpers::{comment_form, comments_section, issue_roots, sidebar_section};
use crate::shared::widgets::status_badge;
pub struct IssueDetailView {
store: Entity<RepoStore>,
issue_id: EventId,
comment_input: Entity<InputState>,
/// Profiles for the author, commenters and the repository owner.
directory: Entity<ProfileDirectory>,
scroll_handle: ScrollHandle,
_subscription: Subscription,
}
impl IssueDetailView {
pub fn new(store: Entity<RepoStore>, issue_id: EventId, cx: &mut Context<Self>) -> Self {
let comment_input = InputState::builder().multiline().build(cx);
let subscription = cx.observe(&store, |this, _store, cx| {
this.track_participants(cx);
cx.notify();
});
let directory = ProfileDirectory::new(cx);
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.track_participants(cx)));
});
Self {
store,
issue_id,
comment_input,
directory,
scroll_handle: ScrollHandle::new(),
_subscription: subscription,
}
}
/// Track the issue author, everyone who commented and the repository owner.
fn track_participants(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx);
let author = store
.issues
.iter()
.find(|issue| issue.id == self.issue_id)
.map(|issue| issue.pubkey);
let owner = store.announcement.as_ref().map(|a| a.owner);
let comments: Vec<_> = store
.comments_of(&self.issue_id)
.map(|comment| comment.pubkey)
.collect();
crate::shared::track_event_participants(
author,
owner,
comments.into_iter(),
&self.directory,
cx,
);
}
}
impl Panel for IssueDetailView {
fn title(&self, _cx: &App) -> SharedString {
let hex = self.issue_id.to_hex();
let short = hex.get(..8).unwrap_or(&hex);
SharedString::from(format!("Issue {short}"))
}
fn loading(&self, cx: &App) -> bool {
!self.store.read(cx).loaded
}
}
impl Render for IssueDetailView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let store = self.store.read(cx);
let Some(issue) = store.issues.iter().find(|issue| issue.id == self.issue_id) else {
// A not-yet-loaded store is not the same as a missing issue.
return if store.loaded {
crate::shared::widgets::empty_state("Issue not found")
} else {
crate::shared::widgets::centered_spinner("issue-loading")
};
};
let (title, author, status, age, issue_id, content, pubkey) = {
let profile = self.directory.read(cx).profile(&issue.pubkey, cx);
let content = if issue.content.is_empty() {
SharedString::from("No description provided.")
} else {
SharedString::from(&issue.content)
};
(
issue.activity_subject(),
profile.name(),
store.status_of(issue),
relative_time(issue.created_at),
issue.id,
content,
issue.pubkey,
)
};
let picture = self.directory.read(cx).profile(&pubkey, cx).picture();
h_flex()
.id("issue-detail")
.size_full()
.child(
ScrollArea::new("issue-detail-scroll")
.handle(self.scroll_handle.clone())
.flex_1()
.min_w_0()
.child(
v_flex()
.p_4()
.gap_6()
.child(
h_flex().gap_2().child(status_badge(status)).child(
div()
.flex_1()
.min_w_0()
.text_sm()
.font_semibold()
.child(title),
),
)
.child(
v_flex()
.gap_8()
.child(
v_flex()
.gap_4()
.child(
h_flex()
.gap_2()
.text_base()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(pubkey)
.name(author.clone())
.picture(picture)
.small(),
)
.child(author),
)
.child(
div()
.text_color(
cx.theme().colors.muted_foreground,
)
.child("opened"),
)
.child(
div()
.text_color(
cx.theme().colors.muted_foreground,
)
.child(SharedString::from(age)),
),
)
.child(div().text_base().child(content)),
)
.child(comments_section(
&self.store,
issue_id,
&self.directory,
cx,
))
.child(comment_form(
&self.store,
issue_id,
issue_roots,
&self.comment_input,
"comment",
cx,
)),
),
),
)
.child(sidebar_section(
&self.store,
issue_id,
issue_roots,
true,
&self.directory,
cx,
))
.into_any_element()
}
}
-274
View File
@@ -1,274 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Entity, IntoElement, ParentElement as _, SharedString, Styled as _, div, px,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Event, EventId, PublicKey};
use signed_core::RepoStatus;
use signed_state::RepoStore;
use ui::avatar::Avatar;
use ui::badge::{Badge, BadgeVariant};
use ui::button::Button;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use utils::relative_time;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IssueFilter {
All,
Open,
Closed,
}
impl IssueFilter {
pub(crate) fn matches(self, status: RepoStatus) -> bool {
match self {
Self::All => true,
Self::Open => status == RepoStatus::Open,
Self::Closed => matches!(status, RepoStatus::Closed | RepoStatus::Applied),
}
}
}
/// 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)
}
pub(crate) fn issue_roots(store: &RepoStore) -> &[Event] {
&store.issues
}
pub(crate) fn pr_roots(store: &RepoStore) -> &[Event] {
&store.pull_requests
}
pub(crate) fn sidebar_section(
store: &Entity<RepoStore>,
id: EventId,
roots: fn(&RepoStore) -> &[Event],
top_gap: bool,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let store = store.read(cx);
let Some(root) = roots(store).iter().find(|event| event.id == id) else {
return div().into_any_element();
};
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();
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_1()
.border_color(cx.theme().colors.border)
.child(
v_flex()
.when(top_gap, |this| this.mt_4())
.gap_2()
.child(crate::shared::widgets::section_label("Participants", cx))
.children(participants.iter().map(|pubkey| {
let profile = directory.read(cx).profile(pubkey, cx);
let name = profile.name();
h_flex()
.gap_1()
.child(
Avatar::new(*pubkey)
.name(name.clone())
.picture(profile.picture())
.small(),
)
.child(div().text_base().text_ellipsis().child(name))
.into_any_element()
})),
)
.child(
v_flex()
.gap_2()
.child(crate::shared::widgets::section_label("Labels", cx))
.map(|this| {
if labels.is_empty() {
this.child(
div()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child("None yet."),
)
} else {
this.child(v_flex().gap_1().children(labels.iter().map(|label| {
Badge::new(SharedString::from(format!("label:{label}")), label.clone())
.variant(BadgeVariant::Outline)
})))
}
}),
)
.into_any_element()
}
pub(crate) fn comments_section(
store: &Entity<RepoStore>,
root: EventId,
directory: &Entity<ProfileDirectory>,
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_medium().child(title))
.children(comments.iter().map(|comment| {
let profile = directory.read(cx).profile(&comment.pubkey, cx);
let author = profile.name();
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().colors.border)
.rounded(cx.theme().radius.control)
.child(
h_flex()
.gap_2()
.text_base()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(comment.pubkey)
.name(author.clone())
.picture(profile.picture())
.small(),
)
.child(author),
)
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child("commented"),
)
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(age)),
),
)
.child(div().text_base().child(content))
}))
.into_any_element()
}
pub(crate) fn comment_form(
store: &Entity<RepoStore>,
root: EventId,
roots: fn(&RepoStore) -> &[Event],
comment_input: &Entity<InputState>,
button_id: &'static str,
cx: &App,
) -> AnyElement {
let comment_input = comment_input.clone();
let store = store.clone();
v_flex()
.gap_2()
.child(
Input::new("comment-input", comment_input.clone())
.rows(4)
.placeholder("Leave a comment..."),
)
.child(
h_flex()
.justify_between()
.child(
h_flex()
.gap_1()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(
Icon::named(IconRole::Markdown)
.size(px(12.))
.color(cx.theme().colors.muted_foreground),
)
.child("Markdown is supported"),
)
.child(
Button::new(button_id)
.label("Comment")
.tooltip(Tooltip::text("Post comment"))
.on_click(move |_, 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()
}
-244
View File
@@ -1,244 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div,
};
use helpers::{IssueFilter, StatusCounts, filter_by_status};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_core::GitEvent;
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
use std::rc::Rc;
use self::detail::IssueDetailView;
use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow};
use crate::shared::panels;
use crate::workspace::Workspace;
pub mod detail;
pub(crate) mod helpers;
pub mod new_issue;
pub struct IssuesView {
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
new_issue: Option<Entity<new_issue::NewIssueDialog>>,
filter: IssueFilter,
visible_issues: Vec<usize>,
counts: StatusCounts,
// A filter change notifies even when the visible rows are unchanged.
synced_filter: IssueFilter,
scroll_handle: UniformListScrollHandle,
/// Profiles for issue authors and the repository owner.
directory: Entity<ProfileDirectory>,
_subscription: Subscription,
}
impl IssuesView {
pub fn new(
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
cx: &mut Context<Self>,
) -> Self {
let subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild(cx);
});
let weak = cx.entity().downgrade();
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.rebuild(cx)));
});
Self {
workspace,
store: store.clone(),
new_issue: None,
filter: IssueFilter::Open,
visible_issues: Vec::new(),
counts: StatusCounts::default(),
synced_filter: IssueFilter::Open,
scroll_handle: UniformListScrollHandle::new(),
directory: ProfileDirectory::new(cx),
_subscription: subscription,
}
}
fn open_new_issue(&mut self, cx: &mut Context<Self>) {
self.new_issue = Some(new_issue::NewIssueDialog::new(self.store.clone(), cx));
cx.notify();
}
/// Total number of issues across all statuses, for the sidebar label.
pub fn total_count(&self) -> usize {
self.counts.total
}
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 store = self.store.read(cx);
let mut keys: Vec<PublicKey> = store.issues.iter().map(|issue| issue.pubkey).collect();
if let Some(owner) = store
.announcement
.as_ref()
.map(|announcement| announcement.owner)
{
keys.push(owner);
}
self.directory.update(cx, |directory, cx| {
directory.track(keys, cx);
});
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.synced_filter = filter;
self.visible_issues = visible_issues;
self.counts = counts;
cx.notify();
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let counts = self.counts;
let muted = cx.theme().colors.muted_foreground;
let weak = cx.entity().downgrade();
crate::shared::event_list::filter_toolbar(
cx,
[
Segmented::new("issue-filter", self.filter)
.options(vec![
SegmentedOption::new(IssueFilter::All, format!("All ({})", counts.total))
.icon(Icon::named(IconRole::GitIssueDone).color(muted)),
SegmentedOption::new(IssueFilter::Open, format!("Open ({})", counts.open))
.icon(Icon::named(IconRole::GitIssueOngoing).color(muted)),
SegmentedOption::new(
IssueFilter::Closed,
format!("Closed ({})", counts.closed),
)
.icon(Icon::named(IconRole::GitIssueClosed).color(muted)),
])
.on_change(move |filter, _, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.filter = filter;
this.rebuild(cx);
}) {
log::warn!("failed to switch issue filter: {error}");
}
})
.into_any_element(),
div().flex_1().into_any_element(),
Button::new("new-issue")
.label("New issue")
.icon(Icon::named(IconRole::CirclePlus))
.on_click(cx.listener(|this, _, _, cx| {
this.open_new_issue(cx);
}))
.into_any_element(),
],
)
}
}
impl Panel for IssuesView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Issues")
}
}
impl Render for IssuesView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let filter = self.filter;
let visible_issues = self.visible_issues.clone();
let directory = self.directory.clone();
let store = self.store.clone();
let workspace = self.workspace.clone();
let rows = visible_issues
.iter()
.enumerate()
.filter_map(|(ix, &issue_ix)| {
// The store re-read per frame can shrink below a captured index.
let issue = store.read(cx).issues.get(issue_ix)?;
let profile = directory.read(cx).profile(&issue.pubkey, cx);
let issue_id = issue.id;
let id_hex = issue.id.to_hex();
let status = store.read(cx).status_of(issue);
let on_click: crate::shared::event_list::EventHandler = {
let workspace = workspace.clone();
let store = store.clone();
Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("issue:{issue_id}"));
let store = store.clone();
panels::open_detail(
&workspace,
id,
move |_, cx| {
cx.new(|cx| IssueDetailView::new(store.clone(), issue_id, cx))
},
window,
cx,
);
})
};
Some(EventRow {
id: ix.into(),
status,
title: issue.activity_subject().into(),
author: profile.name(),
picture: profile.picture(),
pubkey: issue.pubkey,
short_id: short_id(&id_hex),
age: SharedString::from(relative_time(issue.created_at)),
on_click,
})
})
.collect();
let empty_message = match filter {
IssueFilter::All => "No issues",
IssueFilter::Open => "No open issues",
IssueFilter::Closed => "No closed issues",
};
v_flex()
.size_full()
.when_some(self.new_issue.clone(), |el, view| el.child(view))
.child(
EventList::new("issues")
.toolbar(self.render_header(cx))
.scroll_handle(self.scroll_handle.clone())
.rows(rows)
.empty_message(empty_message)
.render(cx),
)
.into_any_element()
}
}
-101
View File
@@ -1,101 +0,0 @@
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
};
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress;
pub struct NewIssueDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
subject: Entity<InputState>,
content: Entity<InputState>,
state: Entity<DialogProgress>,
}
impl NewIssueDialog {
pub fn new(store: Entity<RepoStore>, cx: &mut App) -> Entity<Self> {
let subject = InputState::new(cx);
let content = InputState::builder().multiline().build(cx);
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
subject,
content,
state,
})
}
fn submit(&mut self, cx: &mut Context<Self>) {
// The publish runs detached in the store; one submission per dialog.
if self.state.read(cx).busy {
return;
}
let subject = self.subject.read(cx).value().to_string();
let content = self.content.read(cx).value().to_string();
let subject = (!subject.trim().is_empty()).then_some(subject);
self.state.update(cx, |state, _| state.begin());
self.store.update(cx, |store, cx| {
store.open_issue(subject, content, cx);
});
self.handle.close(cx);
}
}
impl Render for NewIssueDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let subject = self.subject.clone();
let content = self.content.clone();
let this = cx.entity().downgrade();
let action_state = self.state.clone();
Dialog::new("new-issue-dialog")
.handle(self.handle.clone())
.min_width(gpui::px(520.))
.title("New issue")
.content(move |_, cx| {
v_flex()
.gap_3()
.child(
div()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child("Report a bug, ask a question, or propose a change."),
)
.child(
Field::new("issue-title", "Title")
.child(Input::new("issue-title-input", subject.clone())),
)
.child(
Field::new("issue-content", "Content")
.child(Input::new("issue-content-input", content.clone()).rows(6)),
)
.into_any_element()
})
.actions(move |_, cx| {
let this = this.clone();
let busy = action_state.read(cx).busy;
vec![
Button::new("create-issue")
.label("Create issue")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx)));
})
.into_any_element() as AnyElement,
]
})
}
}
-20
View File
@@ -1,20 +0,0 @@
mod app;
mod explore;
mod identity;
#[allow(dead_code)] // temporarily unlinked while the shell migrates
mod inbox;
mod issues;
mod pull_requests;
mod repo;
mod settings;
mod shared;
mod titlebar;
mod workspace;
pub use app::AppRoot;
pub use app::helpers::{apply_appearance, apply_appearance_mode};
use gpui::{App, AppContext as _, Entity, Window};
pub fn root(window: &mut Window, cx: &mut App) -> Entity<AppRoot> {
cx.new(|cx| AppRoot::new(window, cx))
}
@@ -1,600 +0,0 @@
use std::path::PathBuf;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle,
WeakEntity, Window, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{EventId, Kind, Url};
use signed_core::{GitEvent, PullRequest, RepoAddr};
use signed_git::{FileCommit, PatchParser};
use signed_state::{Backend, Mirrors, RepoStore};
use ui::avatar::Avatar;
use ui::button::Button;
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::InputState;
use ui::layout::panel::Panel;
use ui::scroll_area::ScrollArea;
use ui::tabs::{Tab, Tabs};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
use super::dialogs;
use crate::issues::helpers::{comment_form, comments_section, pr_roots, sidebar_section};
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::shared::widgets::{empty_state, status_badge};
use crate::workspace::Workspace;
const NOT_FOUND: &str = "Pull request not found";
#[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,
}
pub struct PullRequestDetailView {
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
pr_id: EventId,
update_dialog: Option<Entity<dialogs::update::UpdatePrDialog>>,
comment_input: Entity<InputState>,
worktree: Option<PathBuf>,
description: SharedString,
current_commit: Option<SharedString>,
commits: Arc<Vec<FileCommit>>,
loading: bool,
error: Option<SharedString>,
bound: Option<PrBinding>,
load_generation: u64,
active_tab: usize,
pane: Entity<DiffPane>,
commit_scroll_handle: UniformListScrollHandle,
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
directory: Entity<ProfileDirectory>,
_subscription: Subscription,
}
impl PullRequestDetailView {
pub fn new(
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
pr_id: EventId,
_window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let pane = cx.new(DiffPane::new);
let comment_input = InputState::builder().multiline().build(cx);
let weak = cx.entity().downgrade();
let subscription = cx.observe(&store, |this, _store, cx| {
this.sync(cx);
});
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.sync(cx)));
});
Self {
workspace,
store,
pr_id,
update_dialog: None,
comment_input,
worktree: None,
description: SharedString::default(),
current_commit: None,
commits: Arc::new(Vec::new()),
loading: true,
error: None,
bound: None,
load_generation: 0,
active_tab: 0,
pane,
commit_scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(),
directory: ProfileDirectory::new(cx),
_subscription: subscription,
}
}
fn track_participants(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx);
let author = store
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
.map(|root| root.pubkey);
let owner = store.announcement.as_ref().map(|a| a.owner);
let comments: Vec<_> = store
.comments_of(&self.pr_id)
.map(|comment| comment.pubkey)
.collect();
crate::shared::track_event_participants(
author,
owner,
comments.into_iter(),
&self.directory,
cx,
);
}
fn sync(&mut self, cx: &mut Context<Self>) {
self.track_participants(cx);
let loaded = self.store.read(cx).loaded;
let binding = {
let store = self.store.read(cx);
store.addr().and_then(|addr| {
store
.pull_requests
.iter()
.find(|pr| pr.id == self.pr_id && pr.kind == Kind::GitPullRequest)
.map(|root| {
let update = PullRequest::latest_update(store.pull_requests.iter(), root);
let tip = update
.and_then(GitEvent::current_commit)
.or_else(|| root.current_commit());
let base = update
.and_then(GitEvent::merge_base)
.or_else(|| root.merge_base());
let clone_urls = root
.clone_urls()
.or_else(|| store.announcement.as_ref().map(|a| a.clone.clone()))
.unwrap_or_default();
PrBinding {
description: root.content.clone(),
patch: PullRequest::new(root).patch(store.patches.iter()),
tip,
base,
clone_urls,
addr: addr.clone(),
has_patch_link: root.tags.event_ids().next().is_some(),
}
})
})
};
let Some(binding) = binding else {
self.bound = None;
if !loaded {
self.loading = true;
self.error = None;
} else if self.error.as_deref() != Some(NOT_FOUND) {
self.loading = false;
self.error = Some(NOT_FOUND.into());
}
cx.notify();
return;
};
if self.bound.as_ref() == Some(&binding) {
return;
}
self.bound = Some(binding.clone());
self.load_diff(binding, cx);
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: gpui::Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
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();
async move { PatchParser::patch_diffs(&patch) }
})
.await;
let nostr_commits = cx
.background_spawn({
let patch = patch.clone();
async move { PatchParser::patch_commits(&patch) }
})
.await;
let use_nostr = match &nostr_diff {
Ok(diff) => has_patch_link || !diff.files.is_empty(),
Err(_) => true,
};
let git = if use_nostr {
None
} else {
let addr = addr.clone();
let clone_urls = clone_urls.clone();
let base = base.clone();
let tip = tip.clone();
Some(
cx.background_spawn(async move {
let repo = Mirrors::ensure(&addr, &clone_urls)?;
let gix_repo = repo.inner();
let workdir = gix_repo
.workdir()
.ok_or_else(|| anyhow::anyhow!("repository has no worktree"))?
.to_path_buf();
let tip =
tip.ok_or_else(|| anyhow::anyhow!("pull request has no tip commit"))?;
let base = match base {
Some(base) => base,
None => {
let head = gix_repo
.head_id()
.map_err(|_| anyhow::anyhow!("repository has no HEAD"))?;
let tip_id = gix_repo.rev_parse_single(tip.as_bytes())?;
gix_repo.merge_base(tip_id, head)?.to_string()
}
};
let diff = repo.range_diff(&base, &tip)?;
let commits = repo.commit_range(&base, &tip)?;
Ok::<_, anyhow::Error>((diff, commits, workdir))
})
.await,
)
};
let (diff, commits, worktree) = match git {
Some(Ok((diff, commits, worktree))) => (Ok(diff), commits, Some(worktree)),
Some(Err(error)) => (Err(error), Vec::new(), None),
None => (nostr_diff, nostr_commits, None),
};
this.update(cx, |this, cx| {
if this.load_generation != generation {
return;
}
this.loading = false;
this.worktree = worktree;
this.commits = Arc::new(commits);
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();
})?;
Ok(())
});
self.push_task(task);
}
fn open_commit_diff(
&mut self,
worktree: PathBuf,
commit_id: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let id = match self.store.read(cx).addr() {
Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")),
None => SharedString::from(format!("commit:{}:{commit_id}", worktree.display())),
};
let workspace = self.workspace.clone();
let commit_id = commit_id.to_owned();
crate::shared::panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| CommitDiffView::new(worktree.clone(), commit_id.clone(), window, cx))
},
window,
cx,
);
}
fn render_tabs(&self, cx: &mut Context<Self>) -> AnyElement {
let files = self.pane.read(cx).diff().map(|diff| diff.files.len());
let commits = (!self.commits.is_empty()).then_some(self.commits.len());
let weak = cx.entity().downgrade();
let files_label = match files {
Some(count) => format!("Files ({count})"),
None => "Files".to_owned(),
};
let commits_label = match commits {
Some(count) => format!("Commits ({count})"),
None => "Commits".to_owned(),
};
Tabs::new("pr-tabs")
.selected(self.active_tab)
.tabs(move |_, _| {
vec![
Tab::new("discussion", "Discussion"),
Tab::new("files", files_label.clone()),
Tab::new("commits", commits_label.clone()),
]
})
.on_change(move |index, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index;
cx.notify();
}));
})
.into_any_element()
}
fn render_discussion(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
}
if let Some(error) = self.error.clone() {
return empty_state(error);
}
let (author, picture, age, root_id, pubkey) = {
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 {
return empty_state(NOT_FOUND);
};
let profile = self.directory.read(cx).profile(&root.pubkey, cx);
(
profile.name(),
profile.picture(),
relative_time(root.created_at),
root.id,
root.pubkey,
)
};
h_flex()
.size_full()
.min_h_0()
.child(
ScrollArea::new("pr-discussion-scroll")
.flex_1()
.min_w_0()
.child(
v_flex()
.p_4()
.gap_6()
.child(
v_flex()
.gap_4()
.child(
h_flex()
.gap_2()
.text_base()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(pubkey)
.name(author.clone())
.picture(picture)
.small(),
)
.child(author),
)
.child(SharedString::from("commented"))
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(age)),
),
)
.when(!self.description.is_empty(), |this| {
this.child(
div().text_base().child(self.description.clone()),
)
}),
)
.child(comments_section(&self.store, root_id, &self.directory, cx))
.child(comment_form(
&self.store,
root_id,
pr_roots,
&self.comment_input,
"pr-comment",
cx,
)),
),
)
.child(sidebar_section(
&self.store,
root_id,
pr_roots,
true,
&self.directory,
cx,
))
.into_any_element()
}
fn render_files(&self, _cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
}
if let Some(error) = self.error.clone() {
return empty_state(error);
}
self.pane.clone().into_any_element()
}
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return centered_spinner();
}
if let Some(error) = self.error.clone() {
return empty_state(error);
}
if self.commits.is_empty() {
return empty_state("No commits found");
}
let commits = Arc::clone(&self.commits);
let worktree = self.worktree.clone();
let view = cx.entity().downgrade();
crate::shared::event_list::commit_list(
"pr-commits",
"pr-commits-scroll",
commits,
self.commit_scroll_handle.clone(),
|_, _, _| None,
move |commit, window, cx| {
if let Some(worktree) = worktree.clone() {
let id = commit.id.clone();
crate::shared::log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(worktree, &id, window, cx);
}));
}
},
cx,
)
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let current_commit = self.current_commit.clone();
let (title, status, branch, author) = {
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 {
return div().into_any_element();
};
(
root.activity_subject(),
store.status_of(root),
root.branch_name(),
root.pubkey,
)
};
let can_update = Backend::global(cx).read(cx).current_user() == Some(author);
let weak = cx.entity().downgrade();
v_flex()
.flex_none()
.px_4()
.py_2()
.gap_2()
.child(
h_flex().gap_2().child(status_badge(status)).child(
div()
.flex_1()
.min_w_0()
.text_sm()
.font_semibold()
.text_ellipsis()
.child(title),
),
)
.child(
h_flex()
.gap_3()
.when_some(branch, |this, branch| {
this.child(
Button::new("branch")
.label(branch)
.icon(Icon::named(IconRole::GitBranch))
.small(),
)
})
.when(can_update, |this| {
this.child(Button::new("update-pr").label("Update").small().on_click(
move |_, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
let root = this
.store
.read(cx)
.pull_requests
.iter()
.find(|pr| {
pr.id == this.pr_id && pr.kind == Kind::GitPullRequest
})
.cloned();
if let Some(root) = root {
this.update_dialog =
Some(dialogs::update::UpdatePrDialog::new(
this.store.clone(),
root,
cx,
));
cx.notify();
}
}));
},
))
})
.when_some(current_commit, |this, id| {
this.child(
h_flex()
.gap_1()
.font_family(cx.theme().mono_font)
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(id.clone())
.child(ClipboardButton::new("pr-commit", &id)),
)
}),
)
.into_any_element()
}
}
impl Panel for PullRequestDetailView {
fn title(&self, _cx: &App) -> SharedString {
let hex = self.pr_id.to_hex();
let short = hex.get(..8).unwrap_or(&hex);
SharedString::from(format!("PR {short}"))
}
fn loading(&self, _cx: &App) -> bool {
self.loading
}
}
impl Render for PullRequestDetailView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.id("pull-request-detail")
.size_full()
.min_h_0()
.child(self.render_header(cx))
.when_some(self.update_dialog.clone(), |el, view| el.child(view))
.child(self.render_tabs(cx))
.map(|this| match self.active_tab {
0 => this.child(self.render_discussion(cx)),
1 => this.child(self.render_files(cx)),
_ => this.child(self.render_commits(cx)),
})
}
}
fn centered_spinner() -> AnyElement {
crate::shared::widgets::centered_spinner("pr-loading")
}
@@ -1 +0,0 @@
pub mod update;
@@ -1,94 +0,0 @@
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div,
};
use nostr::prelude::Event;
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::DialogProgress;
pub struct UpdatePrDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
root: Event,
patch: Entity<InputState>,
state: Entity<DialogProgress>,
}
impl UpdatePrDialog {
pub fn new(store: Entity<RepoStore>, root: Event, cx: &mut App) -> Entity<Self> {
let patch = InputState::builder().multiline().build(cx);
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
root,
patch,
state,
})
}
fn submit(&mut self, cx: &mut Context<Self>) {
// The publish runs detached in the store; one submission per dialog.
if self.state.read(cx).busy {
return;
}
let patch = self.patch.read(cx).value().to_string();
if patch.trim().is_empty() {
return;
}
self.state.update(cx, |state, _| state.begin());
self.store.update(cx, |store, cx| {
store.update_pull_request(&self.root, patch, cx);
});
self.handle.close(cx);
}
}
impl Render for UpdatePrDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let patch = self.patch.clone();
let this = cx.entity().downgrade();
let action_state = self.state.clone();
Dialog::new("update-pr-dialog")
.handle(self.handle.clone())
.min_width(gpui::px(520.))
.title("Update pull request")
.content(move |_, cx| {
v_flex()
.gap_3()
.child(
div()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child("Publish a new revision with the output of `git format-patch`."),
)
.child(
Field::new("update-patch", "Patch")
.child(Input::new("update-patch-input", patch.clone()).rows(6)),
)
.into_any_element()
})
.actions(move |_, cx| {
let this = this.clone();
let busy = action_state.read(cx).busy;
vec![
Button::new("submit-update")
.label("Update pull request")
.loading(busy)
.disabled(busy)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(this.update(cx, |this, cx| this.submit(cx)));
})
.into_any_element() as AnyElement,
]
})
}
}
@@ -1,139 +0,0 @@
use std::path::PathBuf;
use gpui::{SharedString, WeakEntity};
use nostr::prelude::PublicKey;
use signed_core::{Announcement, RepoAddr, RepoStatus};
use ui::menu::MenuItem;
use utils::middle_truncate;
use super::NewPullRequestView;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PullRequestFilter {
All,
Open,
Closed,
Draft,
Merged,
}
impl PullRequestFilter {
pub fn matches(self, status: RepoStatus) -> bool {
match self {
Self::All => true,
Self::Open => status == RepoStatus::Open,
Self::Closed => status == RepoStatus::Closed,
Self::Draft => status == RepoStatus::Draft,
Self::Merged => status == RepoStatus::Applied,
}
}
pub fn empty_message(self) -> &'static str {
match self {
Self::All => "No pull requests",
Self::Open => "No open pull requests",
Self::Closed => "No closed pull requests",
Self::Draft => "No draft pull requests",
Self::Merged => "No merged pull requests",
}
}
}
pub struct ForkCompare {
pub announcement: Announcement,
pub namespace: String,
pub mirror_path: PathBuf,
}
impl ForkCompare {
pub fn base_ref(name: &str) -> String {
format!("refs/remotes/origin/{name}")
}
pub fn compare_ref(&self, name: &str) -> String {
format!("refs/fork/{}/{}", self.namespace, name)
}
}
pub fn shorten_owner(owner: &PublicKey) -> String {
owner.to_hex().chars().take(10).collect()
}
pub fn truncate_label(label: &str) -> SharedString {
SharedString::from(middle_truncate(label, 18, 0))
}
pub fn source_menu_items(
view: WeakEntity<NewPullRequestView>,
associated: Vec<PathBuf>,
active_path: Option<PathBuf>,
candidates: Vec<Announcement>,
user: Option<PublicKey>,
active_fork: Option<RepoAddr>,
) -> Vec<MenuItem> {
let mut items = Vec::new();
for path in associated {
let label = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
let target = view.clone();
let path_for_action = path.clone();
items.push(
MenuItem::new(truncate_label(&label))
.checked(active_path.as_ref() == Some(&path))
.handler(move |window, cx| {
let path = path_for_action.clone();
if let Err(error) =
target.update(cx, |this, cx| this.apply_folder_path(path, window, cx))
{
log::warn!("failed to apply checkout: {error}");
}
}),
);
}
let folder_view = view.clone();
items.push(
MenuItem::new("Choose another folder…").handler(move |window, cx| {
if let Err(error) = folder_view.update(cx, |this, cx| this.choose_checkout(window, cx))
{
log::warn!("failed to choose checkout: {error}");
}
}),
);
items.push(MenuItem::separator());
if candidates.is_empty() {
items.push(MenuItem::new("No announced forks of this repository").disabled(true));
} else {
for candidate in candidates {
let subtitle = if Some(candidate.owner) == user {
SharedString::from("Your fork")
} else {
SharedString::from(format!("by {}", shorten_owner(&candidate.owner)))
};
let title = format!(
"{} — {}",
crate::repo::helpers::announcement_display_name(&candidate),
subtitle
);
let target = view.clone();
let checked = active_fork == Some(candidate.addr());
let announcement = candidate;
items.push(
MenuItem::new(truncate_label(&title))
.checked(checked)
.handler(move |window, cx| {
let announcement = announcement.clone();
if let Err(error) =
target.update(cx, |this, cx| this.choose_fork(announcement, window, cx))
{
log::warn!("failed to choose fork: {error}");
}
}),
);
}
}
items
}
-380
View File
@@ -1,380 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div,
};
use metadata::ProfileDirectory;
use nostr::prelude::{Kind, PublicKey};
use signed_core::GitEvent;
use signed_state::RepoStore;
use std::rc::Rc;
use ui::alert::{Alert, AlertSeverity};
use ui::common::v_flex;
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::menu::MenuItem;
use ui::segmented::{Segmented, SegmentedOption};
use ui::theme::ActiveTheme as _;
use utils::relative_time;
mod detail;
mod dialogs;
mod helpers;
mod new;
mod send_patch;
pub use detail::PullRequestDetailView;
use helpers::PullRequestFilter;
pub use new::NewPullRequestView;
pub use send_patch::SendPatchView;
use crate::issues::helpers::{StatusCounts, filter_by_status};
use crate::repo::helpers::short_id;
use crate::shared::event_list::{EventList, EventRow};
use crate::workspace::Workspace;
pub struct PullRequestsView {
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
filter: PullRequestFilter,
visible_prs: Vec<usize>,
counts: StatusCounts,
synced_filter: PullRequestFilter,
scroll_handle: UniformListScrollHandle,
directory: Entity<ProfileDirectory>,
new_pr_menu_open: bool,
_subscription: Subscription,
}
impl PullRequestsView {
pub fn new(
workspace: WeakEntity<Workspace>,
store: Entity<RepoStore>,
cx: &mut Context<Self>,
) -> Self {
let weak = cx.entity().downgrade();
let subscription = cx.observe(&store, |this, _store, cx| {
this.rebuild(cx);
});
cx.defer(move |cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
this.rebuild(cx);
}));
});
Self {
workspace,
store,
filter: PullRequestFilter::Open,
visible_prs: Vec::new(),
counts: StatusCounts::default(),
synced_filter: PullRequestFilter::Open,
scroll_handle: UniformListScrollHandle::new(),
directory: ProfileDirectory::new(cx),
new_pr_menu_open: false,
_subscription: subscription,
}
}
/// Total number of pull requests across all statuses, for the sidebar label.
pub fn total_count(&self) -> usize {
self.counts.total
}
fn rebuild(&mut self, cx: &mut Context<Self>) {
let store = self.store.read(cx);
let filter = self.filter;
let (visible_prs, counts) = {
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 mut keys: Vec<PublicKey> = store
.pull_requests
.iter()
.filter(|pr| pr.kind == Kind::GitPullRequest)
.map(|pr| pr.pubkey)
.collect();
if let Some(owner) = store
.announcement
.as_ref()
.map(|announcement| announcement.owner)
{
keys.push(owner);
}
self.directory.update(cx, |directory, cx| {
directory.track(keys, cx);
});
let filter_changed = self.synced_filter != filter;
if !filter_changed && self.visible_prs == visible_prs && self.counts == counts {
return;
}
self.synced_filter = filter;
self.visible_prs = visible_prs;
self.counts = counts;
cx.notify();
}
fn open_new(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return;
};
let id = SharedString::from(format!("new-pr:{addr}"));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
let store = self.store.clone();
crate::shared::panels::open_detail(
&workspace,
id.clone(),
move |window, cx| {
cx.new(|cx| {
NewPullRequestView::new(
workspace_for_build.clone(),
id.clone(),
store.clone(),
window,
cx,
)
})
},
window,
cx,
);
}
fn open_send_patch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return;
};
let id = SharedString::from(format!("send-patch:{addr}"));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
let store = self.store.clone();
crate::shared::panels::open_detail(
&workspace,
id.clone(),
move |window, cx| {
cx.new(|cx| {
SendPatchView::new(
workspace_for_build.clone(),
id.clone(),
store.clone(),
window,
cx,
)
})
},
window,
cx,
);
}
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
let counts = self.counts;
let muted = cx.theme().colors.muted_foreground;
let weak = cx.entity().downgrade();
let open_weak = cx.entity().downgrade();
let menu_open_weak = cx.entity().downgrade();
let patch_weak = cx.entity().downgrade();
crate::shared::event_list::filter_toolbar(
cx,
[
Segmented::new("pr-filter", self.filter)
.options(vec![
SegmentedOption::new(
PullRequestFilter::All,
format!("All ({})", counts.total),
)
.icon(Icon::named(IconRole::GitPullRequest).color(muted)),
SegmentedOption::new(
PullRequestFilter::Open,
format!("Open ({})", counts.open),
)
.icon(Icon::named(IconRole::GitPullRequest).color(muted)),
SegmentedOption::new(
PullRequestFilter::Closed,
format!("Closed ({})", counts.closed),
)
.icon(Icon::named(IconRole::GitPullRequestClosed).color(muted)),
SegmentedOption::new(
PullRequestFilter::Draft,
format!("Draft ({})", counts.draft),
)
.icon(Icon::named(IconRole::GitPullRequestDraft).color(muted)),
SegmentedOption::new(
PullRequestFilter::Merged,
format!("Merged ({})", counts.applied),
)
.icon(Icon::named(IconRole::GitPullRequestMerged).color(muted)),
])
.on_change(move |filter, _, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.filter = filter;
this.rebuild(cx);
}) {
log::warn!("failed to switch PR filter: {error}");
}
})
.into_any_element(),
div().flex_1().into_any_element(),
DropdownMenu::new("new-pr-actions")
.label("New")
.icon(Icon::named(IconRole::GitPullRequest))
.open(self.new_pr_menu_open)
.on_click(move |_, window, cx| {
if let Err(error) =
open_weak.update(cx, |this, cx| this.open_new(window, cx))
{
log::warn!("failed to open new PR: {error}");
}
})
.on_open_change(move |open, _, cx| {
crate::shared::log_dropped(menu_open_weak.update(cx, |this, cx| {
this.new_pr_menu_open = open;
cx.notify();
}));
})
.items(move |_, _| {
vec![MenuItem::new("Send Patch").handler({
let weak = patch_weak.clone();
move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
this.open_send_patch(window, cx);
}));
}
})]
})
.into_any_element(),
],
)
}
}
impl Panel for PullRequestsView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Pull requests")
}
}
impl Render for PullRequestsView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let filter = self.filter;
let visible = self.visible_prs.clone();
let directory = self.directory.clone();
let store = self.store.clone();
let workspace = self.workspace.clone();
let (last_error, last_warning) = {
let store = self.store.read(cx);
(store.last_error.clone(), store.last_warning.clone())
};
let dismiss_warning_store = self.store.clone();
let dismiss_error_store = self.store.clone();
let rows = visible
.iter()
.enumerate()
.filter_map(|(ix, &pr_ix)| {
// The store re-read per frame can shrink below a captured index.
let pr = store.read(cx).pull_requests.get(pr_ix)?;
let profile = directory.read(cx).profile(&pr.pubkey, cx);
let pr_id = pr.id;
let id_hex = pr.id.to_hex();
let status = store.read(cx).status_of(pr);
let on_click: crate::shared::event_list::EventHandler = {
let workspace = workspace.clone();
let store = store.clone();
Rc::new(move |_, window, cx| {
let id = SharedString::from(format!("pr:{pr_id}"));
let workspace_for_build = workspace.clone();
let store = store.clone();
crate::shared::panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
PullRequestDetailView::new(
workspace_for_build.clone(),
store.clone(),
pr_id,
window,
cx,
)
})
},
window,
cx,
);
})
};
Some(EventRow {
id: ix.into(),
status,
title: pr.activity_subject().into(),
author: profile.name(),
picture: profile.picture(),
pubkey: pr.pubkey,
short_id: short_id(&id_hex),
age: SharedString::from(relative_time(pr.created_at)),
on_click,
})
})
.collect();
v_flex()
.size_full()
.when_some(last_warning, |this, warning| {
this.child(
Alert::new("pr-warning")
.severity(AlertSeverity::Warning)
.title("Pull request warning")
.message(warning)
.on_dismiss(move |cx| {
dismiss_warning_store.update(cx, |store, _| store.last_warning = None);
}),
)
})
.when_some(last_error, |this, error| {
this.child(
Alert::new("pr-error")
.severity(AlertSeverity::Danger)
.title("Pull request error")
.message(error)
.on_dismiss(move |cx| {
dismiss_error_store.update(cx, |store, _| store.last_error = None);
}),
)
})
.child(
EventList::new("prl")
.toolbar(self.render_header(cx))
.scroll_handle(self.scroll_handle.clone())
.rows(rows)
.empty_message(filter.empty_message())
.render(cx),
)
.into_any_element()
}
}
-466
View File
@@ -1,466 +0,0 @@
use std::path::PathBuf;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle,
WeakEntity, Window, div, px,
};
use signed_state::{CheckoutsStore, RepoStore};
use ui::button::Button;
use ui::combobox::{Combobox, ComboboxState};
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::menu::Menu;
use ui::tabs::{Tab, Tabs};
use super::helpers::{ForkCompare, truncate_label};
use crate::repo::commit_diff::{CommitDiffView, DiffPane};
use crate::shared::progress::error_row;
use crate::shared::widgets::empty_state;
use crate::workspace::Workspace;
mod source;
pub struct NewPullRequestView {
workspace: WeakEntity<Workspace>,
panel_id: SharedString,
pub(super) store: Entity<RepoStore>,
pub(super) repo_path: Option<PathBuf>,
pub(super) branches: Vec<SharedString>,
pub(super) fork: Option<ForkCompare>,
pub(super) base: SharedString,
pub(super) compare: SharedString,
pub(super) base_select: Entity<ComboboxState<SharedString>>,
pub(super) compare_select: Entity<ComboboxState<SharedString>>,
subject: Entity<InputState>,
description: Entity<InputState>,
pub(super) merge_base: Option<String>,
pub(super) commits: Option<Arc<Vec<signed_git::FileCommit>>>,
pub(super) loading: bool,
pub(super) error: Option<SharedString>,
submitting: bool,
pub(super) compare_generation: u64,
pub(super) fork_generation: u64,
active_tab: usize,
pub(super) pane: Entity<DiffPane>,
scroll_handle: UniformListScrollHandle,
pub(super) tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
source_open: bool,
_subscriptions: Vec<Subscription>,
}
impl NewPullRequestView {
pub fn new(
workspace: WeakEntity<Workspace>,
panel_id: SharedString,
store: Entity<RepoStore>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let pane = cx.new(DiffPane::new);
let weak = cx.entity().downgrade();
let subject = InputState::new(cx);
let description = InputState::builder().multiline().build(cx);
let base_select = cx.new(|cx| {
ComboboxState::new(
Combobox::new("pr-base", "Base", Vec::new()).on_change({
let weak = weak.clone();
move |value, _window, cx| {
if let Some(base) = value {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
if this.base == base {
return;
}
this.base = base;
this.reload_compare(cx);
}));
}
}
}),
window,
cx,
)
});
let compare_select = cx.new(|cx| {
ComboboxState::new(
Combobox::new("pr-compare", "Compare", Vec::new()).on_change({
let weak = weak.clone();
move |value, _window, cx| {
if let Some(compare) = value {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
if this.compare == compare {
return;
}
this.compare = compare;
this.reload_compare(cx);
}));
}
}
}),
window,
cx,
)
});
window.defer(cx, move |window, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
let Some(addr) = this.store.read(cx).addr().cloned() else {
return;
};
let Some(path) = CheckoutsStore::global(cx)
.read(cx)
.associations_of(&addr)
.into_iter()
.next()
else {
return;
};
this.apply_folder_path(path, window, cx);
}));
});
Self {
workspace,
panel_id,
store,
repo_path: None,
branches: Vec::new(),
fork: None,
base: SharedString::default(),
compare: SharedString::default(),
base_select,
compare_select,
subject,
description,
merge_base: None,
commits: None,
loading: false,
error: None,
submitting: false,
compare_generation: 0,
fork_generation: 0,
active_tab: 0,
pane,
scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(),
source_open: false,
_subscriptions: Vec::new(),
}
}
/// Reaps finished tasks, then queues another.
pub(super) fn push_task(&mut self, task: gpui::Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn submit(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if self.submitting || self.loading {
return;
}
let Some(merge_base) = self.merge_base.clone() else {
return;
};
let Some(repo_path) = self.work_path() else {
return;
};
let subject = self.subject.read(cx).value().to_string();
let description = self.description.read(cx).value().to_string();
let branch_name = self.compare.to_string();
let compare_ref = self.compare_ref();
let store = self.store.clone();
let workspace = self.workspace.clone();
let panel_id = self.panel_id.clone();
self.submitting = true;
self.error = None;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let publish = store.update(cx, |store, cx| {
store.open_pull_request_from_refs(
repo_path,
merge_base,
compare_ref,
(!subject.is_empty()).then_some(subject),
description,
Some(branch_name),
false,
cx,
)
});
if let Err(error) = publish.await {
this.update(cx, |this, cx| {
this.submitting = false;
this.error = Some(error.to_string().into());
cx.notify();
})?;
return Ok(());
}
this.update(cx, |this, _cx| {
this.submitting = false;
})?;
crate::shared::log_dropped(
workspace.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
Ok(())
});
self.push_task(task);
}
fn open_commit_diff(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context<Self>) {
let Some(repo_path) = self.work_path() else {
return;
};
let id = match self.store.read(cx).addr() {
Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")),
None => SharedString::from(format!("commit:{}:{commit_id}", repo_path.display())),
};
let workspace = self.workspace.clone();
let commit_id = commit_id.to_owned();
crate::shared::panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| CommitDiffView::new(repo_path.clone(), commit_id.clone(), window, cx))
},
window,
cx,
);
}
fn submit_enabled(&self, cx: &App) -> bool {
self.has_source()
&& !self.loading
&& !self.submitting
&& self.merge_base.is_some()
&& self
.commits
.as_ref()
.is_some_and(|commits| !commits.is_empty())
&& !self.subject.read(cx).value().is_empty()
}
fn render_compare_bar(&self, cx: &mut Context<Self>) -> AnyElement {
let weak = cx.entity().downgrade();
let weak_menu = cx.entity().downgrade();
let source_view = cx.entity().downgrade();
let associated = self
.store
.read(cx)
.addr()
.map(|addr| CheckoutsStore::global(cx).read(cx).associations_of(addr))
.unwrap_or_default();
let active_path = (self.fork.is_none())
.then(|| self.repo_path.clone())
.flatten();
let candidates = self.fork_candidates(cx);
let user = signed_state::Backend::global(cx).read(cx).current_user();
let active_fork = self.fork.as_ref().map(|fork| fork.announcement.addr());
let can_submit = self.submit_enabled(cx);
let source_label = match &self.fork {
Some(fork) => truncate_label(&crate::repo::helpers::announcement_display_name(
&fork.announcement,
)),
None => self.repo_path.as_ref().map_or_else(
|| SharedString::from("No source"),
|path| truncate_label(&path.display().to_string()),
),
};
let refresh_fork = self.fork.as_ref().map(|fork| fork.announcement.clone());
h_flex()
.px_4()
.py_2()
.w_full()
.gap_3()
.items_end()
.child(
v_flex()
.gap_1()
.child(label("Merge Into"))
.child(div().w(px(160.)).child(self.base_select.clone())),
)
.child(
v_flex()
.gap_1()
.child(label("Pull From"))
.child(div().w(px(160.)).child(self.compare_select.clone())),
)
.child(
v_flex().gap_1().child(label("Source")).child(
Menu::new("pr-source")
.open(self.source_open)
.on_change(move |open, _, cx| {
crate::shared::log_dropped(weak_menu.update(cx, |this, cx| {
this.source_open = open;
cx.notify();
}));
})
.trigger(move |_, _| {
Button::new("compare-source")
.label(source_label.clone())
.variant(ui::button::ButtonVariant::Secondary)
.into_any_element()
})
.items(move |_, _| {
super::helpers::source_menu_items(
source_view.clone(),
associated.clone(),
active_path.clone(),
candidates.clone(),
user,
active_fork.clone(),
)
}),
),
)
.when_some(refresh_fork, |this, fork| {
this.child(
Button::new("refresh-fork")
.icon(Icon::named(IconRole::Refresh))
.on_click(cx.listener(move |this, _, window, cx| {
this.choose_fork(fork.clone(), window, cx);
})),
)
})
.child(div().flex_1())
.child(
Button::new("create-pr")
.label("Create pull request")
.icon(Icon::named(IconRole::Plus))
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
weak.update(cx, |this, cx| this.submit(window, cx)),
);
}),
)
.into_any_element()
}
fn render_tabs(&self, cx: &mut Context<Self>) -> AnyElement {
let files = self.pane.read(cx).diff().map_or(0, |diff| diff.files.len());
let commits = self.commits.as_ref().map_or(0, |commits| commits.len());
let weak = cx.entity().downgrade();
Tabs::new("new-pr-tabs")
.selected(self.active_tab)
.tabs(move |_, _| {
vec![
Tab::new("files", format!("Files ({files})")).lead(Icon::named(IconRole::File)),
Tab::new("commits", format!("Commits ({commits})"))
.lead(Icon::named(IconRole::GitCommit)),
]
})
.on_change(move |index, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| {
this.active_tab = index;
cx.notify();
}));
})
.into_any_element()
}
fn render_content(&self, cx: &mut Context<Self>) -> AnyElement {
if self.loading {
return crate::shared::widgets::centered_spinner("new-pr-loading");
}
if !self.has_source() {
return empty_state("Choose a local checkout or an announced fork to compare");
}
if self.commits.is_none() && self.error.is_some() {
return empty_state("Nothing to compare");
}
match self.active_tab {
0 => self.pane.clone().into_any_element(),
_ => self.render_commits(cx),
}
}
fn render_commits(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(commits) = self.commits.as_ref() else {
return empty_state("No commits");
};
if commits.is_empty() {
return empty_state("No commits between the branches");
}
let commits = Arc::clone(commits);
let view = cx.entity().downgrade();
crate::shared::event_list::commit_list(
"new-pr-commits",
"new-pr-commits-scroll",
commits,
self.scroll_handle.clone(),
|_, _, _| None,
move |commit, window, cx| {
let id = commit.id.clone();
crate::shared::log_dropped(view.update(cx, |this, cx| {
this.open_commit_diff(&id, window, cx);
}));
},
cx,
)
}
}
impl Panel for NewPullRequestView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("New pull request")
}
fn loading(&self, _cx: &App) -> bool {
self.loading
}
}
impl Render for NewPullRequestView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.id("new-pr")
.size_full()
.child(
v_flex()
.gap_3()
.child(self.render_compare_bar(cx))
.child(
v_flex()
.px_4()
.gap_2()
.child(
Input::new("pr-title", self.subject.clone()).placeholder("Title"),
)
.child(
Input::new("pr-description", self.description.clone())
.rows(3)
.placeholder("Describe..."),
)
.when_some(error_row(&self.error, cx), |this, error| this.child(error)),
)
.child(self.render_tabs(cx)),
)
.child(
v_flex()
.flex_1()
.min_h_0()
.w_full()
.child(self.render_content(cx)),
)
}
}
fn label(text: &'static str) -> AnyElement {
div().text_xs().font_medium().child(text).into_any_element()
}
@@ -1,397 +0,0 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
use gpui::{App, AppContext as _, Context, PathPromptOptions, SharedString, Window};
use nostr::prelude::Url;
use signed_core::Announcement;
use signed_git::{GitCache, Repo};
use signed_state::{Backend, CheckoutsStore, Mirrors, RepoListStore};
use super::NewPullRequestView;
use crate::pull_requests::helpers::ForkCompare;
/// The announced head when listed, else `main`, else the first branch.
fn preferred_branch(branches: &[String], announced: Option<String>) -> String {
announced
.filter(|branch| branches.contains(branch))
.or_else(|| {
branches
.iter()
.find(|branch| branch.as_str() == "main")
.cloned()
})
.unwrap_or_else(|| branches[0].clone())
}
impl NewPullRequestView {
pub(super) fn has_source(&self) -> bool {
self.repo_path.is_some() || self.fork.is_some()
}
pub(super) fn work_path(&self) -> Option<PathBuf> {
match &self.fork {
Some(fork) => Some(fork.mirror_path.clone()),
None => self.repo_path.clone(),
}
}
pub(super) fn base_ref(&self) -> String {
match &self.fork {
Some(_) => ForkCompare::base_ref(&self.base),
None => self.base.to_string(),
}
}
pub(super) fn compare_ref(&self) -> String {
match &self.fork {
Some(fork) => fork.compare_ref(&self.compare),
None => self.compare.to_string(),
}
}
pub(crate) fn choose_checkout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose local checkout".into()),
});
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let picked = match prompt.await {
Ok(Ok(Some(mut paths))) => paths.pop(),
_ => None,
};
let Some(path) = picked else {
return Ok(());
};
this.update_in(cx, |this, window, cx| {
this.apply_folder_path(path, window, cx)
})?;
Ok(())
});
self.push_task(task);
}
pub(crate) fn apply_folder_path(
&mut self,
path: PathBuf,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let path_string = path.to_string_lossy().to_string();
let task: gpui::Task<Result<(), anyhow::Error>> =
cx.spawn_in(window, async move |this, cx| {
let info = cx
.background_spawn({
let path = path.clone();
async move {
let repo = Repo::try_open(&path)?;
match repo.branches() {
Ok(branches) => Some((branches, repo.current_branch())),
Err(error) => {
log::warn!("failed to list branches: {error}");
None
}
}
}
})
.await;
this.update_in(cx, |this, window, cx| {
if generation != this.fork_generation {
return;
}
this.apply_checkout(path_string, info, window, cx);
})?;
Ok(())
});
self.push_task(task);
}
fn apply_checkout(
&mut self,
path: String,
info: Option<(Vec<String>, Option<String>)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.fork = None;
let Some((branches, current)) = info else {
self.error = Some("The chosen folder is not a git repository".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
};
if branches.is_empty() {
self.error = Some("The repository has no branches yet".into());
self.repo_path = None;
self.branches.clear();
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&branches, announced);
let compare = current
.filter(|branch| branches.contains(branch))
.unwrap_or_else(|| base.clone());
self.repo_path = Some(PathBuf::from(&path));
self.error = None;
self.branches = branches.into_iter().map(SharedString::from).collect();
if let Some(addr) = self.store.read(cx).addr().cloned() {
CheckoutsStore::global(cx).update(cx, |store, cx| {
store.record(PathBuf::from(&path), addr, cx);
});
}
self.base = SharedString::from(base);
self.compare = SharedString::from(compare);
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
fn sync_selectors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let options: Vec<(SharedString, SharedString)> = self
.branches
.iter()
.map(|branch| (branch.clone(), branch.clone()))
.collect();
let base = self.base.clone();
let compare = self.compare.clone();
self.base_select.update(cx, |state, cx| {
state.set_options(options.clone(), cx);
state.set_selected(Some(base), window, cx);
});
self.compare_select.update(cx, |state, cx| {
state.set_options(options, cx);
state.set_selected(Some(compare), window, cx);
});
}
pub(super) fn fork_candidates(&self, cx: &App) -> Vec<Announcement> {
let Some(addr) = self.store.read(cx).addr().cloned() else {
return Vec::new();
};
let euc = self
.store
.read(cx)
.announcement
.as_ref()
.and_then(|a| a.euc.clone());
let user = Backend::global(cx).read(cx).current_user();
let announcements = RepoListStore::global(cx).read(cx).announcements.clone();
Announcement::forks_in(&announcements, &addr, euc.as_deref(), user)
.into_iter()
.cloned()
.collect()
}
pub(crate) fn choose_fork(
&mut self,
announcement: Announcement,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(base) = self.store.read(cx).addr().cloned() else {
return;
};
let mirror_path = Mirrors::path(&base);
let namespace = GitCache::fork_namespace(&announcement);
let clone_urls: Vec<Url> = announcement.clone.clone();
let base_clone_urls: Vec<Url> = self
.store
.read(cx)
.announcement
.as_ref()
.map(|a| a.clone.clone())
.unwrap_or_default();
self.fork_generation = self.fork_generation.wrapping_add(1);
let generation = self.fork_generation;
let handle = window.window_handle();
self.loading = true;
self.error = None;
cx.notify();
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
let namespace = namespace.clone();
let mirror_path = mirror_path.clone();
async move {
Mirrors::ensure(&base, &base_clone_urls)?;
let repo = Repo::open(&mirror_path)?;
repo.delete_refs_with_prefix("refs/fork")?;
repo.fetch_refs(
&clone_urls,
&format!("+refs/heads/*:refs/fork/{namespace}/*"),
)?;
let strip = |refs: Vec<String>, prefix: &str| {
let mut names: Vec<String> = refs
.into_iter()
.filter_map(|name| {
name.strip_prefix(prefix)
.map(|rest| rest.trim_start_matches('/').to_owned())
})
.filter(|name| !name.is_empty())
.collect();
names.sort();
names
};
let base_branches = strip(
repo.refs_with_prefix("refs/remotes/origin")?,
"refs/remotes/origin",
);
let compare_branches = strip(
repo.refs_with_prefix(&format!("refs/fork/{namespace}"))?,
&format!("refs/fork/{namespace}"),
);
Ok::<_, anyhow::Error>((base_branches, compare_branches))
}
})
.await;
if let Err(error) = cx.update_window(handle, |_, window, cx| {
this.update(cx, |this, cx| {
if generation != this.fork_generation {
return;
}
this.apply_fork(announcement, mirror_path, namespace, result, window, cx);
})
}) {
log::warn!("failed to apply fork: {error}");
}
Ok(())
});
self.push_task(task);
}
fn apply_fork(
&mut self,
announcement: Announcement,
mirror_path: PathBuf,
namespace: String,
result: Result<(Vec<String>, Vec<String>), anyhow::Error>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.loading = false;
let (base_branches, compare_branches) = match result {
Ok(branches) => branches,
Err(error) => {
self.error = Some(format!("Could not compare against the fork: {error}").into());
cx.notify();
return;
}
};
if compare_branches.is_empty() {
self.error = Some("The fork has no branches to compare".into());
cx.notify();
return;
}
if base_branches.is_empty() {
self.error = Some("Could not list the target repository's branches.".into());
cx.notify();
return;
}
let announced = self.store.read(cx).head.clone();
let base = preferred_branch(&base_branches, announced);
let compare = compare_branches
.iter()
.find(|branch| branch.as_str() == "main")
.map(|branch| SharedString::from(branch.clone()))
.unwrap_or_else(|| SharedString::from(compare_branches[0].clone()));
self.fork = Some(ForkCompare {
announcement,
namespace,
mirror_path,
});
self.error = None;
self.base = SharedString::from(base);
self.compare = compare;
self.branches = base_branches.into_iter().map(SharedString::from).collect();
self.sync_selectors(window, cx);
self.reload_compare(cx);
}
pub(super) fn reload_compare(&mut self, cx: &mut Context<Self>) {
let Some(repo_path) = self.work_path() else {
return;
};
let base = self.base_ref();
let compare = self.compare_ref();
let base_name = self.base.to_string();
let compare_name = self.compare.to_string();
self.loading = true;
self.error = None;
self.compare_generation += 1;
let generation = self.compare_generation;
cx.notify();
if base == compare {
self.loading = false;
self.merge_base = None;
self.commits = None;
self.pane.update(cx, |pane, cx| pane.clear(cx));
self.error = Some("Choose different base and compare branches".into());
cx.notify();
return;
}
let task: gpui::Task<Result<(), anyhow::Error>> = cx.spawn(async move |this, cx| {
let result = cx
.background_spawn({
async move {
let repo = Repo::open(Path::new(&repo_path))?;
let merge_base = repo.merge_base(&base, &compare)?.ok_or_else(|| {
anyhow::anyhow!(
"{base_name} and {compare_name} share no common ancestor"
)
})?;
let commits = repo.commit_range(&merge_base, &compare)?;
let diff = repo.range_diff(&merge_base, &compare)?;
Ok::<_, anyhow::Error>((merge_base, commits, diff))
}
})
.await;
this.update(cx, |this, cx| {
if generation != this.compare_generation {
return;
}
this.loading = false;
match result {
Ok((merge_base, commits, diff)) => {
this.merge_base = Some(merge_base);
this.commits = Some(Arc::new(commits));
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
}
Err(error) => {
this.merge_base = None;
this.commits = None;
this.pane.update(cx, |pane, cx| pane.clear(cx));
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.push_task(task);
}
}
@@ -1,175 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
Render, SharedString, Styled as _, WeakEntity, Window, div,
};
use signed_state::RepoStore;
use ui::button::Button;
use ui::common::{ResultLogErr as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::layout::panel::Panel;
use ui::theme::ActiveTheme as _;
use crate::shared::progress::error_row;
use crate::workspace::Workspace;
pub struct SendPatchView {
workspace: WeakEntity<Workspace>,
panel_id: SharedString,
store: Entity<RepoStore>,
subject: Entity<InputState>,
description: Entity<InputState>,
patch: Entity<InputState>,
submitting: bool,
error: Option<SharedString>,
}
impl SendPatchView {
pub fn new(
workspace: WeakEntity<Workspace>,
panel_id: SharedString,
store: Entity<RepoStore>,
_window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let subject = InputState::new(cx);
let description = InputState::builder().multiline().build(cx);
let patch = InputState::builder().multiline().build(cx);
Self {
workspace,
panel_id,
store,
subject,
description,
patch,
submitting: false,
error: None,
}
}
fn submit(&mut self, cx: &mut Context<Self>) {
if self.submitting {
return;
}
let subject = self.subject.read(cx).value().to_string();
let description = self.description.read(cx).value().to_string();
let patch = self.patch.read(cx).value().to_string();
if patch.is_empty() {
return;
}
self.submitting = true;
self.error = None;
cx.notify();
let task = self.store.update(cx, |store, cx| {
store.open_pull_request(
(!subject.is_empty()).then_some(subject),
description,
None,
patch,
false,
None,
None,
cx,
)
});
cx.spawn(async move |this, cx| match task.await {
Ok(()) => {
this.update(cx, |this, cx| {
let panel_id = this.panel_id.clone();
crate::shared::log_dropped(
this.workspace
.update(cx, |workspace, cx| workspace.close_detail(&panel_id, cx)),
);
})
.log_err();
}
Err(error) => {
this.update(cx, |this, cx| {
this.submitting = false;
this.error = Some(error.to_string().into());
cx.notify();
})
.log_err();
}
})
.detach();
}
fn render_footer(&self, cx: &Context<Self>) -> AnyElement {
let can_submit = !self.submitting
&& !self.subject.read(cx).value().is_empty()
&& !self.patch.read(cx).value().is_empty();
let weak = cx.entity().downgrade();
h_flex()
.px_4()
.py_2()
.w_full()
.justify_end()
.border_t_1()
.border_color(cx.theme().colors.border)
.child(
Button::new("send-patch")
.label("Send patch")
.icon(Icon::named(IconRole::ArrowUp))
.loading(self.submitting)
.disabled(!can_submit)
.on_click(move |_, _, cx| {
crate::shared::log_dropped(weak.update(cx, |this, cx| this.submit(cx)));
}),
)
.into_any_element()
}
}
impl Panel for SendPatchView {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Send patch")
}
fn loading(&self, _cx: &App) -> bool {
self.submitting
}
}
impl Render for SendPatchView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.id("send-patch")
.size_full()
.child(
v_flex()
.p_4()
.flex_1()
.gap_2()
.child(Input::new("patch-subject", self.subject.clone()).placeholder("Title"))
.child(
Input::new("patch-description", self.description.clone())
.rows(2)
.placeholder("Describe the change"),
)
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(
"You can paste a git diff or a git format-patch patch series here.",
),
)
.child(
Input::new("patch-body", self.patch.clone())
.rows(12)
.placeholder("diff --git a/file.txt b/file.txt"),
)
.when_some(error_row(&self.error, cx), |this, error| this.child(error)),
)
.child(self.render_footer(cx))
}
}
-94
View File
@@ -1,94 +0,0 @@
use gpui::{App, AppContext as _, SharedString, WeakEntity, Window};
use nostr::prelude::EventId;
use signed_core::{Announcement, RepoAddr};
use signed_state::RepoStore;
use crate::repo::RepoDetailView;
use crate::shared::panels;
use crate::workspace::Workspace;
/// An item of a repository to open from outside its detail panel.
pub enum RepoItem {
Issue(EventId),
PullRequest(EventId),
Patch,
}
/// Opens a repository as the main panel, keyed by its address.
pub fn open_repo_panel(
workspace: &WeakEntity<Workspace>,
addr: &RepoAddr,
hint: Option<&Announcement>,
window: &mut Window,
cx: &mut App,
) {
let id = SharedString::from(format!("repo:{addr}"));
let addr = addr.clone();
let hint = hint.cloned();
let workspace_for_build = workspace.clone();
panels::open_primary(
workspace,
id,
move |window, cx| {
let addr = addr.clone();
let hint = hint.clone();
cx.new(|cx| RepoDetailView::new(workspace_for_build.clone(), addr, hint, window, cx))
},
window,
cx,
);
}
/// Opens an issue or pull request using a store built here.
pub fn open_repo_item(
workspace: &WeakEntity<Workspace>,
addr: &RepoAddr,
hint: Option<&Announcement>,
item: RepoItem,
window: &mut Window,
cx: &mut App,
) {
let store = cx.new(|cx| RepoStore::new(addr.clone(), hint.cloned(), cx));
match item {
RepoItem::Issue(issue_id) => {
let id = SharedString::from(format!("issue:{issue_id}"));
let store = store.clone();
panels::open_detail(
workspace,
id,
move |_, cx| {
cx.new(|cx| {
crate::issues::detail::IssueDetailView::new(store.clone(), issue_id, cx)
})
},
window,
cx,
);
}
RepoItem::PullRequest(pr_id) => {
let id = SharedString::from(format!("pr:{pr_id}"));
let workspace_for_build = workspace.clone();
let store = store.clone();
panels::open_detail(
workspace,
id,
move |window, cx| {
cx.new(|cx| {
crate::pull_requests::PullRequestDetailView::new(
workspace_for_build.clone(),
store.clone(),
pr_id,
window,
cx,
)
})
},
window,
cx,
);
}
// Opening a patch series directly is not a feature.
_ => {}
}
}
-526
View File
@@ -1,526 +0,0 @@
use std::collections::HashSet;
use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Axis, Context, Entity, IntoElement, ParentElement as _,
Render, ScrollStrategy, SharedString, Styled as _, Task, UniformListScrollHandle, Window, div,
px, uniform_list,
};
use signed_git::{CommitDiff, DiffStatus, FileCommit, FileDiff, Repo};
use ui::badge::{Badge, BadgeVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::Panel;
use ui::layout::resizable::{Resizable, ResizableState};
use ui::theme::ActiveTheme as _;
use ui::tree::{Tree, TreeItem};
use utils::relative_time_secs;
use super::helpers::{DiffRow, diff_rows, render_diff_row};
use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten};
use crate::shared::widgets::empty_state;
pub struct DiffPane {
diff: Option<CommitDiff>,
seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>,
rows: Vec<TreeRow>,
selected_file: Option<SharedString>,
selected_index: Option<usize>,
/// Rows of the selected file's diff, hunk headers and lines.
diff_rows: Vec<DiffRow>,
scroll_handle: UniformListScrollHandle,
split: Entity<ResizableState>,
}
impl DiffPane {
pub fn new(cx: &mut Context<Self>) -> Self {
Self {
diff: None,
seeds: Vec::new(),
expanded: HashSet::new(),
rows: Vec::new(),
selected_file: None,
selected_index: None,
diff_rows: Vec::new(),
scroll_handle: UniformListScrollHandle::new(),
split: {
let split = ResizableState::new(cx);
split.update(cx, |split, cx| split.set_sizes([px(260.)], cx));
split
},
}
}
pub fn diff(&self) -> Option<&CommitDiff> {
self.diff.as_ref()
}
pub fn set_diff(&mut self, diff: CommitDiff, cx: &mut Context<Self>) {
let mut paths: Vec<PathBuf> = diff
.files
.iter()
.map(|file| PathBuf::from(&file.path))
.collect();
paths.sort();
self.seeds = build_tree_items(&paths);
self.expanded = collect_expanded(&self.seeds);
self.rows = flatten(&self.seeds, &self.expanded);
let first = diff
.files
.first()
.map(|file| SharedString::from(file.path.as_str()));
self.selected_file = first.clone();
self.selected_index = first
.as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
self.diff = Some(diff);
if let Some(path) = first {
self.set_diff_rows(path.as_ref());
} else {
self.diff_rows.clear();
}
cx.notify();
}
pub fn clear(&mut self, cx: &mut Context<Self>) {
self.diff = None;
self.seeds.clear();
self.expanded.clear();
self.rows.clear();
self.selected_file = None;
self.selected_index = None;
self.diff_rows.clear();
cx.notify();
}
fn select_file(&mut self, path: &str, cx: &mut Context<Self>) {
self.selected_file = Some(path.into());
self.selected_index = self.rows.iter().position(|row| row.id == path);
self.set_diff_rows(path);
cx.notify();
}
fn set_diff_rows(&mut self, path: &str) {
let Some(diff) = self.diff.as_ref() else {
return;
};
let Some(file) = diff.files.iter().find(|file| file.path == path) else {
return;
};
self.diff_rows = diff_rows(file);
self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top);
}
fn toggle_folder(&mut self, id: &str, cx: &mut Context<Self>) {
if !self.expanded.remove(id) {
self.expanded.insert(id.to_owned());
}
self.rows = flatten(&self.seeds, &self.expanded);
self.selected_index = self
.selected_file
.as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
cx.notify();
}
fn render_tree_column(&self, cx: &mut Context<Self>) -> AnyElement {
let rows = self.rows.clone();
let selected = self.selected_index;
let view = cx.entity().downgrade();
let change_view = view.clone();
v_flex()
.h_full()
.min_h_0()
.p_2()
.child(
Tree::new("commit-diff-tree")
.selected(selected)
.items(move |_, _| {
rows.iter()
.map(|row| {
let item = TreeItem::new(row.id.clone(), row.label.clone())
.depth(row.depth)
.expandable(row.expandable)
.expanded(row.expanded);
if row.expandable {
item.icon(Icon::named(IconRole::Folder))
} else {
item.icon(Icon::named(IconRole::File))
}
})
.collect()
})
.on_change(move |index, window, cx| {
if let Some(index) = index
&& let Err(error) = change_view.update(cx, |this, cx| {
this.activate_row(index, window, cx);
})
{
log::warn!("failed to activate diff tree row: {error}");
}
})
.on_disclosure({
let view = view;
move |index, _, cx| {
if let Err(error) = view.update(cx, |this, cx| {
let id = this.rows.get(index).map(|row| row.id.clone());
if let Some(id) = id {
this.toggle_folder(&id, cx);
}
}) {
log::warn!("failed to toggle diff folder: {error}");
}
}
}),
)
.into_any_element()
}
fn activate_row(&mut self, index: usize, _window: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.rows.get(index) else {
return;
};
let id = row.id.clone();
let expandable = row.expandable;
self.selected_index = Some(index);
if expandable {
self.toggle_folder(&id, cx);
} else {
self.select_file(&id, cx);
}
}
fn render_detail_column(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(diff) = self.diff.as_ref() else {
return empty_state("No changes");
};
let Some(path) = self.selected_file.clone() else {
return if diff.files.is_empty() {
empty_state("No files changed")
} else {
empty_state("Select a file")
};
};
let Some(file) = diff.files.iter().find(|file| file.path == path.as_ref()) else {
return empty_state("File not found");
};
self.render_file_diff(file, cx)
}
fn render_file_diff(&self, file: &FileDiff, cx: &App) -> AnyElement {
let status_label = match file.status {
DiffStatus::Added => "A",
DiffStatus::Modified => "M",
DiffStatus::Deleted => "D",
DiffStatus::Renamed => "R",
DiffStatus::Copied => "C",
};
let status_color = match file.status {
DiffStatus::Added => cx.theme().ramps.success.base,
DiffStatus::Modified => cx.theme().ramps.info.base,
DiffStatus::Deleted => cx.theme().ramps.destructive.base,
DiffStatus::Renamed | DiffStatus::Copied => cx.theme().colors.muted_foreground,
};
let title = match &file.old_path {
Some(old) => format!("{old} → {}", file.path),
None => file.path.clone(),
};
let body: AnyElement = if file.binary {
empty_state("Diff not available")
} else if file.hunks.is_empty() {
empty_state("No content changes")
} else {
let hunks = file.hunks.clone();
let rows = self.diff_rows.clone();
v_flex()
.size_full()
.relative()
.child(
uniform_list("commit-diff-rows", rows.len(), move |range, _, cx| {
range
.map(|ix| render_diff_row(&hunks, rows[ix], cx))
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(crate::shared::widgets::scroll_overlay(
"commit-diff-scroll",
self.scroll_handle.clone(),
))
.into_any_element()
};
v_flex()
.flex_1()
.min_w_0()
.h_full()
.child(
h_flex()
.px_3()
.h_9()
.gap_2()
.child(
div()
.text_xs()
.font_medium()
.text_color(status_color)
.child(status_label),
)
.child(
div()
.flex_1()
.min_w_0()
.text_xs()
.font_medium()
.text_ellipsis()
.whitespace_nowrap()
.child(title),
)
.when(!file.binary, |this| {
this.child(
h_flex()
.gap_2()
.text_xs()
.child(
Badge::new("file-insertions", format!("+ {}", file.insertions))
.variant(BadgeVariant::Success),
)
.child(
Badge::new("file-deletions", format!("- {}", file.deletions))
.variant(BadgeVariant::Danger),
),
)
}),
)
.child(div().flex_1().min_h_0().child(body))
.into_any_element()
}
}
impl Render for DiffPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let tree = self.render_tree_column(cx);
let detail = self.render_detail_column(cx);
h_flex()
.size_full()
.min_h_0()
.bg(cx.theme().colors.background)
.child(
Resizable::new("commit-diff-split", self.split.clone())
.axis(Axis::Horizontal)
.pane_with_min(tree, px(120.))
.pane_with_min(detail, px(240.))
.flex_1()
.min_w_0()
.h_full(),
)
}
}
pub struct CommitDiffView {
worktree: PathBuf,
commit: FileCommit,
/// The diff is being computed on a background task.
loading: bool,
error: Option<SharedString>,
pane: Entity<DiffPane>,
tasks: Vec<Task<Result<(), anyhow::Error>>>,
}
impl CommitDiffView {
pub fn new(
worktree: PathBuf,
commit_id: String,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let pane = cx.new(DiffPane::new);
let weak = cx.entity().downgrade();
window.defer(cx, move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| this.load(window, cx)) {
log::warn!("failed to load commit diff: {error}");
}
});
Self {
worktree,
commit: FileCommit {
id: commit_id,
summary: String::new(),
description: None,
author: String::new(),
time: 0,
},
loading: true,
error: None,
pane,
tasks: Vec::new(),
}
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), anyhow::Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
fn load(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.loading = true;
self.error = None;
cx.notify();
let worktree = self.worktree.clone();
let id = self.commit.id.clone();
let task: 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 { Repo::open(&worktree).and_then(|repo| repo.commit(&id)) }
})
.await;
let diff = cx
.background_spawn({
let worktree = worktree.clone();
let id = id.clone();
async move { Repo::open(&worktree).and_then(|repo| repo.commit_diff(&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));
}
Err(error) => {
this.error = Some(error.to_string().into());
}
}
cx.notify();
})?;
Ok(())
});
self.push_task(task);
}
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| {
(
diff.files.len(),
diff.files.iter().map(|file| file.insertions).sum(),
diff.files.iter().map(|file| file.deletions).sum(),
)
});
v_flex()
.flex_none()
.px_4()
.py_3()
.w_full()
.gap_2()
.border_b_1()
.border_color(cx.theme().colors.border)
.child(
v_flex()
.child(
div()
.text_sm()
.font_semibold()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
h_flex()
.gap_2()
.text_base()
.child(SharedString::from(format!("{} committed", commit.author)))
.child(
h_flex()
.gap_1()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(&commit.id))
.child(ClipboardButton::new("commit-id", &commit.id)),
)
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
),
),
)
.when_some(commit.description.as_ref(), |this, description| {
this.child(div().text_base().child(SharedString::from(description)))
})
.child(
h_flex()
.gap_2()
.text_xs()
.child(Badge::new("commit-files", format!("{files} files changed")))
.when(insertions > 0, |this| {
this.child(
Badge::new("commit-insertions", format!("+ {insertions}"))
.variant(BadgeVariant::Success),
)
})
.when(deletions > 0, |this| {
this.child(
Badge::new("commit-deletions", format!("- {deletions}"))
.variant(BadgeVariant::Danger),
)
}),
)
.into_any_element()
}
}
impl Panel for CommitDiffView {
fn title(&self, _cx: &App) -> SharedString {
let short = self.commit.id.get(..8).unwrap_or(&self.commit.id);
SharedString::from(format!("Commit {short}"))
}
fn loading(&self, _cx: &App) -> bool {
self.loading
}
}
impl Render for CommitDiffView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let body: AnyElement = if self.loading {
crate::shared::widgets::centered_spinner("commit-diff-loading")
} else if let Some(error) = self.error.clone() {
empty_state(error)
} else {
self.pane.clone().into_any_element()
};
v_flex()
.size_full()
.min_h_0()
.child(self.render_header(cx))
.child(div().flex_1().min_h_0().child(body))
}
}
-255
View File
@@ -1,255 +0,0 @@
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Window, div, px,
};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use signed_core::Announcement;
use ui::avatar::Avatar;
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::theme::ActiveTheme as _;
use utils::middle_truncate;
pub struct AboutDialog {
handle: DialogHandle,
announcement: Announcement,
directory: Entity<ProfileDirectory>,
}
impl AboutDialog {
pub fn new(
announcement: Announcement,
directory: Entity<ProfileDirectory>,
cx: &mut App,
) -> Entity<Self> {
cx.new(|_| Self {
handle: DialogHandle::new(true),
announcement,
directory,
})
}
}
impl Render for AboutDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let announcement = self.announcement.clone();
let directory = self.directory.clone();
Dialog::new("about-dialog")
.handle(self.handle.clone())
.min_width(px(500.))
.title("About")
.content(move |_, cx| announcement_rows(&announcement, &directory, cx))
.into_any_element()
}
}
fn announcement_rows(
announcement: &Announcement,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let mut rows: Vec<AnyElement> = Vec::new();
rows.push(row(
"Name",
text(
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from("-")),
),
cx,
));
rows.push(row(
"Description",
text(
announcement
.description
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from("-")),
),
cx,
));
if !announcement.web.is_empty() {
rows.push(row(
"Web",
list(
"about-web",
announcement.web.iter().map(|url| url.to_string()),
cx,
),
cx,
));
}
if let Some(euc) = &announcement.euc {
rows.push(row(
"Earliest Commit",
copy_value("about-euc", euc.clone(), cx),
cx,
));
}
if let Some(upstream) = &announcement.upstream {
rows.push(row("Upstream", text(upstream.display()), cx));
}
if !announcement.hashtags.is_empty() {
rows.push(row(
"Hashtags",
text(SharedString::from(announcement.hashtags.join(", "))),
cx,
));
}
if !announcement.clone.is_empty() {
rows.push(row(
"Clone URLs",
list(
"about-clone",
announcement.clone.iter().map(|url| url.to_string()),
cx,
),
cx,
));
}
if !announcement.relays.is_empty() {
rows.push(row(
"Grasp Relays",
list(
"about-relays",
announcement.relays.iter().map(|url| url.to_string()),
cx,
),
cx,
));
}
if !announcement.maintainers.is_empty() {
rows.push(row(
"Maintainers",
maintainers(&announcement.maintainers, directory, cx),
cx,
));
}
v_flex().gap_3().w_full().children(rows).into_any_element()
}
fn row(label: &'static str, value: AnyElement, cx: &App) -> AnyElement {
v_flex()
.gap_1()
.min_w_0()
.child(
div()
.text_xs()
.font_medium()
.text_color(cx.theme().colors.muted_foreground)
.child(label),
)
.child(value)
.into_any_element()
}
fn text<T>(value: T) -> AnyElement
where
T: Into<SharedString>,
{
div()
.text_base()
.w_full()
.min_w_0()
.child(value.into())
.into_any_element()
}
fn copy_value(id: &'static str, value: String, cx: &App) -> AnyElement {
h_flex()
.gap_2()
.items_center()
.min_w_0()
.child(
div()
.font_family(cx.theme().mono_font)
.text_xs()
.min_w_0()
.child(SharedString::from(value.clone())),
)
.child(ClipboardButton::new(id, value))
.into_any_element()
}
fn maintainers(
maintainers: &[PublicKey],
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
v_flex()
.gap_2()
.min_w_0()
.children(maintainers.iter().map(|pubkey| {
let profile = directory.read(cx).profile(pubkey, cx);
let name = profile.name();
h_flex()
.gap_2()
.items_center()
.min_w_0()
.child(
Avatar::new(*pubkey)
.name(name.clone())
.picture(profile.picture())
.small(),
)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.text_base()
.child(name),
)
.into_any_element()
}))
.into_any_element()
}
fn list(id: &'static str, items: impl IntoIterator<Item = String>, cx: &App) -> AnyElement {
v_flex()
.gap_2()
.min_w_0()
.children(items.into_iter().enumerate().map(|(ix, item)| {
h_flex()
.h_8()
.px_2()
.gap_2()
.min_w_0()
.bg(cx.theme().colors.secondary)
.rounded(cx.theme().radius.control)
.text_color(cx.theme().colors.secondary_foreground)
.child(
div()
.flex_1()
.min_w_0()
.whitespace_nowrap()
.text_ellipsis()
.text_base()
.child(SharedString::from(middle_truncate(&item, 28, 16))),
)
.child(ClipboardButton::new(
SharedString::from(format!("{id}-{ix}")),
item,
))
.into_any_element()
}))
.into_any_element()
}
@@ -1,282 +0,0 @@
use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _,
PathPromptOptions, Render, Styled as _, Task, WeakEntity, Window, div, px,
};
use settings::SettingsStore;
use signed_state::{Backend, CheckoutsStore};
use ui::button::{Button, ButtonVariant};
use ui::common::{ResultLogErr as _, h_flex, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::tooltip::Tooltip;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::actions::open_repo_panel;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with};
use crate::workspace::Workspace;
/// Progress of the create-repository flow, so async results can be rendered.
pub struct CreateRepoDialog {
workspace: WeakEntity<Workspace>,
handle: DialogHandle,
name_input: Entity<InputState>,
desc_input: Entity<InputState>,
folder_input: Entity<InputState>,
relay_input: Entity<InputState>,
state: Entity<DialogProgress>,
grasp_state: Entity<GraspServersState>,
/// Held so the grasp-server load is cancelled when the dialog drops.
task: Option<Task<()>>,
}
impl CreateRepoDialog {
pub fn new(
workspace: WeakEntity<Workspace>,
window: &mut Window,
cx: &mut App,
) -> Entity<Self> {
let settings = SettingsStore::global(cx);
let grasp_settings = settings.read(cx).settings().grasp_servers.clone();
let name_input = InputState::new(cx);
let desc_input = InputState::builder().multiline().build(cx);
let default_folder = settings
.read(cx)
.settings()
.create_repository
.default_folder
.clone()
.unwrap_or_else(paths::desktop_dir);
let folder_input = InputState::builder()
.text(default_folder.to_string_lossy())
.read_only()
.build(cx);
let relay_input = InputState::new(cx);
let state = cx.new(|_| DialogProgress::default());
let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings));
cx.new(|cx| {
cx.defer_in(window, move |this: &mut Self, window, cx| {
let task = load_user_grasp_servers(this.grasp_state.clone(), window, cx);
this.task = Some(task);
});
Self {
workspace,
handle: DialogHandle::new(true),
name_input,
desc_input,
folder_input,
relay_input,
state,
grasp_state,
task: None,
}
})
}
fn create(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.state.read(cx).busy {
return;
}
let name = self.name_input.read(cx).value().trim().to_owned();
let description = self.desc_input.read(cx).value().trim().to_owned();
let folder = PathBuf::from(self.folder_input.read(cx).value().trim());
let servers = self.grasp_state.read(cx).grasp_servers.clone();
if name.is_empty() {
self.state.update(cx, |state, cx| {
state.fail("Repository name is required");
cx.notify();
});
return;
}
if servers.is_empty() {
self.state.update(cx, |state, cx| {
state.fail("Add at least one grasp server");
cx.notify();
});
return;
}
let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else {
self.state.update(cx, |state, cx| {
state.fail("Sign in to create a repository");
cx.notify();
});
return;
};
let addr =
signed_core::RepoAddr::new(user, signed_core::RepoAddr::identifier_from_name(&name));
self.state.update(cx, |state, cx| {
state.begin_push(addr, cx);
cx.notify();
});
let task = backend.update(cx, |backend, cx| {
backend.create_repository(&name, &description, folder, servers, cx)
});
let state = self.state.clone();
let workspace = self.workspace.clone();
let close = self.handle.clone();
let handle = window.window_handle();
run_dialog_task_with(
task,
cx,
move |(announcement, local_path), cx| {
cx.update_window(handle, |_, window, cx| {
let checkouts = CheckoutsStore::global(cx);
checkouts.update(cx, |store, cx| {
store.record(local_path.clone(), announcement.addr(), cx);
});
cx.open_with_system(&local_path);
open_repo_panel(
&workspace,
&announcement.addr(),
Some(&announcement),
window,
cx,
);
close.close(cx);
})
.log_err();
},
move |error, cx| {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
},
);
}
}
impl Render for CreateRepoDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let name_input = self.name_input.clone();
let desc_input = self.desc_input.clone();
let folder_input = self.folder_input.clone();
let relay_input = self.relay_input.clone();
let state = self.state.clone();
let grasp_state = self.grasp_state.clone();
let action_state = state.clone();
let this = cx.entity().downgrade();
Dialog::new("create-repo-dialog")
.handle(self.handle.clone())
.min_width(px(520.))
.title("Create Repository")
.content(move |_window, cx| {
let progress = state.read(cx);
v_flex()
.gap_3()
.child(
Field::new("repo-name", "Repository Name")
.description("Max 100 characters")
.child(Input::new("repo-name-input", name_input.clone())),
)
.child(
Field::new("repo-description", "Description").child(
Input::new("repo-description-input", desc_input.clone()).rows(3),
),
)
.child(
Field::new("repo-folder", "Folder")
.description("Where the repository's working copy is created.")
.child(
h_flex()
.gap_1()
.w_full()
.child(div().flex_1().child(Input::new(
"repo-folder-input",
folder_input.clone(),
)))
.child(
Button::new("choose-folder")
.icon(Icon::named(IconRole::Folder))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Choose folder"))
.on_click({
let folder_input = folder_input.clone();
move |_, window, cx| {
choose_folder(&folder_input, window, cx);
}
}),
),
),
)
.child(grasp_servers_field(&grasp_state, &relay_input, cx))
.when_some(push_steps_row(&progress.push_steps, cx), |el, steps| {
el.child(steps)
})
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let this = this.clone();
let create: AnyElement = Button::new("create-repository")
.label("Create repository")
.icon(Icon::named(IconRole::Plus))
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.create(window, cx)),
);
})
.into_any_element();
vec![create]
})
}
}
fn choose_folder(folder_input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let store = SettingsStore::global(cx);
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose folder".into()),
});
let handle = window.window_handle();
let folder_input = folder_input.clone();
cx.spawn(async move |cx| {
if let Ok(Ok(Some(mut paths))) = prompt.await
&& let Some(path) = paths.pop()
&& let Err(error) = cx.update_window(handle, |_, window, cx| {
let text = path.to_string_lossy().to_string();
store.update(cx, |store, cx| {
store.edit(
|settings| {
settings.create_repository.default_folder = Some(path.clone());
},
cx,
);
});
folder_input.update(cx, |input, cx| input.set_value(text, window, cx));
})
{
log::warn!("failed to apply selected folder: {error}");
}
})
.detach();
}
@@ -1,279 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, SharedString,
Styled as _, Task, Window, div,
};
use nostr::prelude::RelayUrl;
use settings::{DEFAULT_GRASP_SERVERS, GraspServersSettings};
use signed_state::Backend;
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use crate::shared::progress::error_row;
/// State of the grasp-server section of a publish dialog, so async results can be rendered.
#[derive(Default)]
pub struct GraspServersState {
/// Set while the user's kind `10317` grasp list loads.
pub loading_servers: bool,
pub grasp_servers: Vec<RelayUrl>,
pub servers_enabled: bool,
/// 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 and replaces them.
pub fn new_default(settings: &GraspServersSettings) -> Self {
let urls: Vec<String> = if settings.default_servers.is_empty() {
DEFAULT_GRASP_SERVERS
.iter()
.map(|url| (*url).to_owned())
.collect()
} else {
settings.default_servers.clone()
};
Self {
loading_servers: true,
servers_enabled: false,
grasp_servers: urls
.iter()
.filter_map(|url| RelayUrl::parse(url).ok())
.collect(),
..Default::default()
}
}
}
/// The Grasp servers section shared by the publish dialogs.
pub fn grasp_servers_field(
state: &Entity<GraspServersState>,
relay_input: &Entity<InputState>,
cx: &App,
) -> AnyElement {
let state = state.clone();
let relay_input = relay_input.clone();
let servers = state.read(cx).grasp_servers.clone();
let loading_servers = state.read(cx).loading_servers;
let servers_enabled = state.read(cx).servers_enabled;
let error = state.read(cx).error.clone();
let add_state = state.clone();
let add_input = relay_input.clone();
let toggle_state = state.clone();
v_flex()
.gap_2()
.child(
h_flex()
.justify_between()
.items_center()
.child(div().text_xs().child("Grasp servers"))
.child(
Button::new("toggle-grasp-servers")
.icon(Icon::named(if servers_enabled {
IconRole::ChevronRight
} else {
IconRole::ChevronDown
}))
.small()
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text(if servers_enabled {
"Hide grasp servers"
} else {
"Show grasp servers"
}))
.on_click(move |_, _, cx| {
toggle_state.update(cx, |state, cx| {
state.servers_enabled = !state.servers_enabled;
cx.notify();
});
}),
),
)
.when(servers_enabled, |section| {
section
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child("Where the repository is hosted"),
)
.child(
v_flex().gap_1().children(
servers
.iter()
.enumerate()
.map(|(ix, relay)| render_server_row(ix, relay, state.clone(), cx)),
),
)
.child(
h_flex()
.gap_1()
.items_center()
.child(
div()
.flex_1()
.child(Input::new("grasp-relay-input", relay_input.clone())),
)
.child(
Button::new("add-relay")
.icon(Icon::named(IconRole::Plus))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Add grasp server"))
.on_click(move |_, window, cx| {
add_relay(&add_state, &add_input, window, cx);
}),
),
)
.when(loading_servers, |section| {
section.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child("Loading your grasp servers..."),
)
})
.when_some(error_row(&error, cx), |section, error| section.child(error))
})
.into_any_element()
}
fn render_server_row(
ix: usize,
relay: &RelayUrl,
state: Entity<GraspServersState>,
cx: &App,
) -> AnyElement {
let relay = relay.clone();
h_flex()
.w_full()
.gap_1()
.items_center()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(server_host(&relay)),
)
.child(
Button::new(SharedString::from(format!("remove-relay:{ix}")))
.icon(Icon::named(IconRole::Close))
.variant(ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| {
// A row's index can desync after a prior removal; match by value.
state.update(cx, |state, cx| {
if let Some(at) =
state.grasp_servers.iter().position(|known| known == &relay)
{
state.grasp_servers.remove(at);
cx.notify();
}
});
}),
)
.into_any_element()
}
/// Accepts a bare host as well as a full URL.
fn add_relay(
state: &Entity<GraspServersState>,
input: &Entity<InputState>,
window: &mut Window,
cx: &mut App,
) {
let value = input.read(cx).value().trim().to_owned();
if value.is_empty() {
return;
}
match normalize_server(&value) {
Some((_, relay)) => {
state.update(cx, |state, cx| {
state.error = None;
if !state.grasp_servers.contains(&relay) {
state.grasp_servers.push(relay);
}
cx.notify();
});
input.update(cx, |input, cx| input.set_value("", window, cx));
}
None => {
state.update(cx, |state, cx| {
state.error = Some(format!("Invalid grasp server URL: {value}").into());
cx.notify();
});
}
}
}
/// Loads the user's kind `10317` grasp list from the local database.
pub fn load_user_grasp_servers(
state: Entity<GraspServersState>,
window: &mut Window,
cx: &mut App,
) -> Task<()> {
let backend = Backend::global(cx);
let (user, client) = {
let backend = backend.read(cx);
(backend.current_user(), backend.client())
};
let Some(user) = user else {
state.update(cx, |state, _| state.loading_servers = false);
return Task::ready(());
};
let task =
cx.background_spawn(
async move { signed_state::user_grasp_list_servers(&client, user).await },
);
let handle = window.window_handle();
cx.spawn(async move |cx| {
let result = task.await;
if let Err(error) = cx.update_window(handle, |_, _window, cx| {
state.update(cx, |state, cx| {
state.loading_servers = false;
if let Ok(servers) = result
&& !servers.is_empty()
{
state.grasp_servers = servers;
}
cx.notify();
});
}) {
log::warn!("failed to apply grasp servers: {error}");
}
})
}
/// Normalize a user-typed grasp server, adding a `wss://` scheme when none is given.
pub 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 fn server_host(relay: &RelayUrl) -> SharedString {
relay
.domain()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(relay.to_string()))
}
-298
View File
@@ -1,298 +0,0 @@
use std::path::PathBuf;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Task, WeakEntity, Window, div, px,
};
use settings::SettingsStore;
use signed_core::RepoAddr;
use signed_git::Repo;
use signed_state::Backend;
use ui::button::Button;
use ui::common::{ResultLogErr as _, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::field::Field;
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::select::{Select, SelectOption};
use ui::theme::ActiveTheme as _;
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
use crate::repo::RepoDetailView;
use crate::shared::progress::{DialogProgress, error_row, push_steps_row, run_dialog_task_with};
pub struct InitRepoDialog {
handle: DialogHandle,
local_path: PathBuf,
name_input: Entity<InputState>,
desc_input: Entity<InputState>,
relay_input: Entity<InputState>,
state: Entity<DialogProgress>,
grasp_state: Entity<GraspServersState>,
branches: Vec<SharedString>,
selected_branch: Option<SharedString>,
view: WeakEntity<RepoDetailView>,
/// Held so the grasp-server load is cancelled when the dialog drops.
task: Option<Task<()>>,
}
impl InitRepoDialog {
pub fn new(
local_path: PathBuf,
view: WeakEntity<RepoDetailView>,
window: &mut Window,
cx: &mut App,
) -> Entity<Self> {
let default_name = local_path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let grasp_settings = SettingsStore::global(cx)
.read(cx)
.settings()
.grasp_servers
.clone();
let state = cx.new(|_| DialogProgress::default());
let grasp_state = cx.new(|_| GraspServersState::new_default(&grasp_settings));
let name_input = InputState::builder()
.text(default_name)
.read_only()
.build(cx);
let desc_input = InputState::builder().multiline().build(cx);
let relay_input = InputState::new(cx);
let dialog = cx.new(|cx| {
cx.defer_in(window, move |this: &mut Self, window, cx| {
let task = load_user_grasp_servers(this.grasp_state.clone(), window, cx);
this.task = Some(task);
});
Self {
handle: DialogHandle::new(true),
local_path,
name_input,
desc_input,
relay_input,
state,
grasp_state,
branches: Vec::new(),
selected_branch: None,
view,
task: None,
}
});
load_branches(dialog.clone(), cx);
dialog
}
fn init_repository(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.state.read(cx).busy {
return;
}
let name = self.name_input.read(cx).value().trim().to_owned();
let description = self.desc_input.read(cx).value().trim().to_owned();
let servers = self.grasp_state.read(cx).grasp_servers.clone();
let default_branch = self
.selected_branch
.as_ref()
.map(|branch| branch.trim().to_owned())
.filter(|branch| !branch.is_empty());
if name.is_empty() {
self.state.update(cx, |state, cx| {
state.fail("Repository name is required");
cx.notify();
});
return;
}
if servers.is_empty() {
self.state.update(cx, |state, cx| {
state.fail("Add at least one grasp server");
cx.notify();
});
return;
}
let backend = Backend::global(cx);
let Some(user) = backend.read(cx).current_user() else {
self.state.update(cx, |state, cx| {
state.fail("Sign in to publish a repository");
cx.notify();
});
return;
};
let addr = RepoAddr::new(user, RepoAddr::identifier_from_name(&name));
self.state.update(cx, |state, cx| {
state.begin_push(addr, cx);
cx.notify();
});
let local_path = self.local_path.clone();
let task = backend.update(cx, |backend, cx| {
backend.publish_local_repo(local_path, &name, &description, servers, default_branch, cx)
});
let state = self.state.clone();
let view = self.view.clone();
let close = self.handle.clone();
let handle = window.window_handle();
run_dialog_task_with(
task,
cx,
move |announcement, cx| {
cx.update_window(handle, |_, _window, cx| {
close.close(cx);
if let Some(view) = view.upgrade() {
view.update(cx, |this, cx| this.apply_announcement(announcement, cx));
}
})
.log_err();
},
move |error, cx| {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
},
);
}
}
impl Render for InitRepoDialog {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let name_input = self.name_input.clone();
let desc_input = self.desc_input.clone();
let relay_input = self.relay_input.clone();
let state = self.state.clone();
let grasp_state = self.grasp_state.clone();
let action_state = state.clone();
let this = cx.entity().downgrade();
let folder = self.local_path.display().to_string();
let branches = self.branches.clone();
let selected_branch = self.selected_branch.clone();
Dialog::new("init-repo-dialog")
.handle(self.handle.clone())
.min_width(px(520.))
.title("Initialize repository")
.content(move |_, cx| {
let progress = state.read(cx);
v_flex()
.gap_3()
.child(
div()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child("Publish this local repository to Nostr."),
)
.child(
Field::new("init-name", "Repository name")
.description("Max 100 characters")
.child(Input::new("init-name-input", name_input.clone())),
)
.child(
Field::new("init-description", "Description").child(
Input::new("init-description-input", desc_input.clone()).rows(3),
),
)
.child(
Field::new("init-folder", "Folder")
.description("The local repository being published")
.child(
div()
.h_8()
.w_full()
.px_2()
.bg(cx.theme().colors.muted)
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.rounded(cx.theme().radius.control)
.child(folder.clone()),
),
)
.child(
Field::new("init-branch", "Default branch")
.description("The local branch to announce as the default")
.child(
Select::new("init-branch-select")
.options(
branches
.iter()
.cloned()
.map(|branch| SelectOption::new(branch.clone(), branch))
.collect::<Vec<_>>(),
)
.selected(selected_branch.clone())
.placeholder("Select branch"),
),
)
.child(grasp_servers_field(&grasp_state, &relay_input, cx))
.when_some(push_steps_row(&progress.push_steps, cx), |el, steps| {
el.child(steps)
})
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let this = this.clone();
let init: AnyElement = Button::new("initialize-repository")
.label("Initialize")
.icon(Icon::named(IconRole::Plus))
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
crate::shared::log_dropped(
this.update(cx, |this, cx| this.init_repository(window, cx)),
);
})
.into_any_element();
vec![init]
})
}
}
fn load_branches(dialog: Entity<InitRepoDialog>, cx: &mut App) {
let local_path = dialog.read(cx).local_path.clone();
cx.spawn(async move |cx| {
let loaded = cx
.background_spawn(async move {
let repo = Repo::open(&local_path)?;
let current: Option<SharedString> = repo.current_branch().map(Into::into);
Ok::<_, anyhow::Error>((repo.branches()?, current))
})
.await;
let (branches, current) = match loaded {
Ok(loaded) => loaded,
Err(error) => {
log::warn!("failed to list branches for the default branch selector: {error}");
dialog.update(cx, |dialog, cx| {
dialog.state.update(cx, |state, cx| {
state.fail("Could not list the repository's branches");
cx.notify();
});
});
return;
}
};
dialog.update(cx, |dialog, cx| {
dialog.branches = branches.into_iter().map(Into::into).collect();
dialog.selected_branch = current;
cx.notify();
});
})
.detach();
}
@@ -1,5 +0,0 @@
pub mod about;
pub mod create;
pub mod grasp_servers;
pub mod init;
pub mod reset;
-118
View File
@@ -1,118 +0,0 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
Styled as _, Window, div, px,
};
use signed_state::RepoStore;
use ui::button::{Button, ButtonVariant};
use ui::common::{ResultLogErr as _, v_flex};
use ui::dialog::{Dialog, DialogHandle};
use ui::theme::ActiveTheme as _;
use crate::shared::progress::{DialogProgress, error_row};
pub struct ResetRemoteDialog {
handle: DialogHandle,
store: Entity<RepoStore>,
deleted: Vec<String>,
state: Entity<DialogProgress>,
}
impl ResetRemoteDialog {
pub fn new(store: Entity<RepoStore>, deleted: Vec<String>, cx: &mut App) -> Entity<Self> {
let state = cx.new(|_| DialogProgress::default());
cx.new(|_| Self {
handle: DialogHandle::new(true),
store,
deleted,
state,
})
}
}
impl Render for ResetRemoteDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let deleted = self.deleted.clone();
let store = self.store.clone();
let cancel_close = self.handle.clone();
let confirm_close = self.handle.clone();
let content_state = self.state.clone();
let action_state = self.state.clone();
Dialog::new("reset-remote-dialog")
.handle(self.handle.clone())
.min_width(px(480.))
.title("Reset remote to local")
.content(move |_, cx| {
let progress = content_state.read(cx);
v_flex()
.gap_2()
.child(
div().text_base()
.text_color(cx.theme().colors.muted_foreground)
.child(
"Grasp servers are overwritten to match the local mirror. Refs that do not exist locally are deleted from the servers. This cannot be undone.",
),
)
.child(if deleted.is_empty() {
div().text_base()
.text_color(cx.theme().colors.muted_foreground)
.child("No server refs will be deleted.")
.into_any_element()
} else {
v_flex()
.gap_1()
.children(deleted.iter().map(|name| {
div().text_base()
.font_family(cx.theme().mono_font)
.child(name.clone())
}))
.into_any_element()
})
.when_some(error_row(&progress.error, cx), |el, error| el.child(error))
.into_any_element()
})
.actions(move |_, cx| {
let busy = action_state.read(cx).busy;
let store = store.clone();
let cancel_close = cancel_close.clone();
let confirm_close = confirm_close.clone();
let confirm_state = action_state.clone();
let cancel: AnyElement = Button::new("cancel-reset-remote")
.label("Cancel")
.variant(ButtonVariant::Secondary)
.on_click(move |_, _, cx| cancel_close.close(cx))
.into_any_element();
let confirm: AnyElement = Button::new("confirm-reset-remote")
.label("Reset remote")
.variant(ButtonVariant::Destructive)
.loading(busy)
.disabled(busy)
.on_click(move |_, window, cx| {
let task = store.update(cx, |store, cx| store.reset_repository(cx));
let state = confirm_state.clone();
let close = confirm_close.clone();
let handle = window.window_handle();
cx.spawn(async move |cx| match task.await {
Ok(()) => {
cx.update_window(handle, |_, _, cx| close.close(cx))
.log_err();
}
Err(error) => {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
}
})
.detach();
})
.into_any_element();
vec![cancel, confirm]
})
}
}
-723
View File
@@ -1,723 +0,0 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Component, Path, PathBuf};
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, EventEmitter, IntoElement,
ParentElement as _, SharedString, Styled as _, Task, WeakEntity, Window, div, px,
};
use signed_git::{FileCommit, Repo, WorktreeSnapshot};
use ui::code::CodeViewState;
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::markdown::MarkdownViewState;
use ui::theme::ActiveTheme as _;
use ui::tree::{Tree, TreeItem};
use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash};
use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten};
use crate::shared::widgets::empty_state;
const MAX_PREVIEW_BYTES: usize = 1024 * 1024;
const MAX_PREVIEWED_FILES: usize = 32;
const MAX_PREVIEW_CACHE_BYTES: usize = 8 * 1024 * 1024;
/// The tree picked a folder or file, so the repository panel should show Files.
#[derive(Clone, Copy, Debug)]
pub enum RepoFilesEvent {
Activated,
}
enum FileContent {
Text(String),
Binary,
TooLarge,
Failed(String),
}
struct MarkdownView {
/// `None` means the repository README.
path: Option<SharedString>,
state: Entity<MarkdownViewState>,
/// 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<CodeViewState>,
/// Hash of the source, so the same document is not re-parsed on a refresh.
source_hash: u64,
}
pub struct RepoFilesView {
seeds: Vec<TreeItemSeed>,
expanded: HashSet<String>,
rows: Vec<TreeRow>,
selected_index: Option<usize>,
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 EventEmitter<RepoFilesEvent> for RepoFilesView {}
impl RepoFilesView {
pub fn new(_cx: &mut Context<Self>) -> Self {
Self {
seeds: Vec::new(),
expanded: HashSet::new(),
rows: Vec::new(),
selected_index: None,
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 fn set_worktree(&mut self, path: PathBuf) {
self.worktree = Some(path);
}
pub fn apply_entries(
&mut self,
tree: Vec<TreeItemSeed>,
paths: Vec<String>,
cx: &mut Context<Self>,
) {
self.worktree_paths = paths;
self.seeds = tree;
let folder_ids = collect_expanded(&self.seeds);
self.expanded.retain(|id| folder_ids.contains(id));
self.rebuild_rows();
cx.notify();
}
fn rebuild_rows(&mut self) {
self.rows = flatten(&self.seeds, &self.expanded);
self.selected_index = self
.selected_file
.as_ref()
.and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref()));
}
fn toggle_folder(&mut self, id: &str) {
if !self.expanded.remove(id) {
self.expanded.insert(id.to_owned());
}
self.rebuild_rows();
}
/// Point the README pane at `path`/`bytes`, or clear it when absent.
pub 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 fn clear_previews(&mut self) {
self.selected_file = None;
self.selected_index = 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.
pub 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 activate_row(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.rows.get(index) else {
return;
};
let id = row.id.clone();
let expandable = row.expandable;
self.selected_index = Some(index);
// Folder disclosure now toggles from the tree's row click handler.
if !expandable {
self.open_file(&id, window, cx);
}
cx.emit(RepoFilesEvent::Activated);
cx.notify();
}
pub fn render_tree(&self, view: WeakEntity<Self>) -> AnyElement {
let rows = self.rows.clone();
let selected = self.selected_index;
let change_view = view.clone();
let disclosure_view = view;
div()
.flex_1()
.min_h_0()
.w_full()
.child(
Tree::new("repo-tree")
.selected(selected)
.items(move |_, _| {
rows.iter()
.map(|row| {
let item = TreeItem::new(row.id.clone(), row.label.clone())
.depth(row.depth)
.expandable(row.expandable)
.expanded(row.expanded);
if row.expandable {
item.icon(Icon::named(IconRole::Folder))
} else {
item.icon(Icon::named(IconRole::File))
}
})
.collect()
})
.on_change({
let view = change_view;
move |index, window, cx| {
if let Some(index) = index
&& let Err(error) = view.update(cx, |this, cx| {
this.activate_row(index, window, cx);
})
{
log::warn!("failed to activate tree row: {error}");
}
}
})
.on_disclosure({
let view = disclosure_view;
move |index, _, cx| {
if let Err(error) = view.update(cx, |this, cx| {
let id = this.rows.get(index).map(|row| row.id.clone());
if let Some(id) = id {
this.toggle_folder(&id);
cx.emit(RepoFilesEvent::Activated);
cx.notify();
}
}) {
log::warn!("failed to toggle folder: {error}");
}
}
}),
)
.into_any_element()
}
pub fn render_content(&self, cx: &App) -> AnyElement {
let pane_title = self.pane_title();
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()))
} else {
self.code_element(path.as_ref())
}
}
Some(FileContent::Binary) => empty_state("Binary file - preview not supported"),
Some(FileContent::TooLarge) => empty_state("File is too large to preview"),
Some(FileContent::Failed(message)) => empty_state(message),
None => preview_spinner(),
}
} else if self.readme_name.is_some() {
self.markdown_element(None)
} else {
empty_state("No README found")
};
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().colors.muted)
.border_b_1()
.border_color(cx.theme().colors.border)
.text_color(cx.theme().colors.muted_foreground)
.child(
div()
.text_xs()
.font_medium()
.text_ellipsis()
.whitespace_nowrap()
.child(pane_title),
)
.when_some(commit, |this, commit| {
this.child(
h_flex()
.flex_1()
.gap_1()
.child(
div()
.text_xs()
.font_family(cx.theme().mono_font)
.child(commit.id.clone()),
)
.child(
div()
.max_w(px(250.))
.text_xs()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
),
)
}),
)
.child(div().flex_1().min_h_0().child(body))
.into_any_element()
}
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;
}
if let Some(md) = self.md.take()
&& md.path == path
{
md.state.update(cx, |state, cx| {
state.set_source(text, cx);
});
self.md = Some(MarkdownView {
path,
state: md.state,
source_hash: hash,
});
return true;
}
let state = cx.new(|_| MarkdownViewState::new("repo-readme", text));
self.md = Some(MarkdownView {
path,
state,
source_hash: hash,
});
true
}
fn markdown_element(&self, path: Option<&str>) -> 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();
}
div()
.p_4()
.size_full()
.overflow_hidden()
.child(md.state.clone())
.into_any_element()
}
fn set_code(&mut self, path: SharedString, text: &str, cx: &mut Context<Self>) {
let hash = source_hash(text);
let language = code_language(path.as_ref());
if let Some(code) = &self.code
&& code.path == path
&& code.source_hash == hash
{
return;
}
if let Some(code) = self.code.take()
&& code.path == path
{
code.state.update(cx, |state, cx| {
state.set_source(text, language, cx);
});
self.code = Some(CodeView {
path,
state: code.state,
source_hash: hash,
});
return;
}
let state = cx.new(|cx| CodeViewState::new("repo-code", text, language, cx));
self.code = Some(CodeView {
path,
state,
source_hash: hash,
});
}
fn code_element(&self, path: &str) -> AnyElement {
let Some(code) = &self.code else {
return preview_spinner();
};
if code.path.as_ref() != path {
return preview_spinner();
}
div()
.size_full()
.overflow_hidden()
.child(code.state.clone())
.into_any_element()
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
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, 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;
};
// Tree paths originate from git, so symlink escapes are accepted; only
// crafted components are rejected, and visibly.
if unsafe_path {
self.files.insert(
path.to_string(),
FileContent::Failed("Cannot open file".into()),
);
cx.notify();
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, 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.push_task(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 Some(path) = self.file_order.pop_front() else {
break;
};
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().and_then(|md| md.path.as_deref()) == 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 {
Repo::open_cached(&worktree).and_then(|repo| repo.last_commits(&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.push_task(task);
}
}
-455
View File
@@ -1,455 +0,0 @@
use std::collections::HashSet;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, Context, InteractiveElement as _, IntoElement, ParentElement as _, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use signed_state::{Backend, Nip34Kind};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable, StyledExt as _, h_flex, v_flex};
use ui::dropdown_menu::DropdownMenu;
use ui::icons::{Icon, IconRole};
use ui::menu::MenuItem;
use ui::popover::Popover;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use utils::relative_time_secs;
use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name};
use super::{RepoDetailView, actions, dialogs};
use crate::shared::widgets::clone_row;
impl RepoDetailView {
pub(super) fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(addr) = self
.announcement(cx)
.and_then(|announcement| announcement.upstream.as_ref())
.and_then(|upstream| upstream.addr.clone())
else {
return;
};
actions::open_repo_panel(&self.workspace, &addr, None, window, cx);
}
/// Open the dialog that publishes the local repository to NIP-34.
fn open_init_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(local_path) = self.store.read(cx).path.clone() else {
return;
};
self.init = Some(dialogs::init::InitRepoDialog::new(
local_path,
cx.entity().downgrade(),
window,
cx,
));
cx.notify();
}
pub(super) fn render_about(&mut self, cx: &mut Context<Self>) -> AnyElement {
if self.store.read(cx).addr().is_none() {
return self.render_init_banner(cx);
}
let backend = Backend::global(cx);
let store = self.store.read(cx);
let pushing = store.pushing;
let cloning = store.cloning;
let Some(announcement) = store.announcement.clone() else {
return div().into_any_element();
};
let nip05 = self
.directory
.read(cx)
.profile(&announcement.owner, cx)
.metadata()
.nip05
.clone()
.filter(|nip05| !nip05.trim().is_empty());
let nostr_url = nostr_clone_url(&announcement, nip05.as_deref());
let ngit_command = SharedString::from(format!("git clone {nostr_url}"));
let nak_command = SharedString::from(format!("nak git clone {nostr_url}"));
let git_commands: Vec<String> = announcement.clone_urls();
let name = repo_display_name(self.store.read(cx));
let description = announcement.description();
let avatar = Avatar::new(format!("{}:{}", announcement.owner, announcement.id));
let announcement_for_menu = announcement.clone();
let weak_menu_open = cx.entity().downgrade();
let weak_menu_items = cx.entity().downgrade();
let weak_clone = cx.entity().downgrade();
let weak_download = cx.entity().downgrade();
let ngit_for_popover = ngit_command.clone();
let nak_for_popover = nak_command.clone();
let git_for_popover = git_commands.clone();
h_flex()
.p_6()
.w_full()
.gap_6()
.items_start()
.justify_between()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.text_sm()
.font_semibold()
.child(avatar)
.child(name),
)
.child(
div()
.min_w_0()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.line_clamp(3)
.child(description),
)
.when_some(fork_row(&announcement, cx), |this, row| this.child(row)),
)
.child(
h_flex()
.flex_none()
.gap_2()
.justify_end()
.child(
Popover::new("code-popover")
.open(self.clone_open)
.on_change(move |open, _, cx| {
if let Err(error) = weak_clone.update(cx, |this, cx| {
this.clone_open = open;
cx.notify();
}) {
log::warn!("failed to update clone popover: {error}");
}
})
.trigger(move |_, _| {
Button::new("code")
.label("Code")
.icon(Icon::named(IconRole::GitClone))
.tooltip(Tooltip::text("Clone repository"))
.loading(cloning)
.disabled(cloning)
.into_any_element()
})
.content(move |_, cx| {
v_flex()
.w(px(440.))
.p_3()
.gap_4()
.child(clone_group(
"Clone with ngit",
"copy-ngit".into(),
&ngit_for_popover,
cx,
))
.child(clone_group(
"Clone with nak",
"copy-nak".into(),
&nak_for_popover,
cx,
))
.child(
v_flex()
.gap_1()
.child(
div()
.text_xs()
.font_semibold()
.child("Grasp Servers"),
)
.when(git_for_popover.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_center()
.text_color(
cx.theme().colors.muted_foreground,
)
.child("No git clone urls."),
)
})
.children(git_for_popover.iter().enumerate().map(
|(ix, command)| {
clone_row(
SharedString::from(format!(
"copy-git-{ix}"
)),
command.clone().into(),
cx,
)
},
)),
)
.child(
h_flex().justify_end().child(
Button::new("download")
.icon(Icon::named(IconRole::GitClone))
.label("Download")
.on_click({
let weak = weak_download.clone();
move |_, window, cx| {
if let Err(error) =
weak.update(cx, |this, cx| {
this.clone_to_folder(window, cx);
})
{
log::warn!("failed to clone: {error}");
}
}
}),
),
)
.into_any_element()
}),
)
.child(
DropdownMenu::new("repo-menu")
.icon(IconRole::EllipsisVertical)
.variant(ButtonVariant::Ghost)
.disabled(pushing)
.open(self.repo_menu_open)
.on_open_change(move |open, _, cx| {
if let Err(error) = weak_menu_open.update(cx, |this, cx| {
this.repo_menu_open = open;
cx.notify();
}) {
log::warn!("failed to update repo menu: {error}");
}
})
.items(move |_, cx| {
let owner = backend.read(cx).current_user()
== Some(announcement_for_menu.owner);
let mut items = vec![MenuItem::new("About").handler({
let weak = weak_menu_items.clone();
let announcement = announcement_for_menu.clone();
move |_, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.about = Some(dialogs::about::AboutDialog::new(
announcement.clone(),
this.directory.clone(),
cx,
));
cx.notify();
}) {
log::warn!("failed to open about: {error}");
}
}
})];
if owner {
items.push(MenuItem::new("Republish").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.push_repository(window, cx);
}) {
log::warn!("failed to republish: {error}");
}
}
}));
items.push(MenuItem::new("Reset remote to local").handler({
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.reset_remote(window, cx);
}) {
log::warn!("failed to reset remote: {error}");
}
}
}));
items.push(MenuItem::separator());
items.push(MenuItem::new("Delete").destructive(true).handler(
{
let weak = weak_menu_items.clone();
move |window, cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.delete_repository(window, cx);
}) {
log::warn!("failed to delete: {error}");
}
}
},
));
}
items
}),
),
)
.into_any_element()
}
fn render_init_banner(&self, cx: &mut Context<Self>) -> AnyElement {
let binding = self
.store
.read(cx)
.nip34
.as_ref()
.filter(|binding| binding.kind == Nip34Kind::Initialized);
let path = self
.store
.read(cx)
.path
.as_ref()
.map(|path| path.display().to_string())
.unwrap_or_default();
v_flex()
.flex_none()
.p_6()
.h_32()
.w_full()
.items_center()
.justify_center()
.gap_2()
.map(|this| match binding {
Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)),
None => this.child(
Button::new("init")
.icon(Icon::named(IconRole::ArrowUp))
.label("Initialize on Nostr")
.tooltip(Tooltip::text("Publish this repository to Nostr"))
.on_click(cx.listener(|this, _, window, cx| {
this.open_init_dialog(window, cx);
})),
),
})
.child(
div()
.min_w_0()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(path),
)
.into_any_element()
}
pub(super) fn render_metadata(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.px_6()
.h_12()
.w_full()
.gap_4()
.items_center()
.justify_between()
.child(self.render_maintainers(cx))
.child(self.render_ref_controls(cx))
.into_any_element()
}
fn render_ref_controls(&self, cx: &mut Context<Self>) -> AnyElement {
h_flex()
.justify_end()
.flex_none()
.gap_2()
.when_some(self.render_last_commit(cx), |this, commit| {
this.child(commit)
})
.child(self.refs.branch_select.clone())
.child(self.refs.tag_select.clone())
.into_any_element()
}
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let commit = self.head_commit.as_ref()?;
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
let history = self.history.clone();
let commit_id = commit.id.clone();
Some(
h_flex()
.id("last-commit")
.h_8()
.px_2()
.gap_2()
.min_w_0()
.rounded(cx.theme().radius.control)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.tooltip(Tooltip::text("View latest commit"))
.on_click(move |_, window, cx| {
history.update(cx, |history, cx| {
history.open_commit_diff(&commit_id, window, cx);
});
})
.child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground))
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(short)),
)
.child(
div()
.max_w(px(220.))
.text_sm()
.text_ellipsis()
.whitespace_nowrap()
.child(commit.summary.clone()),
)
.child(
div()
.text_sm()
.text_color(cx.theme().colors.muted_foreground)
.child(relative_time_secs(commit.time)),
)
.into_any_element(),
)
}
fn render_maintainers(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(announcement) = self.announcement(cx) else {
return div().into_any_element();
};
let mut seen = HashSet::new();
let rest: Vec<_> = announcement
.maintainers
.iter()
.copied()
.filter(|key| key != &announcement.owner && seen.insert(*key))
.collect();
let owner = self.directory.read(cx).profile(&announcement.owner, cx);
let owner_name = owner.name();
h_flex()
.min_w_0()
.gap_2()
.child(
h_flex()
.gap_2()
.child(
Avatar::new(announcement.owner)
.name(owner_name.clone())
.picture(owner.picture())
.small(),
)
.child(div().text_xs().whitespace_nowrap().child(owner_name)),
)
.when(!rest.is_empty(), |this| {
this.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!("+{}", rest.len()))),
)
})
.into_any_element()
}
}
-466
View File
@@ -1,466 +0,0 @@
use std::path::{Path, PathBuf};
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use metadata::ProfileDirectory;
use nostr::prelude::{RelayUrl, ToBech32};
use signed_core::Announcement;
use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo, WorktreeSnapshot};
use signed_state::{Nip34Binding, RepoListStore, RepoStore};
use ui::avatar::Avatar;
use ui::combobox::ComboboxState;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::ActiveTheme as _;
use utils::relative_time_secs;
use super::RepoDetailView;
use crate::shared::tree::{TreeItemSeed, build_tree_items, sorted_worktree_paths};
const GUTTER_WIDTH: f32 = 44.;
pub const DIFF_ROW_HEIGHT: f32 = 20.;
pub const COMMIT_ROW_HEIGHT: f32 = 56.;
/// The announcement's name, falling back to its id.
pub fn announcement_display_name(announcement: &Announcement) -> SharedString {
announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()))
}
/// The first eight hex characters of an object id, for row labels.
pub fn short_id(hex: &str) -> SharedString {
SharedString::from(hex.get(..8).unwrap_or(hex).to_owned())
}
/// Snapshots the worktree and derives the explorer's tree rows and paths.
pub(super) fn snapshot_worktree(
worktree: PathBuf,
) -> Result<(WorktreeSnapshot, Vec<TreeItemSeed>, Vec<String>), Error> {
let snapshot = Repo::open(&worktree)?.snapshot()?;
let tree = build_tree_items(&snapshot.entries);
let paths = sorted_worktree_paths(&snapshot.entries);
Ok((snapshot, tree, paths))
}
#[derive(Clone, Copy)]
pub(super) enum DiffRow {
Hunk {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
},
Line {
hunk: usize,
line: usize,
},
}
pub(super) struct RepoData {
pub(super) tree: Vec<TreeItemSeed>,
pub(super) entries: Vec<PathBuf>,
pub(super) readme_path: Option<PathBuf>,
pub(super) readme: Option<Vec<u8>>,
pub(super) worktree: Option<PathBuf>,
pub(super) branches: Vec<String>,
pub(super) tags: Vec<String>,
pub(super) current_branch: Option<String>,
pub(super) head_commit: Option<FileCommit>,
}
pub(super) fn clone_group(
label: &str,
id: SharedString,
command: &SharedString,
cx: &App,
) -> AnyElement {
v_flex()
.gap_1()
.min_w_0()
.child(
div()
.text_xs()
.font_semibold()
.child(SharedString::from(label)),
)
.child(crate::shared::widgets::clone_row(id, command.clone(), cx))
.into_any_element()
}
pub(super) fn nostr_clone_url(announcement: &Announcement, nip05: Option<&str>) -> SharedString {
let owner = announcement.owner;
let user = nip05
.map(str::to_owned)
.unwrap_or_else(|| owner.to_bech32().unwrap_or_else(|_| owner.to_string()));
let mut url = format!("nostr://{user}");
if let Some(hint) = announcement.relays.first().and_then(RelayUrl::domain) {
url.push('/');
url.push_str(hint);
}
url.push('/');
url.push_str(&announcement.id);
SharedString::from(url)
}
pub(super) fn fork_row(
announcement: &Announcement,
cx: &mut Context<RepoDetailView>,
) -> Option<AnyElement> {
let upstream = announcement.upstream.as_ref()?;
let (label, clickable) = match &upstream.addr {
Some(addr) => {
let name = RepoListStore::global(cx)
.read(cx)
.announcements
.iter()
.find(|a| a.addr() == *addr)
.map(|a| {
a.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(a.id.clone()))
})
.unwrap_or_else(|| SharedString::from(addr.identifier().to_owned()));
(SharedString::from(format!("Forked from {name}")), true)
}
None => (SharedString::from(upstream.display().as_str()), false),
};
let row = h_flex()
.gap_1()
.min_w_0()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child(Icon::named(IconRole::GitBranch).small())
.child(div().whitespace_nowrap().text_ellipsis().child(label));
Some(if clickable {
row.id("fork-upstream")
.cursor_pointer()
.on_click(cx.listener(|this, _, window, cx| this.open_upstream(window, cx)))
.into_any_element()
} else {
row.into_any_element()
})
}
pub(super) fn load_repo_data(repo: &Repo) -> Result<RepoData, Error> {
let snapshot = repo.snapshot()?;
let worktree = repo.workdir().map(Path::to_path_buf);
let tree = build_tree_items(&snapshot.entries);
Ok(RepoData {
tree,
entries: snapshot.entries,
readme_path: snapshot.readme_path,
readme: snapshot.readme,
worktree,
branches: snapshot.branches,
tags: snapshot.tags,
current_branch: snapshot.current_branch,
head_commit: snapshot.head_commit,
})
}
/// The announcement's name or ID for announced repositories, the directory name for local ones.
pub fn repo_display_name(store: &RepoStore) -> SharedString {
if store.addr().is_none() {
return store
.path
.as_ref()
.map(|path| {
SharedString::from(
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string()),
)
})
.unwrap_or_default();
}
store
.announcement
.as_ref()
.map(announcement_display_name)
.unwrap_or_default()
}
/// The owner and identifier a local repository is already bound to.
pub(super) fn bound_repo_label(
binding: &Nip34Binding,
directory: &Entity<ProfileDirectory>,
cx: &App,
) -> AnyElement {
let profile = binding.owner.map(|pk| directory.read(cx).profile(&pk, cx));
h_flex()
.flex_shrink_0()
.gap_2()
.text_base()
.child("Initialized by")
.text_color(cx.theme().colors.muted_foreground)
.when_some(profile, |this, profile| {
let name = profile.name();
this.child(
h_flex()
.gap_1()
.text_color(cx.theme().colors.foreground)
.child(
Avatar::new(profile.public_key())
.name(name.clone())
.picture(profile.picture())
.small(),
)
.child(name),
)
})
.when_some(binding.identifier.as_deref(), |this, ident| {
this.child(
div()
.text_xs()
.font_medium()
.child(SharedString::from(format!("/{ident}"))),
)
})
.into_any_element()
}
/// Computes a source hash from the given text.
pub(super) 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()
}
pub(super) fn preview_spinner() -> AnyElement {
crate::shared::widgets::centered_spinner("repo-preview-spinner")
}
/// The kit grammar for a path; only four languages are supported.
pub(super) fn code_language(path: &str) -> ui::highlight::Language {
use ui::highlight::Language;
match Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_ascii_lowercase())
.as_deref()
{
Some("rs") => Language::Rust,
Some("ts" | "mts" | "cts" | "tsx") => Language::TypeScript,
Some("js" | "mjs" | "cjs" | "jsx") => Language::JavaScript,
Some("py") => Language::Python,
_ => Language::Plain,
}
}
/// 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) 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
}
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)
.text_xs()
.bg(cx.theme().colors.muted)
.border_y_1()
.border_color(cx.theme().colors.border)
.text_color(cx.theme().colors.muted_foreground)
.child(SharedString::from(format!(
"@@ -{},{} +{},{} @@",
old_start, old_lines, new_start, new_lines
)))
.into_any_element(),
DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) {
Some(line) => render_diff_line(line, cx),
// A stale row index renders as a blank row rather than panicking.
None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(),
},
}
}
fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement {
let bg = match line.kind {
DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)),
DiffLineKind::Deletion => Some(cx.theme().ramps.destructive.base.opacity(0.2)),
DiffLineKind::Context => None,
};
let gutter = cx.theme().colors.muted_foreground;
h_flex()
.w_full()
.h(px(DIFF_ROW_HEIGHT))
.font_family(cx.theme().mono_font)
.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().colors.foreground)
.child(line.text.clone()),
)
.into_any_element()
}
pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit,
action: Option<AnyElement>,
on_click: impl Fn(&mut Window, &mut gpui::App) + 'static,
cx: &gpui::App,
) -> gpui::AnyElement {
h_flex()
.id(ix)
.px_4()
.h(px(COMMIT_ROW_HEIGHT))
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.justify_center()
.child(
h_flex()
.gap_2()
.overflow_hidden()
.child(
div()
.font_family(cx.theme().mono_font)
.text_sm()
.text_color(cx.theme().colors.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().colors.muted_foreground)
.child(commit.author.clone())
.child(relative_time_secs(commit.time)),
),
)
.when_some(action, |row, action| row.child(action))
.on_click(move |_, window, cx| on_click(window, cx))
.into_any_element()
}
pub(super) fn sync_selector(
select: &Entity<ComboboxState<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() != Some(value));
if !items_changed && !selection_changed {
return false;
}
select.update(cx, |state, cx| {
if items_changed {
state.set_options(
items
.iter()
.map(|item| (item.clone(), item.clone()))
.collect(),
cx,
);
}
if let Some(value) = selected
&& (items_changed || selection_changed)
{
state.set_selected(Some(value), window, cx);
}
});
*cached = items;
true
}
-283
View File
@@ -1,283 +0,0 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::Error;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div,
};
use signed_git::{CommitList, FileCommit, Repo};
use signed_state::{Backend, RepoStore, SyncStatusDirectory};
use ui::alert::{Alert, AlertSeverity, AlertStyle};
use ui::button::{Button, ButtonVariant};
use ui::common::{Sizable as _, v_flex};
use ui::icons::{Icon, IconRole};
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use super::RepoDetailView;
use super::commit_diff::CommitDiffView;
use crate::shared::event_list::commit_list;
use crate::shared::panels;
use crate::workspace::Workspace;
pub struct RepoHistoryView {
store: Entity<RepoStore>,
workspace: WeakEntity<Workspace>,
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
worktree: Option<PathBuf>,
all_commits: Option<Arc<CommitList>>,
loading_all_commits: bool,
/// The loaded commit list, shared with the render without a per-frame copy.
commits: Arc<Vec<FileCommit>>,
/// The last load failure, shown instead of the empty list.
error: Option<SharedString>,
scroll_handle: UniformListScrollHandle,
tasks: Vec<Task<Result<(), Error>>>,
}
impl RepoHistoryView {
pub fn new(
store: Entity<RepoStore>,
workspace: WeakEntity<Workspace>,
detail: WeakEntity<RepoDetailView>,
sync_directory: Entity<SyncStatusDirectory>,
) -> Self {
Self {
store,
workspace,
detail,
sync_directory,
worktree: None,
all_commits: None,
loading_all_commits: false,
commits: Arc::new(Vec::new()),
error: None,
scroll_handle: UniformListScrollHandle::new(),
tasks: Vec::new(),
}
}
pub fn set_worktree(&mut self, path: Option<PathBuf>) {
self.worktree = path;
}
pub fn worktree(&self) -> Option<&Path> {
self.worktree.as_deref()
}
/// Number of commits reachable from HEAD, for the Commits tab label.
pub fn commit_count(&self) -> Option<usize> {
self.all_commits.as_ref().map(|list| list.total)
}
/// Drop the current list and walk HEAD again.
pub fn reload(&mut self, cx: &mut Context<Self>) {
self.all_commits = None;
self.loading_all_commits = false;
self.load(cx);
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task);
}
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 {
Repo::open_cached(&worktree).and_then(|repo| repo.all_commits())
})
.await;
this.update(cx, |this, cx| {
match result {
Ok(list) => {
this.commits = Arc::new(list.commits.clone());
this.all_commits = Some(Arc::new(list));
this.error = None;
}
Err(error) => this.error = Some(error.to_string().into()),
}
this.loading_all_commits = false;
cx.notify();
})?;
Ok(())
});
self.push_task(task);
}
pub 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 store = self.store.clone();
let commit_id = commit_id.to_owned();
let id = match store.read(cx).addr() {
Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")),
None => SharedString::from(format!("commit:{}:{}", worktree.display(), commit_id)),
};
let workspace = self.workspace.clone();
panels::open_detail(
&workspace,
id,
move |window, cx| {
cx.new(|cx| CommitDiffView::new(worktree.clone(), commit_id.clone(), window, cx))
},
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 {
crate::shared::widgets::centered_spinner("commits-loading")
} else if let Some(error) = self.error.clone() {
let weak = cx.entity().downgrade();
v_flex()
.size_full()
.items_center()
.justify_center()
.child(
Alert::new("commits-error")
.severity(AlertSeverity::Danger)
.title("Failed to load commits")
.message(error)
.style(AlertStyle::Inline)
.on_dismiss(move |cx| {
if let Err(error) = weak.update(cx, |this, cx| {
this.error = None;
cx.notify();
}) {
log::warn!("failed to dismiss commits error: {error}");
}
}),
)
.into_any_element()
} else {
crate::shared::widgets::empty_state("Failed to load commits")
};
};
if self.commits.is_empty() {
return crate::shared::widgets::empty_state("No commits found");
}
let commits = Arc::clone(&self.commits);
let shown = commits.len();
let total = list.total;
let view = cx.entity().downgrade();
let detail = self.detail.clone();
let user = Backend::global(cx).read(cx).current_user();
let author = user.is_some_and(|user| self.store.read(cx).is_author(&user));
let checkout = self.worktree.clone();
let ahead = self
.store
.read(cx)
.addr()
.cloned()
.filter(|_| author)
.map(|addr| {
self.sync_directory.read_with(cx, |directory, cx| {
directory.ahead_commits_of(&addr, checkout.as_deref(), cx)
})
})
.unwrap_or_default();
let pushing = self.store.read(cx).pushing;
let list = commit_list(
"commits",
"commits-scroll",
commits,
self.scroll_handle.clone(),
move |ix, commit, _| {
ahead
.iter()
.find(|(id, _)| id.starts_with(commit.id.as_str()))
.map(|(ahead_id, path)| {
let detail = detail.clone();
let path = path.clone();
let target = ahead_id.clone();
let short = commit.id.clone();
Button::new(("sync-commit", ix))
.label("Sync")
.icon(Icon::named(IconRole::ArrowUp))
.variant(ButtonVariant::Secondary)
.small()
.disabled(pushing)
.tooltip(Tooltip::text(format!("Sync up to {short}")))
.on_click(move |_, window, cx| {
cx.stop_propagation();
if let Some(detail) = detail.upgrade() {
detail.update(cx, |this, cx| {
this.sync_checkout_commit(
path.clone(),
target.clone(),
window,
cx,
);
});
}
})
.into_any_element()
})
},
move |commit, window, cx| {
if let Err(error) = view.update(cx, |this, cx| {
this.open_commit_diff(&commit.id, window, cx);
}) {
log::warn!("failed to open commit diff: {error}");
}
},
cx,
);
v_flex()
.relative()
.flex_1()
.w_full()
.min_h_0()
.child(list)
.when(shown < total, |this| {
this.child(
div()
.py_2()
.w_full()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(format!("Showing {shown} of {total} commits")),
)
})
.into_any_element()
}
}
File diff suppressed because it is too large Load Diff
-103
View File
@@ -1,103 +0,0 @@
use gpui::{App, AppContext as _, Entity, SharedString, WeakEntity, Window};
use ui::combobox::{Combobox, ComboboxState};
use ui::icons::{IconRole, icon};
use super::RepoDetailView;
use super::helpers::sync_selector;
pub(super) struct RefSwitcher {
pub(super) branch_select: Entity<ComboboxState<SharedString>>,
pub(super) tag_select: Entity<ComboboxState<SharedString>>,
ref_branches: Vec<SharedString>,
ref_tags: Vec<SharedString>,
pub(super) switching_ref: bool,
}
impl RefSwitcher {
pub(super) fn new(view: WeakEntity<RepoDetailView>, window: &mut Window, cx: &mut App) -> Self {
let branch_view = view.clone();
let branch_select = cx.new(|cx| {
ComboboxState::new(
Combobox::new("branch-select", "Branch", Vec::new())
.placeholder("Branch")
.selected_icon(icon(IconRole::GitBranch))
.on_change(move |value, window, cx| {
if let Some(name) = value
&& let Err(error) = branch_view.update(cx, |this, cx| {
this.switch_ref(super::RefKind::Branch, name, window, cx);
})
{
log::warn!("failed to switch branch: {error}");
}
}),
window,
cx,
)
});
let tag_view = view;
let tag_select = cx.new(|cx| {
ComboboxState::new(
Combobox::new("tag-select", "Tag", Vec::new())
.placeholder("Tag")
.on_change(move |value, window, cx| {
if let Some(name) = value
&& let Err(error) = tag_view.update(cx, |this, cx| {
this.switch_ref(super::RefKind::Tag, name, window, cx);
})
{
log::warn!("failed to switch tag: {error}");
}
}),
window,
cx,
)
});
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<SharedString>>,
previous: &Option<SharedString>,
window: &mut Window,
cx: &mut App,
) {
select.update(cx, |state, cx| {
state.set_selected(previous.clone(), window, cx)
});
}
}
-369
View File
@@ -1,369 +0,0 @@
use std::path::PathBuf;
use gpui::{
AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, PathPromptOptions,
SharedString, Styled as _, Window, div, px,
};
use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore};
use ui::button::Button;
use ui::common::{StyledExt as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::select::{Select, SelectOption};
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use crate::repo::dialogs::grasp_servers::{normalize_server, server_host};
/// A settings row with the label and description on the left and the control on the right.
pub fn setting_row(
cx: &App,
title: impl Into<SharedString>,
description: impl Into<SharedString>,
control: impl IntoElement,
) -> AnyElement {
h_flex()
.w_full()
.justify_between()
.gap_4()
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(div().text_sm().font_semibold().child(title.into()))
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
),
)
.child(div().w(px(200.)).flex_shrink_0().child(control))
.into_any_element()
}
/// A full-width settings block with title and subtitle in one header.
pub fn setting_block(
cx: &App,
title: impl Into<SharedString>,
description: impl Into<SharedString>,
control: impl IntoElement,
) -> AnyElement {
v_flex()
.w_full()
.gap_3()
.child(
v_flex()
.gap_1()
.child(div().text_sm().font_semibold().child(title.into()))
.child(
div()
.text_xs()
.text_color(cx.theme().colors.muted_foreground)
.child(description.into()),
),
)
.child(control)
.into_any_element()
}
pub fn appearance_select(cx: &App) -> Select<AppearanceMode> {
let current = SettingsStore::global(cx).read(cx).settings().appearance;
Select::new("settings-appearance")
.options(vec![
SelectOption::new(AppearanceMode::System, "System"),
SelectOption::new(AppearanceMode::Light, "Light"),
SelectOption::new(AppearanceMode::Dark, "Dark"),
])
.selected(Some(current))
.on_change(|value, _, cx| {
let Some(mode) = value else {
return;
};
SettingsStore::global(cx).update(cx, |store, cx| {
store.edit(|settings| settings.appearance = mode, cx);
});
crate::apply_appearance_mode(mode, cx);
})
}
pub fn event_fetching_select(cx: &App) -> Select<EventFetchingStrategy> {
let current = SettingsStore::global(cx).read(cx).settings().event_fetching;
Select::new("settings-event-fetching")
.options(vec![
SelectOption::new(EventFetchingStrategy::Curated, "Curated"),
SelectOption::new(EventFetchingStrategy::Uncensored, "Uncensored"),
])
.selected(Some(current))
.on_change(|value, _, cx| {
let Some(strategy) = value else {
return;
};
SettingsStore::global(cx).update(cx, |store, cx| {
store.edit(|settings| settings.event_fetching = strategy, cx);
});
})
}
pub fn grasp_servers_editor(input: &Entity<InputState>, cx: &App) -> AnyElement {
let store = SettingsStore::global(cx);
let servers = store
.read(cx)
.settings()
.grasp_servers
.default_servers
.clone();
v_flex()
.gap_2()
.children(servers.iter().enumerate().map(|(ix, server)| {
let server = server.clone();
h_flex()
.gap_1()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(display_server(&server)),
)
.child(
Button::new(format!("settings-remove-server:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click({
let store = store.clone();
move |_, _, cx| {
store.update(cx, |store, cx| {
store.edit(
|settings| {
// A row's index can desync after a prior
// removal; match by value.
if let Some(at) = settings
.grasp_servers
.default_servers
.iter()
.position(|known| known == &server)
{
settings.grasp_servers.default_servers.remove(at);
}
},
cx,
);
});
}
}),
)
.into_any_element()
}))
.child(
h_flex()
.gap_1()
.child(
div()
.flex_1()
.child(Input::new("settings-grasp-input", input.clone())),
)
.child(
Button::new("settings-add-server")
.icon(Icon::named(IconRole::Plus))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Add grasp server"))
.on_click({
let input = input.clone();
move |_, window, cx| {
add_server(&input, window, cx);
}
}),
),
)
.into_any_element()
}
fn display_server(server: &str) -> SharedString {
match normalize_server(server) {
Some((_, relay)) => server_host(&relay),
None => SharedString::from(server.to_owned()),
}
}
fn add_server(input: &Entity<InputState>, window: &mut Window, cx: &mut App) {
let settings = SettingsStore::global(cx);
let value = input.read(cx).value().trim().to_owned();
if value.is_empty() {
return;
}
let Some((normalized, _)) = normalize_server(&value) else {
return;
};
settings.update(cx, |store, cx| {
store.edit(
|settings| {
if !settings.grasp_servers.default_servers.contains(&normalized) {
settings
.grasp_servers
.default_servers
.push(normalized.clone());
}
},
cx,
);
});
input.update(cx, |input, cx| input.set_value("", window, cx));
}
pub fn scan_paths_editor(cx: &App) -> AnyElement {
let store = SettingsStore::global(cx);
let scan_paths = store.read(cx).settings().local_repos.scan_paths.clone();
v_flex()
.gap_2()
.children(scan_paths.iter().enumerate().map(|(ix, path)| {
let path = path.clone();
h_flex()
.gap_1()
.child(
h_flex()
.flex_1()
.h_8()
.px_2()
.bg(cx.theme().colors.muted)
.text_color(cx.theme().colors.muted_foreground)
.text_xs()
.rounded(cx.theme().radius.control)
.child(path.display().to_string()),
)
.child(
Button::new(format!("settings-remove-path:{ix}"))
.icon(Icon::named(IconRole::Close))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Remove"))
.on_click(move |_, _, cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| {
// A row's index can desync after a prior
// removal; match by value.
if let Some(at) = settings
.local_repos
.scan_paths
.iter()
.position(|known| known == &path)
{
settings.local_repos.scan_paths.remove(at);
}
},
cx,
);
});
}),
)
.into_any_element()
}))
.child(
h_flex().justify_end().child(
Button::new("settings-add-path")
.icon(Icon::named(IconRole::Plus))
.label("Add directory")
.on_click(|_, _, cx| add_scan_path(cx)),
),
)
.into_any_element()
}
fn add_scan_path(cx: &mut App) {
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: true,
prompt: Some("Choose directories".into()),
});
cx.spawn(async move |cx| {
if let Ok(Ok(Some(paths))) = prompt.await {
cx.update(|cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| {
for path in paths {
let path = path.to_string_lossy().to_string();
if !settings
.local_repos
.scan_paths
.iter()
.any(|existing| existing.to_string_lossy() == path)
{
settings.local_repos.scan_paths.push(PathBuf::from(path));
}
}
},
cx,
);
});
});
}
})
.detach();
}
pub fn default_folder_selector(default_folder: &Entity<InputState>) -> AnyElement {
let folder = default_folder.clone();
h_flex()
.gap_1()
.child(
div()
.flex_1()
.child(Input::new("settings-default-folder", folder.clone())),
)
.child(
Button::new("settings-choose-folder")
.icon(Icon::named(IconRole::Folder))
.variant(ui::button::ButtonVariant::Ghost)
.tooltip(Tooltip::text("Choose folder"))
.on_click(move |_, window, cx| {
choose_default_folder(&folder, window, cx);
}),
)
.into_any_element()
}
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();
let prompt = cx.prompt_for_paths(PathPromptOptions {
files: false,
directories: true,
multiple: false,
prompt: Some("Choose default folder".into()),
});
cx.spawn(async move |cx| {
if let Ok(Ok(Some(mut paths))) = prompt.await
&& let Some(path) = paths.pop()
{
let text = path.to_string_lossy().to_string();
if let Err(error) = cx.update_window(handle, |_, window, cx| {
let store = SettingsStore::global(cx);
store.update(cx, |store, cx| {
store.edit(
|settings| settings.create_repository.default_folder = Some(path.clone()),
cx,
);
});
default_folder.update(cx, |input, cx| input.set_value(text, window, cx));
}) {
log::warn!("failed to apply default folder: {error}");
}
}
})
.detach();
}
-105
View File
@@ -1,105 +0,0 @@
mod helpers;
use gpui::{
App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
Window, px,
};
use helpers::{
appearance_select, default_folder_selector, event_fetching_select, grasp_servers_editor,
scan_paths_editor, setting_block, setting_row,
};
use settings::SettingsStore;
use ui::common::v_flex;
use ui::dialog::{Dialog, DialogHandle};
use ui::input::InputState;
use ui::separator::Separator;
pub struct SettingsDialog {
handle: DialogHandle,
grasp_input: Entity<InputState>,
default_folder: Entity<InputState>,
}
impl SettingsDialog {
pub fn new(cx: &mut App) -> Entity<Self> {
let store = SettingsStore::global(cx);
let settings = store.read(cx).settings().clone();
let grasp_input = InputState::new(cx);
let folder = settings
.create_repository
.default_folder
.clone()
.unwrap_or_else(paths::desktop_dir);
let default_folder = InputState::builder()
.text(folder.to_string_lossy())
.read_only()
.build(cx);
cx.new(|_| Self {
handle: DialogHandle::new(true),
grasp_input,
default_folder,
})
}
}
impl Render for SettingsDialog {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
const APPEARANCE_DESC: &str =
"Choose whether the app follows the system theme or uses a light/dark theme.";
const FETCH_DESC: &str = "Curated fetches events from relays in the repository's announcement. Uncensored also fetches from every maintainer's relays.";
const GRASP_DESC: &str =
"Servers used to host your git repositories via the Grasp protocol";
const SCAN_DESC: &str = "Directories scanned for local git repositories.";
const FOLDER_DESC: &str = "The folder for newly created repositories.";
let grasp_input = self.grasp_input.clone();
let default_folder = self.default_folder.clone();
Dialog::new("settings-dialog")
.handle(self.handle.clone())
.width(px(600.))
.height(px(560.))
.title("Settings")
.content(move |_, cx| {
v_flex()
.gap_4()
.child(setting_row(
cx,
"Appearance",
APPEARANCE_DESC,
appearance_select(cx),
))
.child(Separator::horizontal())
.child(setting_row(
cx,
"Event Fetching Strategy",
FETCH_DESC,
event_fetching_select(cx),
))
.child(Separator::horizontal())
.child(setting_block(
cx,
"Grasp Servers",
GRASP_DESC,
grasp_servers_editor(&grasp_input, cx),
))
.child(Separator::horizontal())
.child(setting_block(
cx,
"Scan Directories",
SCAN_DESC,
scan_paths_editor(cx),
))
.child(setting_block(
cx,
"Default Folder",
FOLDER_DESC,
default_folder_selector(&default_folder),
))
.into_any_element()
})
}
}
-239
View File
@@ -1,239 +0,0 @@
//! The shared issue and pull-request lists: toolbar, uniform rows, scrollbar
//! overlay, and empty state, plus the scrollable commit list.
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement,
ParentElement as _, Pixels, SharedString, StatefulInteractiveElement as _, Styled as _,
UniformListScrollHandle, Window, div, px, uniform_list,
};
use nostr::prelude::PublicKey;
use signed_core::RepoStatus;
use signed_git::FileCommit;
use ui::avatar::Avatar;
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::theme::ActiveTheme as _;
use crate::repo::helpers::commit_row;
use crate::shared::widgets::{empty_state, scroll_overlay, status_badge};
/// The height of one issue or pull-request row.
pub const ROW_HEIGHT: f32 = 73.;
/// A row's activation handler.
pub type EventHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// The toolbar above the issue and pull-request lists: a filter and its actions.
pub fn filter_toolbar(cx: &App, children: impl IntoIterator<Item = AnyElement>) -> AnyElement {
h_flex()
.px_4()
.w_full()
.gap_3()
.border_b_1()
.border_color(cx.theme().colors.border)
.bg(cx.theme().colors.muted)
.children(children)
.into_any_element()
}
/// One issue or pull-request row's display data and click handler.
pub struct EventRow {
pub id: ElementId,
pub status: RepoStatus,
pub title: SharedString,
pub author: SharedString,
pub picture: Option<SharedString>,
pub pubkey: PublicKey,
pub short_id: SharedString,
pub age: SharedString,
pub on_click: EventHandler,
}
/// The shared issue and pull-request list: toolbar, uniform rows, scrollbar
/// overlay, and empty state.
pub struct EventList {
id: ElementId,
toolbar: Option<AnyElement>,
rows: Vec<EventRow>,
scroll_handle: UniformListScrollHandle,
empty_message: SharedString,
}
impl EventList {
/// Builds a list rendering `rows` under `toolbar`.
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
toolbar: None,
rows: Vec::new(),
scroll_handle: UniformListScrollHandle::new(),
empty_message: "Nothing here".into(),
}
}
/// Replaces the list's scroll handle with the caller's.
pub fn scroll_handle(mut self, handle: UniformListScrollHandle) -> Self {
self.scroll_handle = handle;
self
}
/// Sets the toolbar above the rows.
pub fn toolbar(mut self, toolbar: AnyElement) -> Self {
self.toolbar = Some(toolbar);
self
}
/// Sets the rendered rows.
pub fn rows(mut self, rows: Vec<EventRow>) -> Self {
self.rows = rows;
self
}
/// Sets the empty-state message shown when no rows match.
pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
self.empty_message = message.into();
self
}
/// Renders the list.
pub fn render(self, _cx: &App) -> AnyElement {
let count = self.rows.len();
let rows = self.rows;
let row_height = px(ROW_HEIGHT);
v_flex()
.relative()
.flex_1()
.min_h_0()
.w_full()
.children(self.toolbar)
.when(count > 0, |this| {
this.child(
uniform_list((self.id.clone(), "rows"), count, move |range, _, cx| {
range
.map(|ix| {
let Some(row) = rows.get(ix) else {
return div().into_any_element();
};
event_row(row, row_height, cx)
})
.collect()
})
.track_scroll(&self.scroll_handle)
.size_full(),
)
.child(scroll_overlay(
(self.id.clone(), "scroll"),
self.scroll_handle.clone(),
))
})
.when(count == 0, |this| {
this.child(empty_state(self.empty_message))
})
.into_any_element()
}
}
/// Renders one issue or pull-request row.
pub fn event_row(row: &EventRow, row_height: Pixels, cx: &App) -> AnyElement {
h_flex()
.id(row.id.clone())
.w_full()
.h(row_height)
.gap_4()
.px_4()
.border_b_1()
.border_color(cx.theme().colors.border)
.hover(|this| this.bg(cx.theme().colors.muted_hover))
.on_click({
let on_click = row.on_click.clone();
move |event, window, cx| on_click(event, window, cx)
})
.child(status_badge(row.status))
.child(
v_flex()
.flex_1()
.min_w_0()
.gap_1()
.child(
div()
.text_base()
.text_ellipsis()
.whitespace_nowrap()
.child(row.title.clone()),
)
.child(event_meta_row(row, cx)),
)
.into_any_element()
}
/// The author, age, and id line under a row's title.
pub fn event_meta_row(row: &EventRow, cx: &App) -> AnyElement {
h_flex()
.gap_2()
.text_xs()
.child(
h_flex()
.gap_1()
.child(
Avatar::new(row.pubkey)
.name(row.author.clone())
.picture(row.picture.clone())
.small(),
)
.child(div().child(row.author.clone())),
)
.child(SharedString::from("opened"))
.child(
div()
.text_color(cx.theme().colors.muted_foreground)
.child(row.short_id.clone()),
)
.child(row.age.clone())
.into_any_element()
}
/// A scrollable commit list: uniform `commit_row`s under a scrollbar overlay.
#[allow(clippy::too_many_arguments)]
pub fn commit_list(
id: &'static str,
scroll_id: &'static str,
commits: Arc<Vec<FileCommit>>,
scroll_handle: UniformListScrollHandle,
action: impl Fn(usize, &FileCommit, &App) -> Option<AnyElement> + 'static,
on_click: impl Fn(&FileCommit, &mut Window, &mut App) + Clone + 'static,
_cx: &App,
) -> AnyElement {
let count = commits.len();
v_flex()
.relative()
.flex_1()
.min_h_0()
.child(
uniform_list(id, count, move |range, _, cx| {
range
.map(|ix| {
let commit = commits[ix].clone();
let action = action(ix, &commit, cx);
let on_click = on_click.clone();
let row_commit = commit.clone();
commit_row(
ix,
&commit,
action,
move |window, cx| on_click(&row_commit, window, cx),
cx,
)
})
.collect()
})
.track_scroll(&scroll_handle)
.size_full(),
)
.child(scroll_overlay(scroll_id, scroll_handle))
.into_any_element()
}
-37
View File
@@ -1,37 +0,0 @@
use gpui::{App, Entity};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
pub mod event_list;
pub mod panels;
pub mod progress;
pub mod tree;
pub mod widgets;
/// Logs a discarded `Result` with its source location instead of dropping it silently.
#[track_caller]
pub fn log_dropped<T>(result: Result<T, anyhow::Error>) {
if let Err(error) = result {
let location = std::panic::Location::caller();
log::warn!(
"{}:{}: dropped result: {error}",
location.file(),
location.line()
);
}
}
/// Tracks a detail view's author, commenters, and repository owner for
/// profile prefetch.
pub fn track_event_participants(
author: Option<PublicKey>,
owner: Option<PublicKey>,
comments: impl Iterator<Item = PublicKey>,
directory: &Entity<ProfileDirectory>,
cx: &mut App,
) {
let mut keys: Vec<PublicKey> = author.into_iter().collect();
keys.extend(comments);
keys.extend(owner);
directory.update(cx, |directory, cx| directory.track(keys, cx));
}
-71
View File
@@ -1,71 +0,0 @@
use std::sync::Arc;
use gpui::{App, Entity, SharedString, WeakEntity, Window};
use ui::layout::panel::{Panel, PanelView};
use crate::workspace::Workspace;
/// Opens a repository in the main panel, reusing it when it is already cached.
pub fn open_primary<P, F>(
workspace: &WeakEntity<Workspace>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
if workspace
.read_with(cx, |workspace, _| workspace.has_main(&id))
.unwrap_or(false)
{
if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_main(&id, cx)) {
log::warn!("failed to activate repository {id}: {error}");
}
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |workspace, cx| {
workspace.show_main(id.clone(), view, cx)
}) {
log::warn!("failed to open repository {id}: {error}");
}
}
/// Opens a detail panel beside the main panel, reusing it when it is already cached.
pub fn open_detail<P, F>(
workspace: &WeakEntity<Workspace>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
if workspace
.read_with(cx, |workspace, _| workspace.has_detail(&id))
.unwrap_or(false)
{
if let Err(error) = workspace.update(cx, |workspace, cx| workspace.activate_detail(&id, cx))
{
log::warn!("failed to activate detail panel {id}: {error}");
}
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
if let Err(error) = workspace.update(cx, |workspace, cx| {
workspace.show_detail(id.clone(), view, cx)
}) {
log::warn!("failed to open detail panel {id}: {error}");
}
}
-166
View File
@@ -1,166 +0,0 @@
use gpui::{
AnyElement, App, AsyncApp, Context, Entity, IntoElement as _, ParentElement as _, SharedString,
Styled as _, Subscription, Task, div,
};
use signed_core::RepoAddr;
use signed_state::{Backend, BackendEvent, PushStepStatus};
use ui::common::{h_flex, v_flex};
use ui::dialog::DialogHandle;
use ui::icons::{Icon, IconRole};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
/// 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,
pub error: Option<SharedString>,
// The repository whose push checklist is shown; `None` outside a publish.
push_addr: Option<RepoAddr>,
pub push_steps: Vec<PushStepStatus>,
_push_subscription: Option<Subscription>,
}
impl DialogProgress {
/// Marks an action as started, disabling the form and clearing the previous error.
pub fn begin(&mut self) {
self.busy = true;
self.error = None;
}
/// Starts a publish for the repository at `addr` and listens for its push steps.
pub fn begin_push(&mut self, addr: RepoAddr, cx: &mut Context<Self>) {
self.begin();
self.push_addr = Some(addr);
self.push_steps.clear();
if self._push_subscription.is_none() {
let backend = Backend::global(cx);
self._push_subscription = Some(cx.subscribe(&backend, |this, _backend, event, cx| {
let BackendEvent::PushProgress { addr, status } = event else {
return;
};
if this.push_addr.as_ref() != Some(addr) {
return;
}
match this
.push_steps
.iter_mut()
.find(|step| step.step() == status.step())
{
Some(step) => *step = status.clone(),
None => this.push_steps.push(status.clone()),
}
cx.notify();
}));
}
}
/// 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());
}
}
/// The shared error line under a dialog form, `None` when there is no error.
pub fn error_row(error: &Option<SharedString>, cx: &App) -> Option<AnyElement> {
error.as_ref().map(|message| {
div()
.text_base()
.text_color(cx.theme().ramps.destructive.base)
.child(message.clone())
.into_any_element()
})
}
/// The push checklist of a running publish, `None` before any step is reported.
pub fn push_steps_row(steps: &[PushStepStatus], cx: &App) -> Option<AnyElement> {
if steps.is_empty() {
return None;
}
let rows = steps
.iter()
.map(|status| {
let label = SharedString::from(status.step().label());
match status {
PushStepStatus::Running(_) => h_flex()
.gap_2()
.text_base()
.text_color(cx.theme().colors.muted_foreground)
.child(Spinner::new("push-step"))
.child(label)
.into_any_element(),
PushStepStatus::Done(_) => h_flex()
.gap_2()
.text_base()
.text_color(cx.theme().colors.foreground)
.child(
Icon::named(IconRole::Check)
.small()
.color(cx.theme().colors.foreground),
)
.child(label)
.into_any_element(),
PushStepStatus::Failed(_, reason) => h_flex()
.gap_2()
.text_base()
.text_color(cx.theme().ramps.destructive.base)
.child(
Icon::named(IconRole::Close)
.small()
.color(cx.theme().ramps.destructive.base),
)
.child(SharedString::from(format!(
"{}: {reason}",
status.step().label()
)))
.into_any_element(),
}
})
.collect::<Vec<_>>();
Some(v_flex().gap_1().children(rows).into_any_element())
}
/// Runs a dialog task to completion.
pub fn run_dialog_task<T: 'static>(
task: Task<Result<T, anyhow::Error>>,
state: &Entity<DialogProgress>,
handle: &DialogHandle,
cx: &mut App,
) {
let state = state.clone();
let handle = handle.clone();
run_dialog_task_with(
task,
cx,
move |_, cx| cx.update(|cx| handle.close(cx)),
move |error, cx| {
state.update(cx, |state, cx| {
state.fail(error.to_string());
cx.notify();
});
},
);
}
/// Runs a dialog task to completion, with explicit success and failure sinks.
pub fn run_dialog_task_with<T: 'static>(
task: Task<Result<T, anyhow::Error>>,
cx: &mut App,
on_success: impl FnOnce(T, &mut AsyncApp) + 'static,
on_error: impl FnOnce(anyhow::Error, &mut AsyncApp) + 'static,
) {
cx.spawn(async move |cx| match task.await {
Ok(value) => on_success(value, cx),
Err(error) => on_error(error, cx),
})
.detach();
}
-188
View File
@@ -1,188 +0,0 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
pub struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
pub id: String,
pub label: String,
pub children: Vec<TreeItemSeed>,
}
/// One visible row of the flattened tree.
#[derive(Clone)]
pub struct TreeRow {
pub id: String,
pub label: String,
pub depth: usize,
pub expandable: bool,
pub expanded: bool,
}
/// Flattens the seeds into the rows a flat tree renders, honoring `expanded`.
pub fn flatten(seeds: &[TreeItemSeed], expanded: &HashSet<String>) -> Vec<TreeRow> {
fn push(
seed: &TreeItemSeed,
depth: usize,
expanded: &HashSet<String>,
rows: &mut Vec<TreeRow>,
) {
let is_expanded = expanded.contains(&seed.id);
rows.push(TreeRow {
id: seed.id.clone(),
label: seed.label.clone(),
depth,
expandable: !seed.children.is_empty(),
expanded: is_expanded,
});
if is_expanded {
for child in &seed.children {
push(child, depth + 1, expanded, rows);
}
}
}
let mut rows = Vec::new();
for seed in seeds {
push(seed, 0, expanded, &mut rows);
}
rows
}
/// Every folder id, for starting with the tree fully expanded.
pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet<String> {
fn push(seed: &TreeItemSeed, expanded: &mut HashSet<String>) {
if !seed.children.is_empty() {
expanded.insert(seed.id.clone());
for child in &seed.children {
push(child, expanded);
}
}
}
let mut expanded = HashSet::new();
for seed in seeds {
push(seed, &mut expanded);
}
expanded
}
/// Build nested tree items from a flat entry list sorted dirs-first.
pub 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.
pub 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::*;
fn ids(rows: &[TreeRow]) -> Vec<(&str, usize)> {
rows.iter()
.map(|row| (row.id.as_str(), row.depth))
.collect()
}
#[test]
fn collapsed_folders_hide_children() {
let seeds = build_tree_items(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("README.md"),
]);
let rows = flatten(&seeds, &HashSet::new());
assert_eq!(ids(&rows), vec![("src", 0), ("README.md", 0)]);
assert!(rows[0].expandable);
assert!(!rows[0].expanded);
}
#[test]
fn expanding_a_folder_shows_children_in_order() {
let seeds = build_tree_items(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("src/views/mod.rs"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]);
let rows = flatten(&seeds, &expanded);
assert_eq!(
ids(&rows),
vec![
("src", 0),
("src/lib.rs", 1),
("src/views", 1),
("src/views/mod.rs", 2),
("README.md", 0),
]
);
}
#[test]
fn indices_map_to_row_ids() {
let seeds = build_tree_items(&[
PathBuf::from("docs"),
PathBuf::from("docs/guide.md"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["docs".to_owned()]);
let rows = flatten(&seeds, &expanded);
assert_eq!(rows[0].id, "docs");
assert_eq!(rows[1].id, "docs/guide.md");
assert_eq!(rows[2].id, "README.md");
}
}
-100
View File
@@ -1,100 +0,0 @@
use gpui::{
AnyElement, App, ElementId, IntoElement, ParentElement as _, SharedString, Styled as _, div,
};
use signed_core::RepoStatus;
use ui::badge::{Badge, BadgeVariant};
use ui::clipboard::ClipboardButton;
use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex};
use ui::empty_state::EmptyState;
use ui::icons::{Icon, IconRole};
use ui::scrollbar::{Scrollbar, ScrollbarHandle};
use ui::spinner::Spinner;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
/// The status pill shown on issue and pull-request rows.
pub fn status_badge(status: RepoStatus) -> Badge {
let (label, variant, icon) = match status {
RepoStatus::Open => ("Open", BadgeVariant::Neutral, IconRole::GitIssueOngoing),
RepoStatus::Closed => ("Closed", BadgeVariant::Danger, IconRole::GitIssueClosed),
RepoStatus::Draft => ("Draft", BadgeVariant::Warning, IconRole::GitIssueOngoing),
RepoStatus::Applied => ("Applied", BadgeVariant::Success, IconRole::GitIssueDone),
};
Badge::new(format!("status-{label}"), label)
.variant(variant)
.icon(Icon::named(icon))
.tooltip(Tooltip::text(label))
}
/// A centered empty-state message filling the available space.
pub fn empty_state(message: impl Into<SharedString>) -> AnyElement {
let message = message.into();
v_flex()
.size_full()
.items_center()
.justify_center()
.child(EmptyState::new(message))
.into_any_element()
}
/// A centered spinner filling the available space.
pub fn centered_spinner(id: impl Into<ElementId>) -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Spinner::new(id))
.into_any_element()
}
/// The vertical scrollbar pinned over a uniform list's full extent.
pub fn scroll_overlay<I, H>(id: I, handle: H) -> AnyElement
where
I: Into<ElementId>,
H: ScrollbarHandle,
{
div()
.absolute()
.top_0()
.left_0()
.right_0()
.bottom_0()
.child(Scrollbar::vertical(id, handle))
.into_any_element()
}
/// One copyable clone command with its text visible next to the copy icon.
pub fn clone_row(id: SharedString, command: SharedString, cx: &App) -> AnyElement {
h_flex()
.h_8()
.px_2()
.gap_2()
.min_w_0()
.bg(cx.theme().colors.secondary)
.rounded(cx.theme().radius.control)
.text_color(cx.theme().colors.secondary_foreground)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.font_family(cx.theme().mono_font)
.text_xs()
.child(command.clone()),
)
.child(ClipboardButton::new(id, command).xsmall())
.into_any_element()
}
/// A one-line muted label used by section headers.
pub fn section_label(text: impl Into<SharedString>, cx: &App) -> AnyElement {
div()
.text_xs()
.font_medium()
.text_color(cx.theme().colors.muted_foreground)
.child(text.into())
.into_any_element()
}
-628
View File
@@ -1,628 +0,0 @@
use std::rc::Rc;
use std::sync::Arc;
use gpui::{
AnyElement, AnyView, App, AppContext as _, Context, Entity, IntoElement, KeyBinding,
KeyBindingContextPredicate, ParentElement as _, SharedString, Subscription, WeakEntity, Window,
};
use metadata::{Profile, ProfileDirectory};
use nostr::prelude::PublicKey;
use repository_switcher::RepositoryEntry;
pub(crate) use repository_switcher::RepositorySwitcher;
use signed_core::Announcement;
use signed_state::{Backend, BackendEvent, LocalReposStore, RepoListStore, ResolvedLocalRepo};
use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariant};
use ui::command_palette::{Command, CommandPalette, CommandPaletteState};
use ui::icons::{Icon, IconRole};
use ui::layout::panel::PanelView;
use ui::menu::{Menu, MenuItem};
use ui::tabs::{Tab, Tabs, TabsVariant};
use ui::tooltip::Tooltip;
use crate::explore::ExploreView;
use crate::identity::exit::ExitDialog;
use crate::repo::{RepoDetailView, actions, dialogs};
use crate::settings::SettingsDialog;
use crate::shared::{log_dropped, panels};
use crate::workspace::Workspace;
mod repository_switcher;
/// The key context the repository shortcuts bind against.
pub(crate) const REPOSITORY_KEY_CONTEXT: &str = "Signed";
const CREATE_KEYSTROKE: &str = "secondary-n";
const REPOSITORY_KEYSTROKES: [&str; 9] = [
"secondary-1",
"secondary-2",
"secondary-3",
"secondary-4",
"secondary-5",
"secondary-6",
"secondary-7",
"secondary-8",
"secondary-9",
];
/// Opens the repository at this index in the combined announced/local list.
#[derive(Clone, PartialEq, gpui::Action)]
#[action(namespace = signed, no_json)]
pub(crate) struct SwitchRepository {
pub index: usize,
}
/// Opens the create-repository dialog.
#[derive(Clone, PartialEq, gpui::Action)]
#[action(namespace = signed, no_json)]
pub(crate) struct CreateRepository;
pub(crate) fn bind_repository_shortcuts(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(REPOSITORY_KEY_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse repository key context: {error}");
return;
}
};
let bindings = REPOSITORY_KEYSTROKES
.into_iter()
.enumerate()
.map(|(index, keystroke)| {
KeyBinding::load(
keystroke,
Box::new(SwitchRepository { index }),
context.clone(),
false,
None,
cx,
)
})
.chain(std::iter::once(KeyBinding::load(
CREATE_KEYSTROKE,
Box::new(CreateRepository),
context.clone(),
false,
None,
cx,
)))
.collect::<Result<Vec<_>, _>>();
let bindings = match bindings {
Ok(bindings) => bindings,
Err(error) => {
log::error!("failed to parse repository shortcut keystrokes: {error}");
return;
}
};
cx.bind_keys(bindings);
}
pub struct TitlebarView {
weak: WeakEntity<Self>,
workspace: WeakEntity<Workspace>,
/// User's announced repositories.
announcements: Arc<Vec<Announcement>>,
/// Local repositories found by the scan that are not announced yet.
local_repos: Arc<Vec<ResolvedLocalRepo>>,
/// Profiles rendered by the repository switcher.
directory: Entity<ProfileDirectory>,
/// The command palette opened from the titlebar.
palette: Entity<CommandPaletteState>,
repository_switcher: Entity<RepositorySwitcher>,
settings: Option<Entity<SettingsDialog>>,
exit: Option<Entity<ExitDialog>>,
create: Option<Entity<dialogs::create::CreateRepoDialog>>,
user_menu_open: bool,
_subscriptions: Vec<Subscription>,
}
impl TitlebarView {
pub fn new(
workspace: WeakEntity<Workspace>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let backend = Backend::global(cx);
let repos = RepoListStore::global(cx);
let local = LocalReposStore::global(cx);
let weak = cx.entity().downgrade();
let palette = Self::new_palette(weak.clone(), window, cx);
let directory = ProfileDirectory::new(cx);
let entity = cx.entity();
let mut subscriptions = Vec::new();
let repository_switcher = cx.new(|cx| {
RepositorySwitcher::new(
directory.clone(),
{
let weak = weak.clone();
move |index, window, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.activate(index, window, cx);
}));
}
},
{
let weak = weak.clone();
move |window, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.create_repository(window, cx);
}));
}
},
|cx| {
let local_repos = LocalReposStore::global(cx);
local_repos.update(cx, |store, cx| {
store.rescan(cx);
});
},
cx,
)
});
subscriptions.push(cx.subscribe(&backend, |this, _backend, event, cx| {
let signer_changed = matches!(event, BackendEvent::SignerChanged);
let signer_required = matches!(event, BackendEvent::SignerRequired);
if this.refresh(cx) || signer_changed || signer_required {
cx.notify();
}
}));
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();
}
}));
cx.defer(move |cx| {
entity.update(cx, |this, cx| {
if this.refresh(cx) {
cx.notify();
}
});
});
Self {
weak: cx.entity().downgrade(),
workspace,
announcements: Arc::new(Vec::new()),
local_repos: Arc::new(Vec::new()),
directory,
palette,
repository_switcher,
settings: None,
exit: None,
create: None,
user_menu_open: false,
_subscriptions: subscriptions,
}
}
fn new_palette(
weak: WeakEntity<Self>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Entity<CommandPaletteState> {
cx.new(|cx| {
let matcher = |query: &str, commands: &[Command]| {
let needle = query.to_lowercase();
commands
.iter()
.filter(|command| command.label.to_lowercase().contains(&needle))
.cloned()
.collect()
};
CommandPaletteState::new(
CommandPalette::new("command-palette", Self::palette_commands(), matcher)
.on_execute(move |command, window, cx| match command.id.as_ref() {
"create-repo" => {
log_dropped(weak.update(cx, |this, cx| this.open_create(window, cx)));
}
"rescan-repos" => {
let local_repos = LocalReposStore::global(cx);
local_repos.update(cx, |store, cx| store.rescan(cx));
}
"open-settings" => {
log_dropped(weak.update(cx, |this, cx| this.open_settings(cx)));
}
"exit" => {
log_dropped(weak.update(cx, |this, cx| this.open_exit(cx)));
}
_ => {}
}),
window,
cx,
)
})
}
fn palette_commands() -> Vec<Command> {
vec![
Command::new("create-repo", "Create repository").icon(Icon::named(IconRole::Plus)),
Command::new("rescan-repos", "Rescan for local repositories")
.icon(Icon::named(IconRole::Refresh)),
Command::new("open-settings", "Settings").icon(Icon::named(IconRole::Settings)),
Command::new("exit", "Exit"),
]
}
pub fn palette(&self) -> Entity<CommandPaletteState> {
self.palette.clone()
}
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) = {
let repo_list = RepoListStore::global(cx).read(cx);
let announcements = user
.as_ref()
.map(|user| repo_list.announcements_of(user))
.unwrap_or_default();
let local = LocalReposStore::global(cx).read(cx);
let local_repos =
LocalReposStore::resolve(&local.repos, &repo_list.announcements, &announcements);
(announcements, local_repos)
};
let announcements_changed = *self.announcements != announcements;
let local_changed = *self.local_repos != local_repos;
self.announcements = Arc::new(announcements);
self.local_repos = Arc::new(local_repos);
let mut profiles: Vec<PublicKey> = user.into_iter().collect();
profiles.extend(
self.local_repos
.iter()
.filter_map(|entry| {
entry
.nip34
.as_ref()
.and_then(|binding| binding.owner)
.filter(|owner| !profiles.contains(owner))
})
.collect::<Vec<PublicKey>>(),
);
self.directory.update(cx, |directory, cx| {
directory.track(profiles, cx);
});
if announcements_changed || local_changed {
let entries = self.repository_entries();
self.repository_switcher.update(cx, |switcher, cx| {
switcher.set_entries(entries, cx);
});
}
announcements_changed || local_changed
}
fn repository_entries(&self) -> Vec<RepositoryEntry> {
let mut entries = Vec::with_capacity(self.announcements.len() + self.local_repos.len());
for (index, announcement) in self.announcements.iter().enumerate() {
let label = announcement
.name
.as_deref()
.map(SharedString::from)
.unwrap_or_else(|| SharedString::from(announcement.id.clone()));
entries.push(RepositoryEntry {
index,
key: announcement_key(announcement),
label,
owner: Some(announcement.owner),
});
}
for (local_index, entry) in self.local_repos.iter().enumerate() {
let owner = entry.nip34.as_ref().and_then(|binding| binding.owner);
entries.push(RepositoryEntry {
index: self.announcements.len() + local_index,
key: local_key(entry),
label: entry.name(),
owner,
});
}
entries
}
pub(crate) fn repository_switcher(&self) -> Entity<RepositorySwitcher> {
self.repository_switcher.clone()
}
/// Tabs for the repositories opened in the main panel.
pub fn render_repo_tabs(&self, workspace: &Workspace) -> Option<Tabs> {
let open = workspace.open_mains();
if open.is_empty() {
return None;
}
let tabs: Vec<_> = open
.iter()
.map(|id| (id.clone(), workspace.main_view(id)))
.collect();
let selected = workspace
.active_main_id()
.and_then(|id| open.iter().position(|open_id| open_id == id))
.unwrap_or(usize::MAX);
let change_workspace = self.workspace.clone();
let close_workspace = self.workspace.clone();
let open_for_change = open.to_vec();
Some(
Tabs::new("signed-repo-tabs")
.variant(TabsVariant::Titlebar)
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
tabs.iter()
.map(|(id, view)| match view {
Some(view) => view.tab(id.clone().into(), cx).closeable(true),
None => Tab::new(id.clone(), id.clone()).closeable(true),
})
.collect()
})
.on_change(move |index, _, cx| {
let Some(id) = open_for_change.get(index).cloned() else {
return;
};
log_dropped(change_workspace.update(cx, |workspace, cx| {
workspace.activate_main(&id, cx);
}));
})
.on_close(move |index, _, cx| {
log_dropped(close_workspace.update(cx, |workspace, cx| {
workspace.close_main_at(index, cx);
}));
}),
)
}
pub(crate) fn activate_shortcut(
&mut self,
index: usize,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.repository_switcher
.update(cx, |switcher, cx| switcher.close(cx));
self.activate(index, window, cx);
}
pub(crate) fn create_repository(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.repository_switcher
.update(cx, |switcher, cx| switcher.close(cx));
self.open_create(window, cx);
}
fn open_settings(&mut self, cx: &mut Context<Self>) {
self.settings = Some(SettingsDialog::new(cx));
cx.notify();
}
fn open_exit(&mut self, cx: &mut Context<Self>) {
self.exit = Some(ExitDialog::new(cx));
cx.notify();
}
fn open_create(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let view = dialogs::create::CreateRepoDialog::new(self.workspace.clone(), window, cx);
self.create = Some(view);
cx.notify();
}
/// The dialogs this titlebar opens, rendered at the window root.
pub fn dialogs(&self) -> Vec<AnyView> {
[
self.settings.clone().map(Into::into),
self.exit.clone().map(Into::into),
self.create.clone().map(Into::into),
]
.into_iter()
.flatten()
.collect()
}
fn activate(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
if let Some(announcement) = self.announcements.get(index) {
let addr = announcement.addr();
actions::open_repo_panel(&self.workspace, &addr, Some(announcement), window, cx);
return;
}
let Some(entry) = index
.checked_sub(self.announcements.len())
.and_then(|local| self.local_repos.get(local))
.cloned()
else {
return;
};
self.open_local_entry(entry, window, cx);
}
/// A local repository opens as the announced repository when its binding matches one.
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 {
let id = SharedString::from(format!("repo:{}", announcement.addr()));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
panels::open_primary(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
RepoDetailView::new_local_announced(
workspace_for_build.clone(),
announcement.clone(),
path.clone(),
window,
cx,
)
})
},
window,
cx,
);
return;
}
let id = SharedString::from(format!("repo-local:{}", path.display()));
let workspace = self.workspace.clone();
let workspace_for_build = workspace.clone();
panels::open_primary(
&workspace,
id,
move |window, cx| {
cx.new(|cx| {
RepoDetailView::new_local(
workspace_for_build.clone(),
path.clone(),
nip34.clone(),
window,
cx,
)
})
},
window,
cx,
);
}
pub fn render_user_menu(&self, cx: &App) -> Option<AnyElement> {
let profile = Backend::global(cx)
.read(cx)
.current_user()
.map(|public_key| self.directory.read(cx).profile(&public_key, cx))?;
Some(self.render_user(&profile, cx).into_any_element())
}
pub fn render_explore(&self) -> AnyElement {
let workspace = self.workspace.clone();
Button::new("open-explore")
.icon(IconRole::Grid)
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.tooltip(Tooltip::text("Explore repositories"))
.on_click(move |_, window, cx| {
ExploreView::open(&workspace, window, cx);
})
.into_any_element()
}
pub fn render_new_repository(&self) -> AnyElement {
let weak = self.weak.clone();
Button::new("add-repo")
.icon(IconRole::Plus)
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.tooltip(Tooltip::text("Create repository"))
.on_click(move |_, window, cx| {
log_dropped(weak.update(cx, |this, cx| this.open_create(window, cx)));
})
.into_any_element()
}
fn render_user(&self, profile: &Profile, _cx: &App) -> impl IntoElement {
let name = profile.name();
let picture = profile.picture();
let public_key = profile.public_key();
let weak = self.weak.clone();
Menu::new("user-menu")
.open(self.user_menu_open)
.on_change({
let weak = weak.clone();
move |open, _, cx| {
log_dropped(weak.update(cx, |this, cx| {
this.user_menu_open = open;
cx.notify();
}));
}
})
.trigger({
let name = name.clone();
let picture = picture.clone();
move |_, _| {
Button::new("user-menu-trigger")
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.padded(false)
.accessibility_label(name.clone())
.child(
Avatar::new(public_key)
.name(name.clone())
.picture(picture.clone())
.fully_rounded(true),
)
.into_any_element()
}
})
.items(move |_, _| {
vec![
MenuItem::new("Settings").handler({
let weak = weak.clone();
move |_, cx| {
log_dropped(weak.update(cx, |this, cx| this.open_settings(cx)));
}
}),
MenuItem::separator(),
MenuItem::new("Exit").destructive(true).handler({
let weak = weak.clone();
move |_, cx| {
log_dropped(weak.update(cx, |this, cx| this.open_exit(cx)));
}
}),
]
})
}
}
fn announcement_key(announcement: &Announcement) -> SharedString {
SharedString::from(format!("repo:{}", announcement.addr()))
}
fn local_key(entry: &ResolvedLocalRepo) -> SharedString {
match entry.announcement.as_ref() {
Some(announcement) => announcement_key(announcement),
None => SharedString::from(format!("repo-local:{}", entry.path.display())),
}
}
@@ -1,293 +0,0 @@
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Role,
SharedString, StatefulInteractiveElement as _, Styled as _, UniformListScrollHandle, Window,
div, px, rems, uniform_list,
};
use metadata::ProfileDirectory;
use nostr::prelude::PublicKey;
use ui::avatar::Avatar;
use ui::button::{Button, ButtonSide, ButtonVariant};
use ui::common::{Sizable as _, h_flex, v_flex};
use ui::icons::{Icon, IconRole};
use ui::input::{Input, InputState};
use ui::kbd::Kbd;
use ui::popover::Popover;
use ui::separator::Separator;
use ui::theme::ActiveTheme as _;
use ui::tooltip::Tooltip;
use super::{CreateRepository, REPOSITORY_KEY_CONTEXT, SwitchRepository};
use crate::shared::log_dropped;
type OpenHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type CreateHandler = Rc<dyn Fn(&mut Window, &mut App)>;
type RescanHandler = Rc<dyn Fn(&mut App)>;
/// One row of the repository switcher.
#[derive(Clone)]
pub(super) struct RepositoryEntry {
pub(super) index: usize,
pub(super) key: SharedString,
pub(super) label: SharedString,
pub(super) owner: Option<PublicKey>,
}
impl RepositoryEntry {
pub(super) fn avatar(&self, directory: &Entity<ProfileDirectory>, cx: &App) -> Avatar {
let mut avatar = Avatar::new(self.key.clone());
if let Some(owner) = self.owner {
let profile = directory.read(cx).profile(&owner, cx);
avatar = avatar.name(profile.name()).picture(profile.picture());
}
avatar.small()
}
}
/// The titlebar repository launcher: a static trigger and a searchable list.
pub(crate) struct RepositorySwitcher {
search: Entity<InputState>,
directory: Entity<ProfileDirectory>,
entries: Arc<Vec<RepositoryEntry>>,
open: bool,
on_open: OpenHandler,
on_create: CreateHandler,
on_rescan: RescanHandler,
scroll_handle: UniformListScrollHandle,
}
impl RepositorySwitcher {
pub(super) fn new(
directory: Entity<ProfileDirectory>,
on_open: impl Fn(usize, &mut Window, &mut App) + 'static,
on_create: impl Fn(&mut Window, &mut App) + 'static,
on_rescan: impl Fn(&mut App) + 'static,
cx: &mut Context<Self>,
) -> Self {
let search = InputState::new(cx);
Self {
search,
directory,
entries: Arc::new(Vec::new()),
open: false,
on_open: Rc::new(on_open),
on_create: Rc::new(on_create),
on_rescan: Rc::new(on_rescan),
scroll_handle: UniformListScrollHandle::new(),
}
}
pub(super) fn set_entries(&mut self, entries: Vec<RepositoryEntry>, cx: &mut Context<Self>) {
self.entries = Arc::new(entries);
cx.notify();
}
pub(super) fn close(&mut self, cx: &mut Context<Self>) {
if self.open {
self.open = false;
cx.notify();
}
}
}
impl Render for RepositorySwitcher {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = *cx.theme();
let weak = cx.entity().downgrade();
let entries = Arc::clone(&self.entries);
let search = self.search.clone();
let directory = self.directory.clone();
let on_open = self.on_open.clone();
let on_create = self.on_create.clone();
let on_rescan = self.on_rescan.clone();
let row_weak = weak.clone();
let create_weak = weak.clone();
let rescan_weak = weak.clone();
let content_search = search.clone();
let scroll_handle = self.scroll_handle.clone();
let change_search = search.clone();
let change_weak = weak.clone();
Popover::new("repo-switcher-popover")
.open(self.open)
.on_change(move |open, window, cx| {
let search = change_search.clone();
log_dropped(change_weak.update(cx, |this, cx| {
this.open = open;
if open {
search.update(cx, |state, cx| {
state.set_value_silent("", window, cx);
});
}
cx.notify();
}));
})
.trigger(move |_window: &mut Window, _cx: &mut App| {
Button::new("repo-switcher")
.icon(Icon::named(IconRole::Stack))
.variant(ButtonVariant::Ghost)
.fully_rounded(true)
.tooltip(Tooltip::text("Repositories"))
.accessibility_label("Repositories")
.into_any_element()
})
.content(move |window: &mut Window, cx: &mut App| {
let focus = content_search.read(cx).focus_handle();
let query = content_search.read(cx).value().to_lowercase();
window.defer(cx, move |window, cx| {
if !focus.is_focused(window) {
window.focus(&focus, cx);
}
});
let visible: Arc<Vec<RepositoryEntry>> = Arc::new(
entries
.iter()
.filter(|entry| {
query.is_empty() || entry.label.to_lowercase().contains(&query)
})
.cloned()
.collect(),
);
let row_height = rems(2.0).to_pixels(window.rem_size()) + px(2.);
let list_height = (row_height * visible.len() as f32).min(px(280.));
let list_entries = Arc::clone(&visible);
let list_directory = directory.clone();
let list_weak = row_weak.clone();
let list_on_open = on_open.clone();
let list_scroll_handle = scroll_handle.clone();
let create_hint = Kbd::binding_for_action(
&CreateRepository,
Some(REPOSITORY_KEY_CONTEXT),
window,
);
v_flex()
.w(px(380.))
.p_2()
.gap_2()
.child(
Input::new("repo-switcher-search", content_search.clone())
.placeholder("Filter repositories...")
.fully_rounded(true)
.prefix(
Icon::named(IconRole::Search)
.small()
.color(theme.colors.muted_foreground),
)
.bg(theme.colors.muted)
.border_color(theme.colors.muted),
)
.map(|this| {
if visible.is_empty() {
this.child(
div()
.p_3()
.text_color(theme.colors.muted_foreground)
.text_center()
.text_sm()
.child("No repositories found"),
)
} else {
this.child(
uniform_list(
"repo-switcher-list",
visible.len(),
move |range, window, cx| {
range
.filter_map(|row| {
let entry = list_entries.get(row)?;
let index = entry.index;
let shortcut = Kbd::binding_for_action(
&SwitchRepository { index },
Some(REPOSITORY_KEY_CONTEXT),
window,
);
let weak = list_weak.clone();
let on_open = list_on_open.clone();
Some(
h_flex()
.id(("repo-switcher-entry", index))
.role(Role::MenuItem)
.w_full()
.h(row_height)
.px_3()
.gap_2()
.rounded(theme.radius.full)
.text_sm()
.hover(|row| row.bg(theme.colors.muted))
.child(entry.avatar(&list_directory, cx))
.child(
div()
.flex_1()
.min_w_0()
.child(entry.label.clone()),
)
.when_some(shortcut, |row, shortcut| {
row.child(shortcut)
})
.cursor_pointer()
.on_click(move |_, window, cx| {
log_dropped(weak.update(
cx,
|this, cx| {
this.close(cx);
},
));
on_open(index, window, cx);
}),
)
})
.collect()
},
)
.track_scroll(&list_scroll_handle)
.h(list_height)
.w_full(),
)
}
})
.child(Separator::horizontal())
.child(
Button::new("repo-switcher-create")
.variant(ButtonVariant::Ghost)
.side(ButtonSide::Left)
.full_width(true)
.icon(Icon::named(IconRole::CirclePlus))
.child(div().flex_1().child("Create Repository"))
.when_some(create_hint, |button, hint| button.child(hint))
.on_click(move |_, window, cx| {
log_dropped(create_weak.update(cx, |this, cx| {
this.close(cx);
}));
on_create(window, cx);
}),
)
.child(
Button::new("repo-switcher-rescan")
.variant(ButtonVariant::Ghost)
.side(ButtonSide::Left)
.full_width(true)
.icon(Icon::named(IconRole::Refresh))
.label("Rescan Repositories")
.on_click(move |_, _, cx| {
log_dropped(rescan_weak.update(cx, |this, cx| {
this.close(cx);
}));
on_rescan(cx);
}),
)
.into_any_element()
})
}
}
-242
View File
@@ -1,242 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use gpui::{
App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use ui::common::v_flex;
use ui::layout::panel::{Panel, PanelView};
use ui::tabs::{Tab, Tabs, TabsVariant};
use crate::shared::log_dropped;
/// The repository shown in the main panel and the detail panels opened beside it.
#[derive(Default)]
pub struct Workspace {
main: Option<SharedString>,
main_order: Vec<SharedString>,
main_views: HashMap<SharedString, Arc<dyn PanelView>>,
details: Vec<SharedString>,
detail_views: HashMap<SharedString, Arc<dyn PanelView>>,
active_detail: Option<SharedString>,
}
impl Workspace {
pub fn new() -> Self {
Self::default()
}
pub fn active_main(&self) -> Option<Arc<dyn PanelView>> {
self.main
.as_ref()
.and_then(|id| self.main_views.get(id))
.cloned()
}
pub fn active_main_id(&self) -> Option<&SharedString> {
self.main.as_ref()
}
pub fn open_mains(&self) -> &[SharedString] {
&self.main_order
}
/// The open main panel with this id.
pub fn main_view(&self, id: &SharedString) -> Option<Arc<dyn PanelView>> {
self.main_views.get(id).cloned()
}
pub fn active_detail(&self) -> Option<Arc<dyn PanelView>> {
self.active_detail
.as_ref()
.and_then(|id| self.detail_views.get(id))
.cloned()
}
pub fn has_main(&self, id: &SharedString) -> bool {
self.main_views.contains_key(id)
}
pub fn has_details(&self) -> bool {
!self.details.is_empty()
}
pub fn has_detail(&self, id: &SharedString) -> bool {
self.detail_views.contains_key(id)
}
pub fn show_main(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) {
if self.main.as_ref() != Some(&id) {
self.clear_details();
}
if !self.main_views.contains_key(&id) {
self.main_order.push(id.clone());
}
self.main_views.insert(id.clone(), view);
self.main = Some(id);
cx.notify();
}
pub fn activate_main(&mut self, id: &SharedString, cx: &mut Context<Self>) {
if self.main.as_ref() != Some(id) {
self.clear_details();
}
self.main = Some(id.clone());
cx.notify();
}
pub fn activate_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
if self.detail_views.contains_key(id) {
self.active_detail = Some(id.clone());
cx.notify();
}
}
pub fn show_detail(
&mut self,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut Context<Self>,
) {
if !self.details.contains(&id) {
self.details.push(id.clone());
}
self.detail_views.insert(id.clone(), view);
self.active_detail = Some(id);
cx.notify();
}
pub fn close_detail(&mut self, id: &SharedString, cx: &mut Context<Self>) {
let Some(index) = self.details.iter().position(|open| open == id) else {
return;
};
self.close_detail_at(index, cx);
}
pub fn close_main_at(&mut self, index: usize, cx: &mut Context<Self>) {
if index >= self.main_order.len() {
return;
}
let id = self.main_order.remove(index);
self.main_views.remove(&id);
if self.main.as_ref() == Some(&id) {
self.main = self
.main_order
.get(index)
.or_else(|| {
index
.checked_sub(1)
.and_then(|prev| self.main_order.get(prev))
})
.cloned();
self.clear_details();
}
cx.notify();
}
pub fn clear(&mut self, cx: &mut Context<Self>) {
self.main = None;
self.main_order.clear();
self.main_views.clear();
self.clear_details();
cx.notify();
}
fn clear_details(&mut self) {
self.details.clear();
self.detail_views.clear();
self.active_detail = None;
}
fn close_detail_at(&mut self, index: usize, cx: &mut Context<Self>) {
if index >= self.details.len() {
return;
}
let id = self.details.remove(index);
self.detail_views.remove(&id);
if self.active_detail.as_ref() == Some(&id) {
self.active_detail = self
.details
.get(index)
.or_else(|| index.checked_sub(1).and_then(|prev| self.details.get(prev)))
.cloned();
}
cx.notify();
}
fn activate_detail_at(&mut self, index: usize, cx: &mut Context<Self>) {
let Some(id) = self.details.get(index) else {
return;
};
self.active_detail = Some(id.clone());
cx.notify();
}
}
impl Panel for Workspace {
fn title(&self, _cx: &App) -> SharedString {
SharedString::from("Workspace")
}
}
impl Render for Workspace {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let selected = self
.active_detail
.as_ref()
.and_then(|active| self.details.iter().position(|id| id == active))
.unwrap_or(usize::MAX);
let details: Vec<_> = self
.details
.iter()
.map(|id| (id.clone(), self.detail_views.get(id).cloned()))
.collect();
let weak = cx.entity().downgrade();
let close_weak = weak.clone();
let tabs = Tabs::new("signed-detail-tabs")
.variant(TabsVariant::Pill)
.overflow_scroll(true)
.selected(selected)
.tabs(move |_, cx| {
details
.iter()
.map(|(id, view)| match view {
Some(view) => view.tab(id.clone().into(), cx).closeable(true),
None => Tab::new(id.clone(), id.clone()).closeable(true),
})
.collect()
})
.on_change(move |index, _, cx| {
log_dropped(weak.update(cx, |workspace, cx| {
workspace.activate_detail_at(index, cx);
}));
})
.on_close(move |index, _, cx| {
log_dropped(close_weak.update(cx, |workspace, cx| {
workspace.close_detail_at(index, cx);
}));
});
let body = self.active_detail().map(|view| view.view());
v_flex()
.size_full()
.gap_2()
.child(tabs)
.child(div().flex_1().min_h_0().w_full().children(body))
}
}
-5
View File
@@ -6,8 +6,3 @@ publish.workspace = true
[dependencies]
nostr.workspace = true
serde.workspace = true
utils = { path = "../utils" }
[lints]
workspace = true
+22 -76
View File
@@ -2,97 +2,43 @@ use std::fmt;
use std::str::FromStr;
use nostr::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RepoAddr(Coordinate);
/// Address of a NIP-34 repository announcement: `30617:<owner-pubkey>:<repo-id>`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RepoAddr {
pub owner: PublicKey,
pub id: String,
}
impl RepoAddr {
pub fn new(owner: PublicKey, identifier: impl Into<String>) -> Self {
Self(Coordinate::new(Kind::GitRepoAnnouncement, owner).identifier(identifier))
pub fn new(owner: PublicKey, id: impl Into<String>) -> Self {
Self {
owner,
id: id.into(),
}
}
pub fn identifier_from_name(name: &str) -> String {
name.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '/' {
c
} else {
'-'
}
})
.collect()
}
pub fn kind(&self) -> Kind {
self.0.kind
}
pub fn public_key(&self) -> PublicKey {
self.0.public_key
}
pub fn identifier(&self) -> &str {
&self.0.identifier
}
pub fn coordinate(&self) -> &Coordinate {
&self.0
}
pub fn announcement_filter(&self) -> Filter {
Filter::new()
.kind(Kind::GitRepoAnnouncement)
.author(self.public_key())
.identifier(self.identifier())
}
pub fn state_filter(&self) -> Filter {
Filter::new()
.kind(Kind::RepoState)
.author(self.public_key())
.identifier(self.identifier())
}
pub fn activity_filter(&self) -> Filter {
Filter::new()
.kinds(crate::filters::ACTIVITY_KINDS)
.coordinate(&self.0)
}
pub fn deletion_filters(&self) -> Vec<Filter> {
vec![
Filter::new()
.kinds([Kind::EventDeletion, Kind::RequestToVanish])
.author(self.public_key()),
Filter::new().kind(Kind::EventDeletion).coordinate(&self.0),
]
/// The NIP-33 coordinate for the announcement event (`a` tag value).
pub fn coordinate(&self) -> Coordinate {
Coordinate::new(Kind::GitRepoAnnouncement, self.owner).identifier(self.id.clone())
}
}
impl fmt::Display for RepoAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
write!(f, "{}", self.coordinate())
}
}
impl FromStr for RepoAddr {
type Err = <Coordinate as FromStr>::Err;
type Err = nostr::error::Error;
/// Parse from `<kind>:<pubkey>:<d-tag>`, `naddr1...` bech32 or `nostr:naddr1...` URI.
fn from_str(s: &str) -> Result<Self, Self::Err> {
Coordinate::from_str(s).map(RepoAddr)
}
}
impl From<Coordinate> for RepoAddr {
fn from(coordinate: Coordinate) -> Self {
RepoAddr(coordinate)
}
}
impl From<RepoAddr> for Coordinate {
fn from(addr: RepoAddr) -> Self {
addr.0
let coordinate = Coordinate::parse(s)?;
Ok(Self {
owner: coordinate.public_key,
id: coordinate.identifier,
})
}
}
-492
View File
@@ -1,492 +0,0 @@
use std::collections::HashSet;
use nostr::prelude::*;
use crate::RepoAddr;
use crate::upstream::Upstream;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Announcement {
pub event_id: EventId,
pub id: String,
pub owner: PublicKey,
pub created_at: Timestamp,
pub name: Option<String>,
pub description: Option<String>,
pub web: Vec<Url>,
pub clone: Vec<Url>,
pub relays: Vec<RelayUrl>,
pub euc: Option<String>,
pub maintainers: Vec<PublicKey>,
pub upstream: Option<Upstream>,
pub hashtags: Vec<String>,
}
impl Announcement {
/// Lists forks of the base, the user's own first.
pub fn forks_in<'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()
}
/// Parses a kind 30617 event, rejecting other kinds and missing `d` tags.
pub fn from_event(event: &Event) -> Option<Self> {
if event.kind != Kind::GitRepoAnnouncement {
return None;
}
let id = event.tags.identifier()?;
let mut hashtags: Vec<String> = Vec::new();
hashtags.extend(event.tags.hashtags().map(|t| t.to_string()));
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();
let mut euc: Option<String> = None;
let mut maintainers: Vec<PublicKey> = Vec::new();
let mut upstream: Option<Upstream> = None;
for tag in event.tags.iter() {
match Nip34Tag::parse(tag.as_slice()) {
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),
Ok(Nip34Tag::EarliestUniqueCommitId(commit)) => euc = Some(commit.to_string()),
Ok(Nip34Tag::Maintainers(keys)) => maintainers.extend(keys),
_ => {}
}
if upstream.is_none() && tag.kind() == "u" {
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));
}
}
}
Some(Self {
event_id: event.id,
owner: event.pubkey,
created_at: event.created_at,
id,
name,
description,
web,
clone,
relays,
euc,
maintainers,
upstream,
hashtags,
})
}
/// Returns the owner and identifier as a repository address.
pub fn addr(&self) -> RepoAddr {
RepoAddr::new(self.owner, self.id.clone())
}
/// Returns the name, defaulting to "Untitled".
pub fn name(&self) -> String {
self.name.clone().unwrap_or("Untitled".into())
}
/// Matches a `u` tag pointing at the base or a shared earliest unique commit.
pub fn is_fork_of(&self, base: &RepoAddr, base_euc: Option<&str>) -> bool {
if self.addr() == *base {
return false;
}
if self.upstream.as_ref().and_then(|u| u.addr.as_ref()) == Some(base) {
return true;
}
base_euc.is_some_and(|euc| self.euc.as_deref() == Some(euc))
}
/// Returns the description, defaulting to "No description".
pub fn description(&self) -> String {
self.description
.clone()
.unwrap_or("No description".to_string())
}
/// Adds the owner to the maintainers unless a `u` tag marks this a subordinate fork.
pub fn effective_maintainers(&self) -> Vec<PublicKey> {
let mut maintainers = self.maintainers.clone();
if self.upstream.is_none() && !maintainers.contains(&self.owner) {
maintainers.push(self.owner);
}
maintainers
}
/// Returns deduplicated `git clone` commands for the advertised URLs.
pub fn clone_urls(&self) -> Vec<String> {
let mut seen = HashSet::new();
self.clone
.iter()
.map(|url| format!("git clone {url}"))
.filter(|command| seen.insert(command.clone()))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
const MAINTAINER_HEX: &str = "68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272";
/// Returns the test signer keys.
fn keys() -> Keys {
Keys::new(
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
.expect("valid secret key"),
)
}
/// Builds a signed repo announcement event from raw tags.
fn announcement_event(tags: &[&[&str]]) -> Event {
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")
}
/// Parses an event carrying every supported tag.
#[test]
fn parses_full_announcement() {
let event = announcement_event(&[
&["d", "my-repo"],
&["name", "My Repo"],
&["description", "A test repository"],
&["web", "https://example.com/repo"],
&["clone", "https://example.com/repo.git"],
&["relays", "wss://relay.example.com"],
&["r", "aa231c4c6a5777dc89b42207b499891a344add5c", "euc"],
&["maintainers", MAINTAINER_HEX],
&["t", "rust"],
&["t", "nostr"],
]);
let announcement = Announcement::from_event(&event).expect("parses");
assert_eq!(announcement.owner, keys().public_key());
assert_eq!(announcement.id, "my-repo");
assert_eq!(announcement.name.as_deref(), Some("My Repo"));
assert_eq!(
announcement.description.as_deref(),
Some("A test repository")
);
assert_eq!(
announcement.web,
vec![Url::parse("https://example.com/repo").unwrap()]
);
assert_eq!(
announcement.clone,
vec![Url::parse("https://example.com/repo.git").unwrap()]
);
assert_eq!(
announcement.relays,
vec![RelayUrl::parse("wss://relay.example.com").unwrap()]
);
assert_eq!(
announcement.euc.as_deref(),
Some("aa231c4c6a5777dc89b42207b499891a344add5c")
);
assert_eq!(
announcement.maintainers,
vec![PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")]
);
assert_eq!(announcement.hashtags, vec!["rust", "nostr"]);
}
/// Skips malformed clone, relay, and maintainer values.
#[test]
fn drops_malformed_values() {
let event = announcement_event(&[
&["d", "my-repo"],
&["clone", "not a url"],
&["relays", "wss://good.example.com"],
&["maintainers", "not-a-pubkey"],
]);
let announcement = Announcement::from_event(&event).expect("parses");
assert!(announcement.clone.is_empty());
assert_eq!(
announcement.relays,
vec![RelayUrl::parse("wss://good.example.com").unwrap()]
);
assert!(announcement.maintainers.is_empty());
}
/// Parses the `u` tag into an upstream coordinate.
#[test]
fn parses_upstream_tag() {
let event = announcement_event(&[
&["d", "my-fork"],
&[
"u",
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git",
"wss://relay.example.com",
],
]);
let announcement = Announcement::from_event(&event).expect("parses");
let upstream = announcement.upstream.expect("parses the u tag");
assert_eq!(
upstream.addr,
Some(RepoAddr::new(
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
"upstream"
))
);
assert_eq!(
upstream.raw,
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git"
);
assert_eq!(
upstream.display().to_string(),
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream"
);
}
/// Matches a fork through its `u` tag coordinate.
#[test]
fn is_fork_of_matches_the_u_tag_coordinate() {
let base = RepoAddr::new(
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
"upstream",
);
let event = announcement_event(&[&["d", "my-fork"], &["u", &base.to_string()]]);
let fork = Announcement::from_event(&event).expect("parses");
assert!(fork.is_fork_of(&base, None));
}
/// Matches forks sharing the base's earliest unique commit.
#[test]
fn is_fork_of_matches_a_shared_euc() {
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
let base_event = announcement_event(&[&["d", "upstream"], &["r", euc, "euc"]]);
let base = Announcement::from_event(&base_event).expect("parses");
let base_addr = base.addr();
let fork_event = announcement_event(&[&["d", "mirror"], &["r", euc, "euc"]]);
let fork = Announcement::from_event(&fork_event).expect("parses");
assert!(fork.is_fork_of(&base_addr, base.euc.as_deref()));
let other_event = announcement_event(&[
&["d", "other"],
&["r", "bb231c4c6a5777dc89b42207b499891a344add5c", "euc"],
]);
let other = Announcement::from_event(&other_event).expect("parses");
assert!(!other.is_fork_of(&base_addr, base.euc.as_deref()));
assert!(!fork.is_fork_of(&base_addr, None));
}
/// Matches permanent forks whose `u` tag points at the base despite a diverged EUC.
#[test]
fn is_fork_of_matches_permanent_forks_with_a_diverged_euc() {
let base = RepoAddr::new(
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
"upstream",
);
let base_euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
let event = announcement_event(&[
&["d", "my-fork"],
&["u", &base.to_string()],
&["r", "cc231c4c6a5777dc89b42207b499891a344add5c", "euc"],
]);
let fork = Announcement::from_event(&event).expect("parses");
assert!(fork.is_fork_of(&base, Some(base_euc)));
}
/// Includes the owner among maintainers for primary repositories.
#[test]
fn effective_maintainers_include_owner_for_primary_repos() {
let event = announcement_event(&[&["d", "my-repo"], &["maintainers", MAINTAINER_HEX]]);
let announcement = Announcement::from_event(&event).expect("parses");
let maintainers = announcement.effective_maintainers();
assert_eq!(maintainers.len(), 2);
assert!(maintainers.contains(&announcement.owner));
assert!(maintainers.contains(&PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")));
}
/// Excludes the owner from maintainers for subordinate forks.
#[test]
fn effective_maintainers_exclude_owner_for_subordinate_forks() {
let event = announcement_event(&[
&["d", "my-fork"],
&["u", "30617:abc:upstream|https://example.com/upstream.git"],
&["maintainers", MAINTAINER_HEX],
]);
let announcement = Announcement::from_event(&event).expect("parses");
let maintainers = announcement.effective_maintainers();
assert!(!maintainers.contains(&announcement.owner));
assert_eq!(
maintainers,
vec![PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey")]
);
}
const OWNER_KEYS: [&str; 3] = [
"0000000000000000000000000000000000000000000000000000000000000001",
"0000000000000000000000000000000000000000000000000000000000000002",
"0000000000000000000000000000000000000000000000000000000000000003",
];
/// Builds an announcement event signed by the given owner key.
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")
}
/// Builds one announcement owned by the owner key at the given index.
fn owned_announcements(owner_ix: usize, tags: &[&[&str]]) -> Vec<Announcement> {
vec![
Announcement::from_event(&owned_announcement_event(OWNER_KEYS[owner_ix], tags))
.expect("parses"),
]
}
/// Places the user's own forks before everyone else's.
#[test]
fn fork_candidates_orders_own_forks_first() {
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
let clone = "https://grasp.example/npub1x/my-fork.git";
let base_addr = RepoAddr::new(
PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey"),
"upstream",
);
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 = Announcement::forks_in(&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"]);
}
/// Excludes the base itself, unrelated repos, and repos without clone URLs.
#[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 = RepoAddr::new(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 = Announcement::forks_in(&all, &base_addr, Some(euc), Some(base_owner));
assert_eq!(forks.len(), 1);
assert_eq!(forks[0].id, "mirror");
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 = Announcement::forks_in(&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"]);
}
}
+29
View File
@@ -0,0 +1,29 @@
use nostr::prelude::*;
/// Build a NIP-34 user grasp list (kind `10317`).
pub fn grasp_list(grasp_servers: Vec<RelayUrl>) -> EventBuilder {
GitUserGraspList { grasp_servers }.into_event_builder()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grasp_list_tags() {
let servers = vec![
RelayUrl::parse("wss://gitnostr.com").unwrap(),
RelayUrl::parse("wss://relay.ngit.dev").unwrap(),
];
let builder = grasp_list(servers);
let urls: Vec<&str> = builder
.tags
.iter()
.filter_map(|t| t.content())
.collect();
assert_eq!(urls, vec!["wss://gitnostr.com", "wss://relay.ngit.dev"]);
}
}
+119
View File
@@ -0,0 +1,119 @@
use nostr::prelude::*;
use crate::RepoAddr;
/// Target of a `nostr://` clone URL (NIP-34 "Nostr Clone URL format").
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CloneTarget {
/// `nostr://<naddr1...>` — 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(RepoAddr::new(
coordinate.coordinate.public_key,
coordinate.coordinate.identifier,
)));
}
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(),
}
);
}
}
-67
View File
@@ -1,67 +0,0 @@
use std::collections::HashSet;
use nostr::prelude::*;
pub struct Deletions {
ids: HashSet<(EventId, PublicKey)>,
coords: Vec<(Coordinate, PublicKey, Timestamp)>,
vanished: Vec<(PublicKey, Timestamp)>,
}
impl Deletions {
/// Builds a [`Deletions`] instance from a collection of events.
pub fn from_events<E>(events: E) -> Self
where
E: IntoIterator<Item = Event>,
{
let mut ids = HashSet::new();
let mut coords = Vec::new();
let mut vanished = Vec::new();
for event in events {
if event.kind == Kind::EventDeletion {
ids.extend(event.tags.event_ids().map(|id| (id, event.pubkey)));
coords.extend(
event
.tags
.coordinates()
.map(|c| (c, event.pubkey, event.created_at)),
);
} else if event.kind == Kind::RequestToVanish {
vanished.push((event.pubkey, event.created_at));
}
}
Self {
ids,
coords,
vanished,
}
}
/// Returns whether the given event is deleted.
pub fn is_deleted(&self, event: &Event) -> bool {
if self
.vanished
.iter()
.any(|(pk, cutoff)| *pk == event.pubkey && event.created_at <= *cutoff)
{
return true;
}
if self.ids.contains(&(event.id, event.pubkey)) {
return true;
}
if event.kind.is_addressable()
&& let Some(identifier) = event.tags.identifier()
{
let coordinate = Coordinate::new(event.kind, event.pubkey).identifier(identifier);
return self.coords.iter().any(|(c, pk, cutoff)| {
*c == coordinate && *pk == event.pubkey && event.created_at <= *cutoff
});
}
false
}
}
+38 -189
View File
@@ -1,9 +1,10 @@
use std::time::Duration;
use nostr::filter::{Alphabet, SingleLetterTag};
use nostr::prelude::*;
pub const ACTIVITY_KINDS: [Kind; 9] = [
Kind::Comment,
use crate::RepoAddr;
/// Kinds that make up the activity of a repository.
pub const ACTIVITY_KINDS: [Kind; 8] = [
Kind::GitPatch,
Kind::GitPullRequest,
Kind::GitPullRequestUpdate,
@@ -14,47 +15,34 @@ pub const ACTIVITY_KINDS: [Kind; 9] = [
Kind::GitStatusDraft,
];
const NOTIFICATION_KINDS: [Kind; 8] = [
Kind::GitIssue,
Kind::GitPullRequest,
Kind::GitPatch,
Kind::GitPullRequestUpdate,
Kind::GitStatusOpen,
Kind::GitStatusApplied,
Kind::GitStatusClosed,
Kind::GitStatusDraft,
];
const GIT_ROOT_KINDS: [Kind; 4] = [
Kind::GitIssue,
Kind::GitPatch,
Kind::GitPullRequest,
Kind::GitRepoAnnouncement,
];
pub fn is_repo_kind(kind: Kind) -> bool {
kind == Kind::GitRepoAnnouncement
|| kind == Kind::RepoState
|| kind == Kind::EventDeletion
|| kind == Kind::RequestToVanish
|| ACTIVITY_KINDS.contains(&kind)
/// Latest announcement event for a repository.
pub fn announcement(addr: &RepoAddr) -> Filter {
Filter::new()
.kind(Kind::GitRepoAnnouncement)
.author(addr.owner)
.identifier(addr.id.clone())
}
fn tag_kind(event: &Event, name: &str) -> Option<Kind> {
event
.tags
.iter()
.find(|tag| tag.kind() == name)
.and_then(|tag| tag.content())
.and_then(|value| value.parse::<Kind>().ok())
/// Latest state event (refs / HEAD) for a repository.
pub fn state(addr: &RepoAddr) -> Filter {
Filter::new()
.kind(Kind::RepoState)
.author(addr.owner)
.identifier(addr.id.clone())
}
pub struct Filters;
/// All NIP-34 activity addressed to a repository (`#a` tag).
///
/// Note: the `a` tag on status events is optional per NIP-34, so statuses
/// published without it won't be matched here.
pub fn activity(addr: &RepoAddr) -> Filter {
Filter::new()
.kinds(ACTIVITY_KINDS)
.custom_tag(SingleLetterTag::lowercase(Alphabet::A), addr.to_string())
}
impl Filters {
const DELETIONS_LOOKBACK: Duration = Duration::from_secs(3 * 365 * 86_400);
pub fn statuses_for(roots: impl IntoIterator<Item = EventId>) -> Filter {
/// Status events (`1630..=1633`) referencing a specific root event (`#e` tag).
pub fn statuses_for(root: EventId) -> Filter {
Filter::new()
.kinds([
Kind::GitStatusOpen,
@@ -62,167 +50,28 @@ impl Filters {
Kind::GitStatusClosed,
Kind::GitStatusDraft,
])
.events(roots)
.event(root)
}
/// A user's grasp list (kind `10317`).
pub fn grasp_list(public_key: PublicKey) -> Filter {
Filter::new()
.kind(Kind::GitUserGraspList)
.author(public_key)
}
/// NIP-51: code (people who produce NIP-34 events) follow list
pub fn git_authors(public_key: PublicKey) -> Filter {
Filter::new().kind(Kind::Custom(10017)).author(public_key)
}
/// NIP-51: NIP-34 followed repositories
pub fn git_repos(public_key: PublicKey) -> Filter {
Filter::new().kind(Kind::Custom(10018)).author(public_key)
}
/// Replaceable events, so the latest of each kind is all we need.
pub fn user_metadata(public_key: PublicKey) -> Vec<Filter> {
vec![
Self::grasp_list(public_key).limit(1),
Self::git_authors(public_key).limit(1),
Self::git_repos(public_key).limit(1),
/// All repositories announced by an author.
pub fn announcements_by(public_key: PublicKey) -> Filter {
Filter::new()
.kind(Kind::ContactList)
.kind(Kind::GitRepoAnnouncement)
.author(public_key)
.limit(1),
Filter::new()
.kind(Kind::Metadata)
.author(public_key)
.limit(1),
Filter::new()
.kind(Kind::MuteList)
.author(public_key)
.limit(1),
Filter::new()
.kind(Kind::BlossomServerList)
.author(public_key)
.limit(1),
]
}
pub fn comments_for(roots: impl IntoIterator<Item = EventId>) -> Vec<Filter> {
let roots: Vec<String> = roots.into_iter().map(|id| id.to_hex()).collect();
if roots.is_empty() {
return Vec::new();
}
vec![
Filter::new()
.kind(Kind::Comment)
.custom_tags(SingleLetterTag::UPPERCASE_E, roots.clone()),
Filter::new()
.kind(Kind::Comment)
.custom_tags(SingleLetterTag::LOWERCASE_E, roots),
]
}
fn notification_comments(me: PublicKey) -> Filter {
Filter::new()
.kind(Kind::Comment)
.custom_tags(SingleLetterTag::UPPERCASE_P, [me.to_hex()])
.custom_tags(SingleLetterTag::UPPERCASE_K, ["1621", "1617", "1618"])
}
pub fn notifications(me: PublicKey) -> Vec<Filter> {
vec![
Self::notification_comments(me),
Filter::new().kinds(NOTIFICATION_KINDS).pubkey(me),
]
}
pub fn authored_activity(me: PublicKey) -> Filter {
Filter::new().kinds(ACTIVITY_KINDS).author(me)
}
/// All repository announcements (for global discovery).
///
/// Unbounded: intended for negentropy sync, which reconciles sets
/// efficiently regardless of size. Local database queries with this
/// filter are served by LMDB, so they stay fast as the database grows.
pub fn all_announcements() -> Filter {
Filter::new().kind(Kind::GitRepoAnnouncement)
}
pub fn all_states() -> Filter {
Filter::new().kind(Kind::RepoState)
}
fn deletions_since() -> Timestamp {
let now = Timestamp::now().as_secs();
Timestamp::from_secs(now - now % 86_400) - Self::DELETIONS_LOOKBACK
}
pub fn deletions() -> Filter {
Filter::new()
.kinds([Kind::EventDeletion, Kind::RequestToVanish])
.since(Self::deletions_since())
}
}
pub(crate) fn is_git_comment(event: &Event) -> bool {
event.kind == Kind::Comment
&& tag_kind(event, "K").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
}
pub(crate) fn is_git_status(event: &Event) -> bool {
tag_kind(event, "k").is_some_and(|kind| GIT_ROOT_KINDS.contains(&kind))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GitEvent;
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!(on_git.is_git_activity());
assert!(on_repo.is_git_activity());
assert!(!on_note.is_git_activity());
assert!(!signed(&keys(1), Kind::Comment, Vec::new()).is_git_activity());
}
#[test]
fn status_activity_depends_on_the_lowercase_k_tag() {
let status = signed(
&keys(1),
Kind::GitStatusClosed,
vec![kind_tag("k", Kind::GitPullRequest)],
);
let unrelated = signed(
&keys(1),
Kind::GitStatusClosed,
vec![kind_tag("k", Kind::Metadata)],
);
assert!(status.is_git_activity());
assert!(!unrelated.is_git_activity());
assert!(!signed(&keys(1), Kind::GitStatusClosed, Vec::new()).is_git_activity());
}
}
-145
View File
@@ -1,145 +0,0 @@
use nostr::prelude::*;
pub trait GitEvent {
/// Returns the NIP-34 subject or the first non-empty content line.
fn activity_subject(&self) -> String;
/// Returns the current commit id.
fn current_commit(&self) -> Option<String>;
/// Returns the merge base commit id.
fn merge_base(&self) -> Option<String>;
/// Returns the advertised clone URLs.
fn clone_urls(&self) -> Option<Vec<Url>>;
/// Returns the branch name.
fn branch_name(&self) -> Option<String>;
/// Returns whether the event is git activity.
fn is_git_activity(&self) -> bool;
/// Returns whether an `e` or `E` tag points at the root event.
fn references_root(&self, root: &EventId) -> bool;
}
impl GitEvent for Event {
/// Reads the subject tag, then the first content line, then "Untitled".
fn activity_subject(&self) -> String {
let subject = self
.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Subject(subject)) => Some(subject),
_ => None,
});
subject
.or_else(|| {
self.content
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.map(|value| value.to_string())
})
.unwrap_or("Untitled".to_string())
}
/// Reads the `commit` tag.
fn current_commit(&self) -> Option<String> {
self.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::CurrentCommit(commit)) => Some(commit.to_string()),
_ => None,
})
}
/// Reads the `merge-base` tag.
fn merge_base(&self) -> Option<String> {
self.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::MergeBase(commit)) => Some(commit.to_string()),
_ => None,
})
}
/// Reads the `clone` tag.
fn clone_urls(&self) -> Option<Vec<Url>> {
self.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Clone(urls)) => Some(urls),
_ => None,
})
}
/// Reads the `branch-name` tag.
fn branch_name(&self) -> Option<String> {
self.tags
.iter()
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::BranchName(name)) => Some(name),
_ => None,
})
}
/// Classifies git issue, patch, pull request, comment, and status kinds.
fn is_git_activity(&self) -> bool {
match self.kind {
Kind::GitIssue | Kind::GitPatch | Kind::GitPullRequest => true,
Kind::Comment => crate::filters::is_git_comment(self),
Kind::GitStatusOpen
| Kind::GitStatusApplied
| Kind::GitStatusClosed
| Kind::GitStatusDraft => crate::filters::is_git_status(self),
_ => false,
}
}
/// Compares `e` and `E` tag contents against the root id.
fn references_root(&self, root: &EventId) -> bool {
let root = root.to_hex();
self.tags
.iter()
.any(|tag| matches!(tag.kind(), "e" | "E") && tag.content() == Some(root.as_str()))
}
}
impl<T: GitEvent + ?Sized> GitEvent for &T {
/// Delegates to the referenced event.
fn activity_subject(&self) -> String {
(*self).activity_subject()
}
/// Delegates to the referenced event.
fn current_commit(&self) -> Option<String> {
(*self).current_commit()
}
/// Delegates to the referenced event.
fn merge_base(&self) -> Option<String> {
(*self).merge_base()
}
/// Delegates to the referenced event.
fn clone_urls(&self) -> Option<Vec<Url>> {
(*self).clone_urls()
}
/// Delegates to the referenced event.
fn branch_name(&self) -> Option<String> {
(*self).branch_name()
}
/// Delegates to the referenced event.
fn is_git_activity(&self) -> bool {
(*self).is_git_activity()
}
/// Delegates to the referenced event.
fn references_root(&self, root: &EventId) -> bool {
(*self).references_root(root)
}
}
-172
View File
@@ -1,172 +0,0 @@
use std::collections::HashMap;
use nostr::prelude::*;
use utils::sort_newest_first;
use super::{InboxItem, InboxReadState, ThreadResolver};
use crate::RepoAddr;
/// Groups events into inbox threads, merging the user's own events.
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 resolver = ThreadResolver::new(lookup);
let mut groups: HashMap<EventId, Vec<Event>> = HashMap::new();
for event in events {
if event.pubkey == me {
continue;
}
let Some(root) = resolver.notification_root(&event) 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 = resolver.notification_root(&event).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())
.map(RepoAddr::from),
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
}
#[cfg(test)]
mod tests {
use super::*;
/// Derives deterministic signer keys from a seed byte.
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"))
}
/// Builds a signed event with a fixed timestamp.
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")
}
/// Builds an uppercase `E` tag for the event.
fn uppercase_e_tag(event: &Event) -> Tag {
Tag::parse(["E", &event.id.to_hex()]).expect("valid E tag")
}
/// Builds an event lookup closure over a slice.
fn lookup(events: &[Event]) -> impl Fn(EventId) -> Option<Event> + '_ {
move |id| events.iter().find(|event| event.id == id).cloned()
}
/// Builds a git issue event with a subject tag.
fn titled_issue(author: &Keys, title: &str, at: u64) -> Event {
signed(
author,
Kind::GitIssue,
vec![Tag::parse(["subject", title]).expect("valid subject tag")],
at,
)
}
/// Merges the user's own events into the matching thread.
#[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()]);
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]
);
}
}
-99
View File
@@ -1,99 +0,0 @@
use std::collections::HashSet;
use nostr::prelude::*;
use super::InboxReadState;
use crate::{GitEvent, RepoAddr};
#[derive(Debug, Clone)]
pub struct InboxItem {
pub root: EventId,
pub root_event: Option<Event>,
pub address: Option<RepoAddr>,
pub events: Vec<Event>,
pub own_events: Vec<Event>,
pub unread_ids: Vec<EventId>,
pub archived: bool,
}
impl InboxItem {
/// Returns the thread title from the root, own events, or events.
pub fn title(&self) -> String {
self.root_event
.as_ref()
.or_else(|| self.own_events.first())
.or_else(|| self.events.first())
.map(|event| event.activity_subject())
.unwrap_or_else(|| "Untitled".to_string())
}
/// Returns the kind of the thread's primary event.
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)
}
/// Returns the newest timestamp among the root, own, and other events.
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()
}
/// Builds a chronological timeline capped at `limit` events, root 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
}
/// Returns whether the thread has unread events and is not archived.
pub fn is_unread(&self) -> bool {
!self.archived && !self.unread_ids.is_empty()
}
/// Recomputes unread ids and the archived flag from the read state.
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();
self.archived =
!self.events.is_empty() && self.events.iter().all(|event| state.is_archived(event));
}
}
-9
View File
@@ -1,9 +0,0 @@
mod group;
mod item;
mod read_state;
mod resolver;
pub use group::group;
pub use item::InboxItem;
pub use read_state::InboxReadState;
pub use resolver::ThreadResolver;
-109
View File
@@ -1,109 +0,0 @@
use std::collections::{HashMap, HashSet};
use std::time::Duration;
use nostr::prelude::*;
use serde::{Deserialize, Serialize};
const ADVANCE_WINDOW: Duration = Duration::from_secs(3 * 24 * 60 * 60);
const MARK_ALL_WINDOW: Duration = Duration::from_secs(10 * 24 * 60 * 60);
#[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 {
/// Returns whether the event falls under the read high-water mark or id set.
pub fn is_read(&self, event: &Event) -> bool {
event.created_at <= self.read_before || self.read_ids.contains(&event.id)
}
/// Returns whether the event falls under the archived high-water mark or id set.
pub fn is_archived(&self, event: &Event) -> bool {
event.created_at <= self.archived_before || self.archived_ids.contains(&event.id)
}
/// Records the event as read when it is past the current cutoff.
pub fn mark_read(&mut self, event: &Event) {
if event.created_at > self.read_before {
self.read_ids.insert(event.id);
}
}
/// Records the event as archived when it is past the current cutoff.
pub fn mark_archived(&mut self, event: &Event) {
if event.created_at > self.archived_before {
self.archived_ids.insert(event.id);
}
}
/// Marks all events from other authors within the window as read.
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();
}
/// Advances the read cutoff as far as possible, then prunes 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);
}
/// Advances the archived cutoff as far as possible, then prunes the id set.
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);
}
}
/// Computes the newest cutoff that leaves unmarked events uncovered.
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)
}
/// Drops ids whose events predate 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));
}
-249
View File
@@ -1,249 +0,0 @@
use std::collections::HashSet;
use nostr::prelude::*;
pub struct ThreadResolver<'a, L: ?Sized> {
lookup: &'a L,
}
impl<'a, L> ThreadResolver<'a, L>
where
L: Fn(EventId) -> Option<Event> + ?Sized,
{
/// Creates a resolver over the given event lookup.
pub fn new(lookup: &'a L) -> Self {
Self { lookup }
}
/// Maps a git event kind to the thread root it notifies about.
pub fn notification_root(&self, event: &Event) -> Option<EventId> {
match event.kind {
Kind::GitIssue | Kind::GitPullRequest => Some(event.id),
Kind::GitPatch => Some(match self.first_e_id(event) {
Some(parent) => self.resolve_thread_root(parent),
None => event.id,
}),
Kind::Comment => match nip22::extract_root(event) {
Some(CommentTarget::Event { id, .. }) => Some(self.resolve_thread_root(id)),
_ => None,
},
Kind::GitPullRequestUpdate => self
.first_uppercase_e_id(event)
.map(|root| self.resolve_thread_root(root)),
Kind::GitStatusOpen
| Kind::GitStatusApplied
| Kind::GitStatusClosed
| Kind::GitStatusDraft => self
.nip10_root_id(event)
.map(|root| self.resolve_thread_root(root)),
_ => None,
}
}
/// Follows parent pointers until a git issue or pull request root is reached.
pub fn resolve_thread_root(&self, id: EventId) -> EventId {
let mut seen = HashSet::new();
let mut root = id;
loop {
if !seen.insert(root) {
return id;
}
let Some(event) = (self.lookup)(root) else {
return root;
};
if matches!(event.kind, Kind::GitIssue | Kind::GitPullRequest) {
return root;
}
match self.parent_id(&event) {
Some(parent) => root = parent,
None => return root,
}
}
}
/// Mirrors gitworkshop's `getParentId` parent resolution.
fn parent_id(&self, event: &Event) -> Option<EventId> {
for marker in ["reply", "root"] {
if let Some(id) = event
.tags
.iter()
.find_map(|tag| self.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);
}
self.first_uppercase_e_id(event)
}
/// Reads the NIP-10 `root` marker, falling back to the first `e` tag.
fn nip10_root_id(&self, event: &Event) -> Option<EventId> {
event
.tags
.iter()
.find_map(|tag| self.e_tag_with_marker(tag, "root"))
.or_else(|| self.first_e_id(event))
}
/// Reads the first lowercase `e` tag id.
fn first_e_id(&self, event: &Event) -> Option<EventId> {
self.first_tag_id(event, "e")
}
/// Reads the first uppercase `E` tag id.
fn first_uppercase_e_id(&self, event: &Event) -> Option<EventId> {
self.first_tag_id(event, "E")
}
/// Reads the first event id from tags of the given kind.
fn first_tag_id(&self, 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())
})
}
/// Parses a four-value `e` tag carrying the given marker.
fn e_tag_with_marker(&self, 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::*;
/// Derives deterministic signer keys from a seed byte.
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"))
}
/// Builds a signed event with a fixed timestamp.
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")
}
/// Builds a plain lowercase `e` tag for the event.
fn e_tag(event: &Event) -> Tag {
Tag::parse(["e", &event.id.to_hex()]).expect("valid e tag")
}
/// Builds a four-value `e` tag with the given marker.
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")
}
/// Builds an uppercase `E` tag for the event.
fn uppercase_e_tag(event: &Event) -> Tag {
Tag::parse(["E", &event.id.to_hex()]).expect("valid E tag")
}
/// Builds an event lookup closure over a slice.
fn lookup(events: &[Event]) -> impl Fn(EventId) -> Option<Event> + '_ {
move |id| events.iter().find(|event| event.id == id).cloned()
}
/// Builds a git issue event.
fn issue(author: &Keys, at: u64) -> Event {
signed(author, Kind::GitIssue, Vec::new(), at)
}
/// Resolves a comment to its uppercase `E` root.
#[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!(
ThreadResolver::new(&lookup(&events)).notification_root(&comment),
Some(issue.id)
);
}
/// Resolves a child patch to its root patch.
#[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!(
ThreadResolver::new(&lookup(&events)).notification_root(&child_patch),
Some(root_patch.id)
);
}
/// Resolves a status through its `root` marker tag.
#[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!(
ThreadResolver::new(&lookup(&events)).notification_root(&status),
Some(issue.id)
);
}
/// Follows a nested comment chain to the issue root.
#[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!(
ThreadResolver::new(&lookup(&events)).notification_root(&nested),
Some(issue.id)
);
}
}
+6 -14
View File
@@ -1,19 +1,11 @@
pub mod addr;
pub mod announcement;
pub mod deletions;
pub mod builders;
pub mod clone_url;
pub mod filters;
pub mod git_event;
pub mod inbox;
pub mod pull_request;
pub mod model;
pub mod status;
pub mod upstream;
pub use addr::RepoAddr;
pub use announcement::Announcement;
pub use deletions::Deletions;
pub use filters::Filters;
pub use git_event::GitEvent;
pub use inbox::{InboxItem, InboxReadState, ThreadResolver};
pub use pull_request::PullRequest;
pub use status::RepoStatus;
pub use upstream::Upstream;
pub use clone_url::{CloneTarget, parse_clone_url};
pub use model::Announcement;
pub use status::{RepoStatus, references_root, resolve_status};
+86
View File
@@ -0,0 +1,86 @@
use nostr::prelude::*;
/// Parsed NIP-34 repository announcement (plain data, ready for the UI).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Announcement {
/// Author of the announcement event.
pub owner: PublicKey,
/// When the announcement was published (for latest-wins resolution).
pub created_at: Timestamp,
/// Repository ID (`d` tag).
pub id: String,
pub name: Option<String>,
pub description: Option<String>,
/// Webpage URLs for browsing.
pub web: Vec<String>,
/// URLs for `git clone`.
pub clone: Vec<String>,
/// Relays the repository monitors for patches and issues.
pub relays: Vec<String>,
/// Earliest unique commit ID (`r` tag with `euc` marker).
pub euc: Option<String>,
/// Other recognized maintainers.
pub maintainers: Vec<PublicKey>,
}
impl Announcement {
/// Parse a kind `30617` event. Returns `None` if the kind is wrong or the `d` tag is missing.
pub fn from_event(event: &Event) -> Option<Self> {
if event.kind != Kind::GitRepoAnnouncement {
return None;
}
let mut id: Option<String> = None;
let mut name: Option<String> = None;
let mut description: Option<String> = None;
let mut web: Vec<String> = Vec::new();
let mut clone: Vec<String> = Vec::new();
let mut relays: Vec<String> = Vec::new();
let mut euc: Option<String> = None;
let mut maintainers: Vec<PublicKey> = Vec::new();
for tag in event.tags.iter() {
let values: &[String] = tag.as_slice();
match tag.kind() {
"d" => id = tag.content().map(str::to_owned),
"name" => name = tag.content().map(str::to_owned),
"description" => description = tag.content().map(str::to_owned),
"web" => web.extend(values.iter().skip(1).cloned()),
"clone" => clone.extend(values.iter().skip(1).cloned()),
"relays" => relays.extend(values.iter().skip(1).cloned()),
"r" => {
if values.get(2).map(String::as_str) == Some("euc") {
euc = tag.content().map(str::to_owned);
}
}
"maintainers" => {
maintainers.extend(
values
.iter()
.skip(1)
.filter_map(|v| PublicKey::from_hex(v).ok()),
);
}
_ => {}
}
}
Some(Self {
owner: event.pubkey,
created_at: event.created_at,
id: id?,
name,
description,
web,
clone,
relays,
euc,
maintainers,
})
}
/// The repository address of this announcement.
pub fn addr(&self) -> crate::RepoAddr {
crate::RepoAddr::new(self.owner, self.id.clone())
}
}
-280
View File
@@ -1,280 +0,0 @@
use nostr::prelude::*;
use crate::git_event::GitEvent;
pub struct PullRequest<'a>(pub &'a Event);
impl<'a> PullRequest<'a> {
/// Wraps a pull request root event.
pub fn new(event: &'a Event) -> Self {
Self(event)
}
/// Returns the ordered patch series, found via the root reference or the tip commit.
pub fn patches(&self, patches: impl IntoIterator<Item = &'a Event>) -> Vec<&'a Event> {
let pr = self.0;
let patches: Vec<&'a Event> = patches.into_iter().collect();
if let Some(root_id) = pr.tags.event_ids().next()
&& let Some(root) = patches.iter().find(|patch| patch.id == root_id)
{
return Self::forward_series(root, &patches);
}
let Some(tip) = pr.current_commit() else {
return Vec::new();
};
let Some(last) = patches
.iter()
.filter(|patch| Self::patch_produces_commit(patch, &tip))
.max_by_key(|patch| patch.created_at)
.copied()
else {
return Vec::new();
};
let mut series = vec![last];
let mut tail = last;
loop {
let Some(prev_id) = tail.tags.event_ids().next() else {
break;
};
let Some(prev) = patches
.iter()
.find(|patch| patch.id == prev_id && !series.contains(patch))
.copied()
else {
break;
};
series.push(prev);
tail = prev;
}
series.reverse();
series
}
/// Joins the patch series with newlines, falling back to the event content.
pub fn patch(&self, patches: impl IntoIterator<Item = &'a Event>) -> String {
let pr = self.0;
let patches: Vec<&'a Event> = patches.into_iter().collect();
let series = self.patches(patches.iter().copied());
if series.is_empty() {
return pr.content.clone();
}
series
.iter()
.map(|patch| patch.content.as_str())
.collect::<Vec<_>>()
.join("\n")
}
/// Returns the root author's newest update, since only the author may move the tip.
pub fn latest_update(
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)
}
/// Walks reply links outward from the root patch, taking the newest child first.
fn forward_series(root: &'a Event, patches: &[&'a Event]) -> Vec<&'a Event> {
let mut series = vec![root];
let mut tail = root;
loop {
let next = patches
.iter()
.filter(|patch| !series.contains(patch))
.filter(|patch| patch.tags.event_ids().any(|id| id == tail.id))
.max_by_key(|patch| patch.created_at);
let Some(next) = next else {
break;
};
series.push(next);
tail = next;
}
series
}
/// Checks the commit against the patch's `c` and `r` tags.
fn patch_produces_commit(patch: &Event, commit: &str) -> bool {
patch
.tags
.iter()
.any(|tag| match Nip34Tag::parse(tag.as_slice()) {
Ok(Nip34Tag::Commit(c) | Nip34Tag::Reference(c)) => c.to_string() == commit,
_ => false,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Returns the test signer keys.
fn keys() -> Keys {
Keys::new(
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
.expect("valid secret key"),
)
}
/// Builds a signed pull request event.
fn pr_event(content: &str, tags: Vec<Tag>) -> Event {
EventBuilder::new(Kind::GitPullRequest)
.content(content)
.tags(tags)
.finalize(&keys())
.expect("signed event")
}
/// Builds a signed patch event with a fixed timestamp.
fn patch_event(content: &str, tags: Vec<Tag>, created_at: u64) -> Event {
EventBuilder::new(Kind::GitPatch)
.content(content)
.tags(tags)
.custom_created_at(Timestamp::from(created_at))
.finalize(&keys())
.expect("signed event")
}
/// Joins the full patch series into one diff.
#[test]
fn pull_request_patch_joins_the_whole_patch_set() {
let root = patch_event("patch-one", vec![], 100);
let second = patch_event("patch-two", vec![Tag::event(root.id)], 200);
let pr = pr_event("description", vec![Tag::event(root.id)]);
assert_eq!(
PullRequest::new(&pr).patch([&root, &second]),
"patch-one\npatch-two"
);
assert_eq!(
PullRequest::new(&pr).patches([&root, &second]),
vec![&root, &second]
);
}
/// Orders patches by walking the reply chain.
#[test]
fn pull_request_patches_walks_the_reply_chain_in_order() {
let root = patch_event("patch-one", vec![], 100);
let second = patch_event("patch-two", vec![Tag::event(root.id)], 200);
let third = patch_event("patch-three", vec![Tag::event(second.id)], 300);
let pr = pr_event("description", vec![Tag::event(root.id)]);
let series = PullRequest::new(&pr).patches([&third, &root, &second]);
assert_eq!(
series
.iter()
.map(|p| p.content.as_str())
.collect::<Vec<_>>(),
vec!["patch-one", "patch-two", "patch-three"]
);
}
/// Finds the patch series through the declared tip commit.
#[test]
fn pull_request_patches_finds_the_set_via_the_tip_commit() {
let root = patch_event("patch-one", vec![], 100);
let tip = "1111111111111111111111111111111111111111";
let last = patch_event(
"patch-two",
vec![
Tag::event(root.id),
Tag::parse(["r", tip]).expect("valid tag"),
],
200,
);
let pr = pr_event(
"description",
vec![Tag::parse(["c", tip]).expect("valid tag")],
);
let series = PullRequest::new(&pr).patches([&root, &last]);
assert_eq!(
series
.iter()
.map(|p| p.content.as_str())
.collect::<Vec<_>>(),
vec!["patch-one", "patch-two"]
);
}
const COMMIT_HEX: &str = "1111111111111111111111111111111111111111";
const OTHER_ROOT_HEX: &str = "2222222222222222222222222222222222222222";
/// Builds a signed event with a fixed timestamp.
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")
}
/// Builds the pull request root used by the update tests.
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,
)
}
/// Picks the newest update targeting the root.
#[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,
)
};
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 = PullRequest::latest_update(events.iter(), &root).expect("an update");
assert_eq!(latest.created_at.as_secs(), 300);
assert_eq!(latest.kind, Kind::GitPullRequestUpdate);
}
/// Ignores updates from authors other than the root owner.
#[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");
assert!(PullRequest::latest_update([&stranger, &root].into_iter(), &root).is_none());
}
}
+16 -90
View File
@@ -1,5 +1,6 @@
use nostr::prelude::*;
/// Status of a root patch, pull request or issue (kinds `1630..=1633`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RepoStatus {
Open,
@@ -27,12 +28,25 @@ impl RepoStatus {
Self::Draft => Kind::GitStatusDraft,
}
}
}
pub fn resolve<'a, I>(
/// Check whether a status event references the given root event via an `e` tag.
pub fn references_root(event: &Event, root: &EventId) -> bool {
let root_hex: String = root.to_hex();
event
.tags
.iter()
.any(|t| t.kind() == "e" && t.content() == Some(root_hex.as_str()))
}
/// Resolve the status of a root event per NIP-34:
/// the most recent status event from the root author or a maintainer wins.
/// Defaults to [`RepoStatus::Open`].
pub fn resolve_status<'a, I>(
status_events: I,
root_author: &PublicKey,
maintainers: &[PublicKey],
) -> Self
) -> RepoStatus
where
I: IntoIterator<Item = &'a Event>,
{
@@ -44,91 +58,3 @@ impl RepoStatus {
.and_then(|e| RepoStatus::from_kind(e.kind))
.unwrap_or(RepoStatus::Open)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GitEvent;
const ROOT_ID_HEX: &str = "1111111111111111111111111111111111111111111111111111111111111111";
const OTHER_ID_HEX: &str = "2222222222222222222222222222222222222222222222222222222222222222";
fn keys_from_hex(hex: &str) -> Keys {
Keys::new(SecretKey::from_hex(hex).expect("valid secret key"))
}
fn root_event_id() -> EventId {
EventId::from_hex(ROOT_ID_HEX).expect("valid event id")
}
fn status_event(author: &Keys, kind: Kind, root: EventId, created_at: u64) -> Event {
EventBuilder::new(kind)
.tags([Tag::event(root)])
.custom_created_at(Timestamp::from(created_at))
.finalize(author)
.expect("signed event")
}
#[test]
fn references_root_matches_e_tag() {
let root = root_event_id();
let event = EventBuilder::new(Kind::GitStatusOpen)
.tags([Tag::event(root)])
.finalize(&keys_from_hex(
"0000000000000000000000000000000000000000000000000000000000000001",
))
.expect("signed event");
assert!(event.references_root(&root));
assert!(!event.references_root(&EventId::from_hex(OTHER_ID_HEX).expect("valid id")));
}
#[test]
fn latest_status_wins() {
let owner =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let root = root_event_id();
let statuses = [
status_event(&maintainer, Kind::GitStatusClosed, root, 100),
status_event(&owner, Kind::GitStatusOpen, root, 200),
];
assert_eq!(
RepoStatus::resolve(
statuses.iter(),
&owner.public_key(),
&[maintainer.public_key()]
),
RepoStatus::Open
);
}
#[test]
fn ignores_statuses_from_others() {
let owner =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000001");
let maintainer =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000002");
let stranger =
keys_from_hex("0000000000000000000000000000000000000000000000000000000000000003");
let root = root_event_id();
let statuses = [
status_event(&stranger, Kind::GitStatusClosed, root, 300),
status_event(&maintainer, Kind::GitStatusDraft, root, 100),
];
assert_eq!(
RepoStatus::resolve(
statuses.iter(),
&owner.public_key(),
&[maintainer.public_key()]
),
RepoStatus::Draft
);
}
}
-33
View File
@@ -1,33 +0,0 @@
use nostr::prelude::*;
use crate::RepoAddr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Upstream {
pub raw: String,
pub addr: Option<RepoAddr>,
}
impl Upstream {
/// Parses a raw `u` tag value, extracting the coordinate when present.
pub(crate) fn parse(raw: &str) -> Self {
let coordinate = raw.split('|').next().unwrap_or(raw);
let addr = coordinate
.parse::<Coordinate>()
.ok()
.filter(|coordinate| coordinate.kind == Kind::GitRepoAnnouncement)
.map(RepoAddr::from);
Self {
raw: raw.to_owned(),
addr,
}
}
/// Shows the coordinate when parsed, otherwise the raw value.
pub fn display(&self) -> String {
match &self.addr {
Some(addr) => addr.to_string(),
None => self.raw.clone(),
}
}
}
+1 -14
View File
@@ -8,18 +8,5 @@ publish.workspace = true
signed_core = { path = "../signed_core" }
nostr.workspace = true
serde.workspace = true
serde_json.workspace = true
log.workspace = true
gix.workspace = true
anyhow.workspace = true
gix = { workspace = true, features = ["revision", "blob-diff"] }
gix-worktree = "0.57"
gix-worktree-state = "0.35"
diffy = "0.5"
ignore = "0.4"
[dev-dependencies]
tempfile = "3"
[lints]
workspace = true
-114
View File
@@ -1,114 +0,0 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use anyhow::Result;
use signed_core::{Announcement, RepoAddr};
use crate::repo::Repo;
#[derive(Debug, Clone)]
pub struct GitCache {
root: PathBuf,
clone_locks: Arc<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>>,
}
impl GitCache {
/// Creates a cache rooted at `root`.
pub fn new(root: PathBuf) -> Self {
Self {
root,
clone_locks: Arc::default(),
}
}
/// Returns the cache root directory.
pub fn root(&self) -> &Path {
&self.root
}
/// Returns the cache path for a repository address.
pub fn repo_path(&self, addr: &RepoAddr) -> PathBuf {
self.root
.join(addr.public_key().to_hex())
.join(Self::sanitize_path_component(addr.identifier()))
}
/// Opens the cached repository, or `None` when it is not cloned yet.
pub fn open(&self, addr: &RepoAddr) -> Result<Option<Repo>> {
let path = self.repo_path(addr);
match gix::open(&path) {
Ok(repo) => Ok(Some(Repo::new(repo))),
Err(e) if e.is_not_found() => Ok(None),
Err(e) => Err(e.into()),
}
}
/// Returns the clone lock for `path`, creating it on first use.
fn clone_lock(&self, path: &Path) -> Arc<Mutex<()>> {
let mut locks = self
.clone_locks
.lock()
.unwrap_or_else(PoisonError::into_inner);
Arc::clone(locks.entry(path.to_path_buf()).or_default())
}
/// Returns the cached repository, cloning from one of `clone_urls` on first use.
pub fn ensure_clone<U: AsRef<str>>(&self, addr: &RepoAddr, clone_urls: &[U]) -> Result<Repo> {
let path = self.repo_path(addr);
// Lock the clone lock for this path to prevent concurrent clones.
let clone_lock = self.clone_lock(&path);
let _clone_guard = clone_lock.lock().unwrap_or_else(PoisonError::into_inner);
// Refreshes the cached repository if it is already cloned, or clones it from one of `clone_urls` otherwise.
if let Ok(Some(repo)) = self.open(addr) {
if let Err(error) = repo.fetch() {
log::warn!("failed to refresh the cached repository: {error:#}");
}
return Ok(repo);
}
// Create the parent directory if it does not exist.
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
// Remove the cached clone if it exists but is unusable.
if path.exists() {
log::warn!("removing unusable cached clone at {}", path.display());
std::fs::remove_dir_all(&path)?;
}
Repo::clone(clone_urls, &path)
}
/// Maps untrusted relay content onto 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
}
/// Returns the `owner/identifier` namespace used for fork checkouts.
pub fn fork_namespace(announcement: &Announcement) -> String {
format!(
"{}/{}",
announcement.owner.to_hex(),
Self::sanitize_path_component(&announcement.id)
)
}
}
-237
View File
@@ -1,237 +0,0 @@
use gix::diff::blob::unified_diff::{ConsumeHunk, DiffLineKind as GixLineKind, HunkHeader};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffLineKind {
Context,
Addition,
Deletion,
}
#[derive(Debug, Clone)]
pub struct DiffLine {
pub kind: DiffLineKind,
pub old: Option<u32>,
pub new: Option<u32>,
pub text: String,
}
impl DiffLine {
/// Creates a diff line with its kind, optional line numbers, and text.
pub fn new(kind: DiffLineKind, old: Option<u32>, new: Option<u32>, text: String) -> Self {
Self {
kind,
old,
new,
text,
}
}
}
#[derive(Debug, Clone)]
pub struct DiffHunk {
pub old_start: u32,
pub old_lines: u32,
pub new_start: u32,
pub new_lines: u32,
pub lines: Vec<DiffLine>,
}
impl DiffHunk {
/// Creates a hunk spanning the given old and new ranges.
pub fn new(
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
lines: Vec<DiffLine>,
) -> Self {
Self {
old_start,
old_lines,
new_start,
new_lines,
lines,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffStatus {
Added,
Modified,
Deleted,
Renamed,
Copied,
}
#[derive(Debug, Clone)]
pub struct FileDiff {
pub path: String,
pub old_path: Option<String>,
pub status: DiffStatus,
pub insertions: usize,
pub deletions: usize,
pub binary: bool,
pub hunks: Vec<DiffHunk>,
}
impl FileDiff {
/// Creates a file diff; `old_path` is the rename or copy source and `binary` files have no hunks.
pub fn new(
path: String,
old_path: Option<String>,
status: DiffStatus,
insertions: usize,
deletions: usize,
binary: bool,
hunks: Vec<DiffHunk>,
) -> Self {
Self {
path,
old_path,
status,
insertions,
deletions,
binary,
hunks,
}
}
}
#[derive(Debug, Clone)]
pub struct CommitDiff {
pub files: Vec<FileDiff>,
}
impl CommitDiff {
/// Creates a commit diff from its files.
pub fn new(files: Vec<FileDiff>) -> Self {
Self { files }
}
}
pub(crate) struct HunkBuilder {
old_start: u32,
old_lines: u32,
new_start: u32,
new_lines: u32,
old: u32,
new: u32,
lines: Vec<DiffLine>,
insertions: usize,
deletions: usize,
}
impl HunkBuilder {
/// Starts a hunk spanning the given old and new ranges.
pub(crate) fn new(old_start: u32, old_lines: u32, new_start: u32, new_lines: u32) -> Self {
Self {
old_start,
old_lines,
new_start,
new_lines,
old: old_start,
new: new_start,
lines: Vec::new(),
insertions: 0,
deletions: 0,
}
}
/// Appends a line, numbering it and counting insertions and deletions.
pub(crate) fn push(&mut self, kind: DiffLineKind, text: impl Into<String>) {
let (old_no, new_no) = match kind {
DiffLineKind::Context => {
let numbers = (Some(self.old), Some(self.new));
self.old += 1;
self.new += 1;
numbers
}
DiffLineKind::Addition => {
self.insertions += 1;
let number = Some(self.new);
self.new += 1;
(None, number)
}
DiffLineKind::Deletion => {
self.deletions += 1;
let number = Some(self.old);
self.old += 1;
(number, None)
}
};
self.lines
.push(DiffLine::new(kind, old_no, new_no, text.into()));
}
/// Finishes the hunk and returns it with its insertion and deletion counts.
pub(crate) fn finish(self) -> (DiffHunk, usize, usize) {
let hunk = DiffHunk::new(
self.old_start,
self.old_lines,
self.new_start,
self.new_lines,
self.lines,
);
(hunk, self.insertions, self.deletions)
}
}
pub(crate) struct HunkCollector<'a> {
hunks: &'a mut Vec<DiffHunk>,
insertions: &'a mut usize,
deletions: &'a mut usize,
}
impl<'a> HunkCollector<'a> {
/// Collects hunks into `hunks` while counting `insertions` and `deletions`.
pub(crate) fn new(
hunks: &'a mut Vec<DiffHunk>,
insertions: &'a mut usize,
deletions: &'a mut usize,
) -> Self {
Self {
hunks,
insertions,
deletions,
}
}
}
impl ConsumeHunk for HunkCollector<'_> {
type Out = ();
/// Consumes one hunk, tracking line numbers and insertion/deletion counts.
fn consume_hunk(
&mut self,
header: HunkHeader,
lines: &[(GixLineKind, &[u8])],
) -> std::io::Result<()> {
let mut builder = HunkBuilder::new(
header.before_hunk_start,
header.before_hunk_len,
header.after_hunk_start,
header.after_hunk_len,
);
for (kind, content) in lines {
let kind = match kind {
GixLineKind::Context => DiffLineKind::Context,
GixLineKind::Remove => DiffLineKind::Deletion,
GixLineKind::Add => DiffLineKind::Addition,
};
builder.push(kind, String::from_utf8_lossy(content).into_owned());
}
let (hunk, insertions, deletions) = builder.finish();
*self.insertions += insertions;
*self.deletions += deletions;
self.hunks.push(hunk);
Ok(())
}
/// Marks the end of the unified diff stream.
fn finish(self) {}
}
-77
View File
@@ -1,77 +0,0 @@
pub const MAX_LISTED_COMMITS: usize = 20_000;
pub struct CommitList {
pub total: usize,
pub commits: Vec<FileCommit>,
}
impl CommitList {
/// Creates a list holding `total` commits of which `commits` are materialized.
pub fn new(total: usize, commits: Vec<FileCommit>) -> Self {
Self { total, commits }
}
}
#[derive(Debug, Clone)]
pub struct FileCommit {
pub id: String,
pub summary: String,
pub description: Option<String>,
pub author: String,
pub time: i64,
}
impl FileCommit {
/// Creates a commit entry from its id, message parts, author, and timestamp.
pub fn new(
id: String,
summary: String,
description: Option<String>,
author: String,
time: i64,
) -> Self {
Self {
id,
summary,
description,
author,
time,
}
}
/// Converts a gix commit including its message body.
pub(crate) fn from_commit(commit: &gix::Commit<'_>) -> anyhow::Result<Self> {
Self::from_commit_with_description(commit, true)
}
/// Converts a gix commit, skipping the message body since lists never show it.
pub(crate) fn from_commit_summary(commit: &gix::Commit<'_>) -> anyhow::Result<Self> {
Self::from_commit_with_description(commit, false)
}
/// Converts a gix commit, optionally skipping the message body.
fn from_commit_with_description(
commit: &gix::Commit<'_>,
include_description: bool,
) -> anyhow::Result<Self> {
use crate::GixResultExt as _;
let author = commit.author().into_anyhow()?;
let message = commit.message().into_anyhow()?;
Ok(FileCommit::new(
commit.id().shorten_or_id().to_string(),
String::from_utf8_lossy(message.title).trim().to_string(),
if include_description {
message
.body
.map(|body| String::from_utf8_lossy(body).trim().to_string())
.filter(|body| !body.is_empty())
} else {
None
},
String::from_utf8_lossy(author.name).trim().to_string(),
author.time().into_anyhow()?.seconds,
))
}
}
+116 -38
View File
@@ -1,51 +1,129 @@
mod cache;
mod diff;
mod history;
mod nip34;
mod patch;
mod repo;
mod scan;
mod sync;
mod worktree;
//! Blocking local git operations against GRASP servers.
//!
//! All functions may block; call them inside `cx.background_spawn`.
#[cfg(test)]
mod tests;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
pub use cache::GitCache;
pub use diff::{CommitDiff, DiffHunk, DiffLine, DiffLineKind, DiffStatus, FileDiff};
pub use history::{CommitList, FileCommit, MAX_LISTED_COMMITS};
pub use nip34::{GraspSignals, Nip34Binding, Nip34Kind};
pub use patch::PatchParser;
pub use repo::{Repo, RepoRefState};
pub use scan::{LocalRepo, find_git_repos};
pub use sync::{RefSync, RepoSyncStatus};
pub use worktree::WorktreeSnapshot;
use anyhow::{Context, Result, bail};
use gix::interrupt::IS_INTERRUPTED;
use gix::progress::Discard;
use signed_core::RepoAddr;
pub(crate) trait GixResultExt<T> {
/// Converts a gix exception result into an `anyhow` result.
fn into_anyhow(self) -> anyhow::Result<T>;
/// On-disk cache of cloned repositories, keyed by owner pubkey / repo id.
#[derive(Debug, Clone)]
pub struct GitCache {
root: PathBuf,
}
impl<T, E> GixResultExt<T> for Result<T, gix::Exn<E>>
where
E: std::error::Error + Send + Sync + 'static,
{
fn into_anyhow(self) -> anyhow::Result<T> {
self.map_err(|exn| anyhow::Error::from(exn.into_error()))
impl GitCache {
pub fn new(root: PathBuf) -> Self {
Self { root }
}
/// Local path of the clone for a repository.
pub fn repo_path(&self, addr: &RepoAddr) -> PathBuf {
self.root
.join(addr.owner.to_hex())
.join(sanitize_path_component(&addr.id))
}
/// Open an existing clone.
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()),
}
}
#[cfg(test)]
fn git_in(dir: &std::path::Path, args: &[&str]) -> anyhow::Result<String> {
let output = Repo::run_git(dir, args, "git")?;
/// Open the local clone if it exists (fetching first), otherwise clone
/// from the first working URL in `clone_urls` (the announcement's `clone` tag).
pub fn ensure_clone(&self, addr: &RepoAddr, clone_urls: &[String]) -> 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()))?;
}
let mut last_err: Option<anyhow::Error> = None;
for url in clone_urls {
match clone(url, &path) {
Ok(repo) => return Ok(repo),
Err(e) => last_err = Some(e),
}
}
match last_err {
Some(e) => Err(e).context("failed to clone from any mirror"),
None => bail!("no clone URLs provided"),
}
}
}
/// Fetch all configured refspecs from `origin`.
pub fn fetch_all(repo: &gix::Repository) -> Result<()> {
repo.find_remote("origin")?
.connect(gix::remote::Direction::Fetch)?
.prepare_fetch(Discard, Default::default())?
.receive(Discard, &IS_INTERRUPTED)?;
Ok(())
}
/// Apply a `git format-patch` patch (or series) with `git am`.
///
/// Uses the git CLI because it handles the mbox format natively; can be
/// replaced 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() {
anyhow::bail!(
"git {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&output.stderr).trim()
);
bail!("git am failed: {}", String::from_utf8_lossy(&output.stderr));
}
Ok(())
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
fn clone(url: &str, path: &Path) -> Result<gix::Repository> {
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)
}
fn sanitize_path_component(id: &str) -> String {
id.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'_'
}
})
.collect()
}
-63
View File
@@ -1,63 +0,0 @@
use nostr::prelude::*;
#[derive(serde::Deserialize)]
pub(crate) struct Nip34Json {
pub(crate) identifier: Option<String>,
pub(crate) owner: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Nip34Kind {
Initialized,
Cloned,
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,
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 {
/// Returns whether any Nostr tooling marker was found.
pub fn any(&self) -> bool {
*self != Self::default()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Nip34Binding {
pub kind: Nip34Kind,
pub signals: GraspSignals,
pub owner: Option<PublicKey>,
pub identifier: Option<String>,
pub grasp_urls: Vec<String>,
}
impl Nip34Binding {
/// Creates a binding from its kind, detected signals, and recovered coordinates.
pub fn new(
kind: Nip34Kind,
signals: GraspSignals,
owner: Option<PublicKey>,
identifier: Option<String>,
grasp_urls: Vec<String>,
) -> Self {
Self {
kind,
signals,
owner,
identifier,
grasp_urls,
}
}
}
-238
View File
@@ -1,238 +0,0 @@
use anyhow::Result;
use diffy::patch_set::{FileOperation, FilePatch, ParseOptions, PatchSet};
use diffy::{Hunk, Line};
use crate::diff::{CommitDiff, DiffHunk, DiffLineKind, DiffStatus, FileDiff, HunkBuilder};
use crate::history::FileCommit;
pub struct PatchParser;
impl PatchParser {
/// Splits an mbox series into the raw text of each message.
pub fn split_patch_series(patch: &str) -> Vec<&str> {
Self::envelopes(patch)
.into_iter()
.map(|message| message.text)
.collect()
}
/// Parses a git diff into file diffs, returning an empty diff without one.
pub fn patch_diffs(patch: &str) -> Result<CommitDiff> {
if !patch.lines().any(|line| line.starts_with("diff --git ")) {
return Ok(CommitDiff::new(Vec::new()));
}
let mut files = Vec::new();
for file in PatchSet::parse(patch, ParseOptions::gitdiff()) {
files.push(Self::file_diff(file?));
}
Ok(CommitDiff::new(files))
}
/// Lists the commits represented by the mbox messages that carry an id.
pub fn patch_commits(patch: &str) -> Vec<FileCommit> {
Self::envelopes(patch)
.into_iter()
.filter(|message| !message.id.is_empty())
.map(|message| {
FileCommit::new(
message.id.to_string(),
message
.header("Subject")
.map(Self::strip_patch_prefix)
.unwrap_or_default(),
None,
message
.header("From")
.map(Self::name_from_address)
.unwrap_or_default(),
message
.header("Date")
.and_then(|value| gix::date::parse(value.trim(), None).ok())
.map(|time| time.seconds)
.unwrap_or(0),
)
})
.collect()
}
/// Splits `patch` on `From <40-hex> <date>` envelopes, falling back to one message.
fn envelopes(patch: &str) -> Vec<Envelope<'_>> {
let mut messages: Vec<Envelope<'_>> = Vec::new();
let mut current: Option<(usize, &str, Vec<&str>)> = None;
let mut headers_closed = false;
let mut offset = 0usize;
for line in patch.lines() {
let line_start = offset;
offset += line.len() + 1;
let is_envelope = line
.strip_prefix("From ")
.and_then(|rest| rest.split_whitespace().next())
.is_some_and(|id| id.len() == 40);
if is_envelope {
if let Some((start, id, headers)) = current.take() {
messages.push(Envelope::new(&patch[start..], id, headers));
}
let id = line
.strip_prefix("From ")
.and_then(|rest| rest.split_whitespace().next())
.unwrap_or("");
current = Some((line_start, id, Vec::new()));
headers_closed = false;
continue;
}
if let Some((_, _, headers)) = &mut current {
if headers_closed {
continue;
}
if line.is_empty() {
headers_closed = true;
} else {
headers.push(line);
}
}
}
if let Some((start, id, headers)) = current.take() {
messages.push(Envelope::new(&patch[start..], id, headers));
}
if messages.is_empty() {
messages.push(Envelope::new(patch, "", Vec::new()));
}
messages
}
/// Extracts the display name from a `From` header value.
fn name_from_address(from: &str) -> String {
match from.trim().find('<') {
Some(ix) => from[..ix].trim().to_string(),
None => from.trim().to_string(),
}
}
/// Strips mailing list prefixes like `[PATCH]` or `[RFC PATCH 1/2]`.
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()
}
}
/// Converts one parsed file patch, keeping rename and copy paths unstripped.
fn file_diff(file: FilePatch<'_, str>) -> FileDiff {
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_insertions, hunk_deletions) = Self::hunk_diff(hunk);
insertions += hunk_insertions;
deletions += hunk_deletions;
hunks.push(hunk);
}
}
FileDiff::new(
path.to_owned(),
old_path.map(str::to_owned),
status,
insertions,
deletions,
patch.is_binary(),
hunks,
)
}
/// Converts a diffy hunk into a `DiffHunk` with its insertion and deletion counts.
fn hunk_diff(hunk: &Hunk<'_, str>) -> (DiffHunk, usize, usize) {
let old_range = hunk.old_range();
let new_range = hunk.new_range();
let mut builder = HunkBuilder::new(
old_range.start() as u32,
old_range.len() as u32,
new_range.start() as u32,
new_range.len() as u32,
);
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 text = text.strip_suffix('\n').unwrap_or(text);
let text = text.strip_suffix('\r').unwrap_or(text);
builder.push(kind, text.to_owned());
}
builder.finish()
}
}
struct Envelope<'a> {
text: &'a str,
id: &'a str,
headers: Vec<&'a str>,
}
impl<'a> Envelope<'a> {
/// Creates an envelope from its text, commit id, and header lines.
fn new(text: &'a str, id: &'a str, headers: Vec<&'a str>) -> Self {
Self { text, id, headers }
}
/// Returns the first header line matching `name: `.
fn header(&self, name: &str) -> Option<&str> {
let prefix = format!("{name}: ");
self.headers
.iter()
.find(|line| line.starts_with(&prefix))
.map(|line| &line[prefix.len()..])
}
}
File diff suppressed because it is too large Load Diff
-82
View File
@@ -1,82 +0,0 @@
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use ignore::WalkBuilder;
use crate::nip34::Nip34Binding;
use crate::repo::Repo;
const SCAN_MAX_DEPTH: usize = 12;
#[derive(Debug, Clone)]
pub struct LocalRepo {
pub path: PathBuf,
pub nip34: Option<Nip34Binding>,
}
impl LocalRepo {
/// Creates a local repository entry from its path and optional NIP-34 binding.
pub fn new(path: PathBuf, nip34: Option<Nip34Binding>) -> Self {
Self { path, nip34 }
}
}
/// Finds git repositories under `root` up to `SCAN_MAX_DEPTH` deep, without descending into them.
pub fn find_git_repos(root: &Path) -> Vec<LocalRepo> {
let Ok(root) = root.canonicalize() else {
return Vec::new();
};
let found = Arc::new(Mutex::new(Vec::<PathBuf>::new()));
let walker = WalkBuilder::new(&root)
.max_depth(Some(SCAN_MAX_DEPTH))
.require_git(false)
.filter_entry({
let found = found.clone();
move |entry| {
let Some(kind) = entry.file_type() else {
return true;
};
if !kind.is_dir() {
return true;
}
let dir = entry.path();
let Ok(repo) = gix::discover(dir) else {
return true;
};
let Some(workdir) = repo.workdir() else {
return false;
};
if workdir != dir {
return true;
}
match found.lock() {
Ok(mut repos) => repos.push(dir.to_path_buf()),
Err(poisoned) => poisoned.into_inner().push(dir.to_path_buf()),
}
false
}
})
.build();
for _ in walker {}
let mut repos = match found.lock() {
Ok(mut repos) => std::mem::take(&mut *repos),
Err(poisoned) => std::mem::take(&mut *poisoned.into_inner()),
};
repos.sort();
repos
.into_iter()
.map(|path| {
let nip34 = Repo::open(&path).ok().and_then(|repo| repo.nip34_binding());
LocalRepo::new(path, nip34)
})
.collect()
}
-42
View File
@@ -1,42 +0,0 @@
use std::collections::BTreeMap;
/// How a single branch compares between local and Nostr.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RefSync {
InSync,
LocalAhead { ahead: usize },
RemoteAhead { behind: usize },
Diverged { ahead: usize, behind: usize },
LocalOnly,
RemoteOnly,
}
/// Branch comparison between a local repository and its Nostr state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepoSyncStatus {
/// Branch short name and its classification.
pub refs: Vec<(String, RefSync)>,
pub ahead_total: usize,
pub behind_total: usize,
/// Current branch short name of the checkout, `None` when detached.
pub head: Option<String>,
/// Ids of commits reachable from HEAD that publish the current branch as a fast-forward.
pub ahead_commits: Vec<String>,
}
impl RepoSyncStatus {
/// True when every branch matches the Nostr state.
pub fn in_sync(&self) -> bool {
self.refs.iter().all(|(_, sync)| *sync == RefSync::InSync)
}
/// Maps branch short name to lowercase commit oid.
pub(crate) fn branches(refs: &[(String, String)]) -> BTreeMap<&str, String> {
refs.iter()
.filter_map(|(name, commit)| {
name.strip_prefix("refs/heads/")
.map(|branch| (branch, commit.to_ascii_lowercase()))
})
.collect()
}
}
-994
View File
@@ -1,994 +0,0 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use nostr::prelude::Keys;
use signed_core::RepoAddr;
use super::*;
#[test]
fn blocks_parent_components() {
assert_eq!(GitCache::sanitize_path_component(".."), "_");
assert_eq!(GitCache::sanitize_path_component("."), "_");
assert_eq!(GitCache::sanitize_path_component("../.."), ".._..");
assert_eq!(GitCache::sanitize_path_component("a/../b"), "a_.._b");
}
#[test]
fn concurrent_ensure_clone_succeeds_for_every_caller() {
let server = tempfile::tempdir().expect("tempdir");
let server_repo = bare_server(server.path(), "npub1test", "repo");
let (work_dir, work_repo) = fixture(&[("a.txt", b"one")]);
commit_all(&work_repo, "initial");
let work_dir = work_dir.path();
let base_url = format!("file://{}", server.path().display());
Repo::open(work_dir)
.expect("open")
.push_all(&base_url, "npub1test", "repo")
.expect("push");
let cache_dir = tempfile::tempdir().expect("tempdir");
let cache = GitCache::new(cache_dir.path().to_path_buf());
let addr = RepoAddr::new(Keys::generate().public_key(), "repo");
let clone_url = format!("file://{}", server_repo.display());
std::thread::scope(|scope| {
for _ in 0..4 {
scope.spawn(|| {
cache
.ensure_clone(&addr, &[&clone_url])
.expect("ensure_clone");
});
}
});
assert!(cache.open(&addr).expect("open").is_some());
}
#[test]
fn ensure_clone_recovers_from_a_leftover_directory() {
let server = tempfile::tempdir().expect("tempdir");
let server_repo = bare_server(server.path(), "npub1test", "repo");
let (work_dir, work_repo) = fixture(&[("a.txt", b"one")]);
commit_all(&work_repo, "initial");
let work_dir = work_dir.path();
let base_url = format!("file://{}", server.path().display());
Repo::open(work_dir)
.expect("open")
.push_all(&base_url, "npub1test", "repo")
.expect("push");
let cache_dir = tempfile::tempdir().expect("tempdir");
let cache = GitCache::new(cache_dir.path().to_path_buf());
let addr = RepoAddr::new(Keys::generate().public_key(), "repo");
let clone_url = format!("file://{}", server_repo.display());
// Simulate the remains of an interrupted clone.
let leftover = cache.repo_path(&addr);
std::fs::create_dir_all(&leftover).expect("mkdir");
cache
.ensure_clone(&addr, &[&clone_url])
.expect("ensure_clone");
assert!(cache.open(&addr).expect("open").is_some());
}
#[test]
fn root_commit_reports_the_first_ancestor() {
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let dir = dir.path();
let root = repo.root_commit().expect("root").expect("commit");
assert_eq!(root.len(), 40);
std::fs::write(dir.join("b.txt"), b"two").expect("write");
commit_all(&repo, "second");
assert_eq!(
repo.root_commit().expect("root").as_deref(),
Some(root.as_str())
);
}
#[test]
fn push_all_mirrors_branches_and_tags() {
let server = tempfile::tempdir().unwrap();
let server_repo = bare_server(server.path(), "npub1test", "my-repo");
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let dir = dir.path();
git_run(dir, &["checkout", "-b", "feature"]);
std::fs::write(dir.join("b.txt"), b"two").expect("write");
commit_all(&repo, "feature work");
git_run(dir, &["checkout", "-"]);
git_run(dir, &["tag", "v1.0"]);
let base_url = format!("file://{}", server.path().display());
Repo::open(dir)
.expect("open")
.push_all(&base_url, "npub1test", "my-repo")
.expect("push");
let refs = git_in(&server_repo, &["show-ref"]).expect("server refs");
assert!(refs.contains("refs/heads/main"));
assert!(refs.contains("refs/heads/feature"));
assert!(refs.contains("refs/tags/v1.0"));
}
#[test]
fn ls_remote_lists_branches_and_tags_only() {
let server = tempfile::tempdir().unwrap();
let server_repo = bare_server(server.path(), "npub1test", "my-repo");
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let dir = dir.path();
git_run(dir, &["branch", "feature"]);
git_run(dir, &["tag", "v1"]);
git_run(dir, &["tag", "-a", "v2", "-m", "annotated"]);
let base_url = format!("file://{}", server.path().display());
let local = Repo::open(dir).expect("open");
local
.push_all(&base_url, "npub1test", "my-repo")
.expect("push");
// Refs outside heads and tags, and the HEAD symref line, are not listed.
let main = git_in(dir, &["rev-parse", "refs/heads/main"]).expect("main oid");
git_run(&server_repo, &["update-ref", "refs/nostr/abc", &main]);
let remote = local
.ls_remote(&format!("file://{}", server_repo.display()))
.expect("ls-remote");
let names: Vec<String> = remote.iter().map(|(name, _)| name.clone()).collect();
assert_eq!(
names,
vec![
"refs/heads/feature".to_owned(),
"refs/heads/main".to_owned(),
"refs/tags/v1".to_owned(),
"refs/tags/v2".to_owned(),
]
);
assert_eq!(
remote
.iter()
.find(|(name, _)| name == "refs/heads/main")
.map(|(_, oid)| oid.as_str()),
Some(main.as_str())
);
// The annotated tag lists the tag object, matching the local ref state,
// without a peeled `^{}` duplicate.
let v2 = git_in(dir, &["rev-parse", "refs/tags/v2"]).expect("v2 oid");
assert_eq!(
remote
.iter()
.find(|(name, _)| name == "refs/tags/v2")
.map(|(_, oid)| oid.as_str()),
Some(v2.as_str())
);
}
#[test]
fn push_all_force_updates_diverged_remote_branches() {
let server = tempfile::tempdir().unwrap();
let server_repo = bare_server(server.path(), "npub1test", "my-repo");
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
std::fs::write(dir.path().join("b.txt"), b"two").expect("write");
commit_all(&repo, "second");
let dir = dir.path();
let base_url = format!("file://{}", server.path().display());
let local = Repo::open(dir).expect("open");
local
.push_all(&base_url, "npub1test", "my-repo")
.expect("initial push");
// Diverge local main from the pushed state.
git_run(dir, &["reset", "-q", "--hard", "HEAD~1"]);
std::fs::write(dir.join("c.txt"), b"three").expect("write");
commit_all(&repo, "diverged");
local
.push_all(&base_url, "npub1test", "my-repo")
.expect("force push");
assert_eq!(
git_in(dir, &["rev-parse", "refs/heads/main"]).expect("local main"),
git_in(&server_repo, &["rev-parse", "refs/heads/main"]).expect("server main")
);
}
#[test]
fn push_refspecs_deletes_server_refs_missing_locally() {
let server = tempfile::tempdir().unwrap();
let server_repo = bare_server(server.path(), "npub1test", "my-repo");
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let dir = dir.path();
git_run(dir, &["branch", "feature"]);
git_run(dir, &["tag", "v1"]);
let base_url = format!("file://{}", server.path().display());
let local = Repo::open(dir).expect("open");
local
.push_all(&base_url, "npub1test", "my-repo")
.expect("initial push");
git_run(dir, &["branch", "-D", "feature"]);
git_run(dir, &["tag", "-d", "v1"]);
local
.push_refspecs(
&base_url,
"npub1test",
"my-repo",
&[
"+refs/heads/*:refs/heads/*",
"+refs/tags/*:refs/tags/*",
":refs/heads/feature",
":refs/tags/v1",
],
)
.expect("push with deletions");
let refs = git_in(&server_repo, &["show-ref"]).expect("server refs");
assert!(refs.contains("refs/heads/main"));
assert!(!refs.contains("refs/heads/feature"));
assert!(!refs.contains("refs/tags/v1"));
}
#[test]
fn fetch_refs_brings_server_only_branches_into_local() {
let server = tempfile::tempdir().unwrap();
bare_server(server.path(), "npub1test", "my-repo");
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let dir = dir.path();
git_run(dir, &["branch", "feature"]);
let base_url = format!("file://{}", server.path().display());
Repo::open(dir)
.expect("open")
.push_all(&base_url, "npub1test", "my-repo")
.expect("push");
let feature = git_in(dir, &["rev-parse", "refs/heads/feature"]).expect("feature oid");
// A repository that never had the branch fetches it by name.
let (other_dir, _other_repo) = fixture(&[("unrelated.txt", b"x")]);
let other = Repo::open(other_dir.path()).expect("open other");
let server_url = format!("file://{}/npub1test/my-repo.git", server.path().display());
other
.fetch_refs(&[&server_url], "+refs/heads/feature:refs/heads/feature")
.expect("fetch ref");
assert_eq!(
git_in(other_dir.path(), &["rev-parse", "refs/heads/feature"]).expect("fetched feature"),
feature
);
}
#[test]
fn ref_state_matches_the_git_cli_ref_listing() {
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let dir = dir.path();
git_run(dir, &["branch", "browse-group"]);
git_run(dir, &["checkout", "-q", "-b", "new-search"]);
std::fs::write(dir.join("b.txt"), b"two").expect("write");
commit_all(&repo, "search work");
git_run(dir, &["checkout", "-q", "-"]);
git_run(dir, &["tag", "v1"]);
let listing = |repo: &Repo| {
let mut refs = repo.ref_state().expect("ref state").refs;
refs.sort();
refs
};
// Loose refs.
let loose = listing(&Repo::open(dir).expect("open"));
// Packed refs.
git_run(dir, &["pack-refs", "--all"]);
let packed = listing(&Repo::open(dir).expect("open"));
let output = git_run(
dir,
&[
"for-each-ref",
"--format=%(refname) %(objectname)",
"refs/heads",
"refs/tags",
],
);
let mut cli = String::from_utf8_lossy(&output.stdout)
.lines()
.map(|line| {
let (name, oid) = line.split_once(' ').expect("for-each-ref format");
(name.to_owned(), oid.to_owned())
})
.collect::<Vec<_>>();
cli.sort();
assert_eq!(loose, cli);
assert_eq!(packed, cli);
assert!(
loose
.iter()
.any(|(name, _)| name == "refs/heads/new-search")
);
assert!(
loose
.iter()
.any(|(name, _)| name == "refs/heads/browse-group")
);
}
#[test]
fn repo_ref_state_lists_branches_tags_and_head() {
let (_dir, repo) = fixture(&[("a.txt", b"hello")]);
commit_all(&repo, "initial");
let workdir = repo.workdir().expect("workdir").to_path_buf();
let state = repo.ref_state().expect("refs");
let branch = repo.current_branch().expect("on a branch");
assert_eq!(state.head.as_deref(), Some(branch.as_str()));
assert_eq!(state.refs.len(), 1);
assert_eq!(state.refs[0].0, format!("refs/heads/{branch}"));
assert_eq!(state.refs[0].1.len(), 40);
git_run(&workdir, &["branch", "feature"]);
git_run(&workdir, &["tag", "v1.0"]);
let state = repo.ref_state().expect("refs");
let mut expected: Vec<String> = vec![
format!("refs/heads/{branch}"),
"refs/heads/feature".to_owned(),
"refs/tags/v1.0".to_owned(),
];
expected.sort();
assert_eq!(
state
.refs
.iter()
.map(|(name, _)| name.clone())
.collect::<Vec<_>>(),
expected
);
git_run(&workdir, &["checkout", "--detach"]);
let state = repo.ref_state().expect("refs");
assert!(state.head.is_none());
assert_eq!(state.refs.len(), 3);
}
/// Creates a repository fixture with the given files.
fn fixture(files: &[(&str, &[u8])]) -> (tempfile::TempDir, Repo) {
let dir = tempfile::tempdir().expect("tempdir");
gix::init(&dir).expect("init");
for (rel, bytes) in files {
let path = dir.path().join(rel);
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
std::fs::write(&path, bytes).expect("write");
}
let repo = Repo::open(dir.path()).expect("open");
(dir, repo)
}
/// Stages and commits every change in the repository.
fn commit_all(repo: &Repo, message: &str) {
git_run(repo.workdir().expect("workdir"), &["add", "-A"]);
git_run(repo.workdir().expect("workdir"), &["commit", "-m", message]);
}
#[test]
fn merge_base_finds_the_fork_point_and_reports_unrelated_history() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("repo");
let initial = Repo::init(&path, "My Repo", "desc").expect("init");
let repo = Repo::open(&path).expect("open");
git_run(&path, &["checkout", "-b", "feature"]);
std::fs::write(path.join("feature.txt"), "feature\n").expect("write");
commit_all(&repo, "feature commit");
git_run(&path, &["checkout", "main"]);
std::fs::write(path.join("main.txt"), "main\n").expect("write");
commit_all(&repo, "mainline commit");
assert_eq!(
repo.merge_base("feature", "main")
.expect("merge base")
.as_deref(),
Some(initial.as_str())
);
git_run(&path, &["checkout", "--orphan", "orphan"]);
std::fs::write(path.join("orphan.txt"), "orphan\n").expect("write");
commit_all(&repo, "orphan commit");
assert_eq!(repo.merge_base("orphan", "main").expect("ok"), None);
assert!(repo.merge_base("orphan", "no-such-ref").is_err());
}
#[test]
fn sync_status_lists_commits_missing_from_nostr() {
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root");
std::fs::write(dir.path().join("b.txt"), b"two").expect("write");
commit_all(&repo, "second");
let second = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("second");
std::fs::write(dir.path().join("c.txt"), b"three").expect("write");
commit_all(&repo, "third");
let third = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("third");
let branch = repo.current_branch().expect("branch");
let ahead = repo
.sync_status(&[(format!("refs/heads/{branch}"), root.clone())])
.expect("status");
assert_eq!(ahead.head.as_deref(), Some(branch.as_str()));
assert_eq!(ahead.ahead_total, 2);
assert_eq!(ahead.ahead_commits.len(), 2);
assert!(ahead.ahead_commits.contains(&second));
assert!(ahead.ahead_commits.contains(&third));
assert!(!ahead.ahead_commits.contains(&root));
let in_sync = repo
.sync_status(&[(format!("refs/heads/{branch}"), third)])
.expect("status");
assert!(in_sync.ahead_commits.is_empty());
let missing = repo
.sync_status(&[(format!("refs/heads/{branch}"), "0".repeat(40))])
.expect("status");
assert!(missing.ahead_commits.is_empty());
}
#[test]
fn publishing_a_commit_advances_the_remote_tip() {
let server = tempfile::tempdir().expect("tempdir");
let server_repo = bare_server(server.path(), "npub1test", "my-repo");
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root");
std::fs::write(dir.path().join("b.txt"), b"two").expect("write");
commit_all(&repo, "second");
let second = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("second");
std::fs::write(dir.path().join("c.txt"), b"three").expect("write");
commit_all(&repo, "third");
let third = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("third");
let branch = repo.current_branch().expect("branch");
let refname = format!("refs/heads/{branch}");
let base_url = format!("file://{}", server.path().display());
let root_refspec = format!("+{root}:{refname}");
repo.push_refspecs(&base_url, "npub1test", "my-repo", &[root_refspec.as_str()])
.expect("publish root");
assert_eq!(
git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"),
root
);
let status = repo
.sync_status(&[(refname.clone(), root.clone())])
.expect("status");
assert_eq!(status.ahead_commits.len(), 2);
assert!(status.ahead_commits.contains(&second));
assert!(status.ahead_commits.contains(&third));
let second_refspec = format!("+{second}:{refname}");
repo.push_refspecs(
&base_url,
"npub1test",
"my-repo",
&[second_refspec.as_str()],
)
.expect("publish second");
assert_eq!(
git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"),
second
);
let status = repo
.sync_status(&[(refname, second.clone())])
.expect("status");
assert_eq!(status.ahead_commits, vec![third]);
}
#[test]
fn sync_status_skips_a_merged_commit_that_would_rewind_the_branch() {
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root");
let branch = repo.current_branch().expect("branch");
let refname = format!("refs/heads/{branch}");
git_run(dir.path(), &["checkout", "-q", "-b", "side"]);
std::fs::write(dir.path().join("side.txt"), b"side").expect("write");
commit_all(&repo, "side work");
let side = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("side");
git_run(dir.path(), &["checkout", "-q", branch.as_str()]);
std::fs::write(dir.path().join("main.txt"), b"main").expect("write");
commit_all(&repo, "main work");
let mainline = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("mainline");
assert_ne!(root, mainline);
git_run(
dir.path(),
&["merge", "-q", "--no-ff", "-m", "merge side", "side"],
);
let merge = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("merge");
let status = repo.sync_status(&[(refname, mainline)]).expect("status");
assert!(status.ahead_commits.contains(&merge));
assert!(!status.ahead_commits.contains(&root));
// Publishing the side commit would drop the merge and everything after it.
assert!(!status.ahead_commits.contains(&side));
}
#[test]
fn sync_status_skips_a_diverged_history() {
let (dir, repo) = fixture(&[("a.txt", b"one")]);
commit_all(&repo, "initial");
let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root");
let branch = repo.current_branch().expect("branch");
let refname = format!("refs/heads/{branch}");
std::fs::write(dir.path().join("published.txt"), b"published").expect("write");
commit_all(&repo, "published");
let published = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("published");
git_run(dir.path(), &["reset", "-q", "--hard", root.as_str()]);
std::fs::write(dir.path().join("local.txt"), b"local").expect("write");
commit_all(&repo, "local");
let local = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("local");
let status = repo.sync_status(&[(refname, published)]).expect("status");
assert!(status.ahead_commits.is_empty());
assert!(!status.ahead_commits.contains(&local));
}
#[test]
fn split_patch_series_splits_real_multi_commit_mboxes() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("repo");
let initial = Repo::init(&path, "My Repo", "desc").expect("init");
let repo = Repo::open(&path).expect("open");
git_run(&path, &["checkout", "-b", "feature"]);
std::fs::write(path.join("one.txt"), "one\n").expect("write");
commit_all(&repo, "first commit");
std::fs::write(path.join("two.txt"), "two\n").expect("write");
commit_all(&repo, "second commit");
let series = repo
.format_patch_between(&initial, "feature")
.expect("series");
let parts = PatchParser::split_patch_series(&series);
assert_eq!(parts.len(), 2);
assert!(parts[0].contains("Subject: [PATCH 1/2] first commit"));
assert!(parts[1].contains("Subject: [PATCH 2/2] second commit"));
let first = parts[0].lines().next().expect("first header");
let second = parts[1].lines().next().expect("second header");
assert!(first.starts_with("From ") && first.len() >= 45);
assert_ne!(first, second);
}
#[test]
fn head_commit_and_commits_since_track_applied_commits() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("repo");
let initial = Repo::init(&path, "My Repo", "desc").expect("init");
let repo = Repo::open(&path).expect("open");
assert_eq!(repo.head().as_deref(), Some(initial.as_str()));
assert_eq!(
repo.commits_since(None).expect("commits"),
vec![initial.clone()]
);
std::fs::write(path.join("one.txt"), "one\n").expect("write");
commit_all(&repo, "first commit");
let first = repo.head().expect("on a branch");
std::fs::write(path.join("two.txt"), "two\n").expect("write");
commit_all(&repo, "second commit");
let second = repo.head().expect("on a branch");
assert_eq!(
repo.commits_since(Some(&initial)).expect("commits"),
vec![first.clone(), second.clone()]
);
assert_eq!(
repo.commits_since(Some(&first)).expect("commits"),
vec![second]
);
}
#[test]
fn working_copy_cloned_from_the_mirror_matches_head_and_origin() {
let dir = tempfile::tempdir().expect("tempdir");
let mirror = dir.path().join("mirror");
let commit = Repo::init(&mirror, "My Repo", "Does things.").expect("init");
Repo::open(&mirror)
.expect("open")
.ensure_origin("https://gitnostr.com/npub1test/my-repo.git")
.expect("origin");
let destination = dir.path().join("folder").join("My_Repo");
std::fs::create_dir_all(destination.parent().unwrap()).expect("parent");
Repo::clone(&[format!("file://{}", mirror.display())], &destination).expect("clone");
Repo::open(&destination)
.expect("open")
.set_origin("https://gitnostr.com/npub1test/my-repo.git")
.expect("set origin");
let working = Repo::open(&destination).expect("open");
assert_eq!(
working.origin_url().expect("url").as_deref(),
Some("https://gitnostr.com/npub1test/my-repo.git")
);
assert_eq!(working.head().as_deref(), Some(commit.as_str()));
assert!(destination.join("README.md").is_file());
}
#[test]
fn fast_forward_branches_moves_the_mirror_and_keeps_local_work() {
let dir = tempfile::tempdir().expect("tempdir");
bare_server(dir.path(), "npub1test", "repo");
let (work_dir, work_repo) = fixture(&[("a.txt", b"one")]);
commit_all(&work_repo, "initial");
let work = work_dir.path();
let base_url = format!("file://{}", dir.path().display());
work_repo
.push_all(&base_url, "npub1test", "repo")
.expect("push");
let mirror = dir.path().join("mirror");
git_run(
dir.path(),
&[
"clone",
"-q",
&format!("{base_url}/npub1test/repo.git"),
mirror.to_str().unwrap(),
],
);
let initial = git_in(&mirror, &["rev-parse", "HEAD"]).expect("initial");
let repo = Repo::open(&mirror).expect("open");
std::fs::write(work.join("new.txt"), b"new\n").expect("write");
commit_all(&work_repo, "new commit");
work_repo
.push_all(&base_url, "npub1test", "repo")
.expect("push");
git_run(&mirror, &["fetch", "origin"]);
let remote = git_in(&mirror, &["rev-parse", "refs/remotes/origin/main"]).expect("remote");
assert_eq!(
git_in(&mirror, &["rev-parse", "HEAD"]).expect("local"),
initial
);
assert_ne!(remote, initial);
assert!(repo.fast_forward_branches().expect("ff"));
assert_eq!(
git_in(&mirror, &["rev-parse", "HEAD"]).expect("local"),
remote
);
assert!(mirror.join("new.txt").is_file());
assert!(!repo.fast_forward_branches().expect("idle"));
git_run(&mirror, &["checkout", "-b", "wip"]);
std::fs::write(mirror.join("wip.txt"), b"wip\n").expect("write");
commit_all(&repo, "local wip");
let wip = git_in(&mirror, &["rev-parse", "HEAD"]).expect("wip");
assert!(!repo.fast_forward_branches().expect("wip skipped"));
assert_eq!(
git_in(&mirror, &["rev-parse", "HEAD"]).expect("wip kept"),
wip
);
}
#[test]
fn fetch_repo_refs_imports_heads_under_a_prefix() {
let dir = tempfile::tempdir().expect("tempdir");
let base_server = bare_server(dir.path(), "npub1base", "base");
let (upstream_dir, upstream_repo) = fixture(&[("a.txt", b"one")]);
commit_all(&upstream_repo, "initial");
let upstream_path = upstream_dir.path();
let initial = git_in(upstream_path, &["rev-parse", "HEAD"]).expect("initial");
upstream_repo
.push_all(
&format!("file://{}", dir.path().display()),
"npub1base",
"base",
)
.expect("push");
let base_url = format!("file://{}", base_server.display());
let mirror = dir.path().join("mirror");
git_run(
dir.path(),
&["clone", "-q", &base_url, mirror.to_str().unwrap()],
);
let mirror_repo = Repo::open(&mirror).expect("open");
let fork_work = dir.path().join("fork-work");
git_run(
dir.path(),
&["clone", "-q", &base_url, fork_work.to_str().unwrap()],
);
git_run(&fork_work, &["checkout", "-b", "feature"]);
std::fs::write(fork_work.join("feature.txt"), "feature\n").expect("write");
commit_all(&Repo::open(&fork_work).expect("open"), "feature commit");
let tip = git_in(&fork_work, &["rev-parse", "HEAD"]).expect("tip");
let fork_server = bare_server(dir.path(), "npub1fork", "fork");
Repo::open(&fork_work)
.expect("open")
.push_ref(
&format!("file://{}", fork_server.display()),
&tip,
"refs/heads/feature",
)
.expect("push");
let dead = format!("file://{}/missing.git", dir.path().display());
mirror_repo
.fetch_refs(
&[dead, format!("file://{}", fork_server.display())],
"+refs/heads/*:refs/fork/npub1fork/fork/*",
)
.expect("fetch");
assert_eq!(
mirror_repo
.refs_with_prefix("refs/fork/npub1fork/fork")
.expect("refs"),
vec!["refs/fork/npub1fork/fork/feature"]
);
assert_eq!(
mirror_repo
.refs_with_prefix("refs/heads/fork")
.expect("refs"),
Vec::<String>::new()
);
assert_eq!(
mirror_repo
.merge_base(
"refs/remotes/origin/main",
"refs/fork/npub1fork/fork/feature",
)
.expect("merge base")
.as_deref(),
Some(initial.as_str())
);
let patch = mirror_repo
.format_patch_between(&initial, "refs/fork/npub1fork/fork/feature")
.expect("patch");
assert!(patch.contains("Subject: [PATCH] feature commit"));
assert!(patch.contains("feature.txt"));
mirror_repo
.delete_refs_with_prefix("refs/fork/npub1fork/fork")
.expect("delete");
assert_eq!(
mirror_repo
.refs_with_prefix("refs/fork/npub1fork/fork")
.expect("refs"),
Vec::<String>::new()
);
}
/// Runs `git` in `dir`, failing the test on a non-zero exit.
fn git_run(dir: &Path, args: &[&str]) -> std::process::Output {
let output = 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)
.output()
.expect("spawn git");
assert!(output.status.success(), "git {args:?} failed");
output
}
#[test]
fn find_git_repos_reports_the_outermost_repository() {
let root = tempfile::tempdir().expect("tempdir");
let repo_dir = root.path().join("project").join("sub");
std::fs::create_dir_all(&repo_dir).expect("mkdir");
git_run(&repo_dir, &["init", "-q"]);
let plain_dir = root.path().join("plain").join("deep");
std::fs::create_dir_all(&plain_dir).expect("mkdir");
let repos = find_git_repos(root.path());
assert_eq!(repos.len(), 1);
assert_eq!(repos[0].path, repo_dir.canonicalize().expect("canonical"));
assert!(repos[0].nip34.is_none());
}
#[test]
fn find_git_repos_skips_repositories_nested_in_repositories() {
let root = tempfile::tempdir().expect("tempdir");
let outer = root.path().join("outer");
std::fs::create_dir_all(&outer).expect("mkdir");
git_run(&outer, &["init", "-q"]);
let nested = outer.join("nested");
std::fs::create_dir_all(&nested).expect("mkdir");
git_run(&nested, &["init", "-q"]);
let repos = find_git_repos(root.path());
assert_eq!(repos.len(), 1);
assert_eq!(repos[0].path, outer.canonicalize().expect("canonical"));
}
#[test]
fn find_git_repos_ignores_a_repository_above_the_scan_root() {
let outer = tempfile::tempdir().expect("tempdir");
git_run(outer.path(), &["init", "-q"]);
let root = outer.path().join("scan");
std::fs::create_dir_all(&root).expect("mkdir");
assert!(find_git_repos(&root).is_empty());
}
/// Creates an empty bare server repository for push tests.
fn bare_server(base: &Path, owner: &str, name: &str) -> PathBuf {
let repo = base.join(owner).join(format!("{name}.git"));
std::fs::create_dir_all(repo.parent().expect("parent")).expect("mkdir");
git_run(
base,
&["init", "--bare", "-q", repo.to_str().expect("utf8 path")],
);
repo
}
#[test]
fn patch_commits_lists_every_patch_in_order() {
let patch = r#"From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
From: Alice <alice@example.com>
Date: Tue, 1 Aug 2023 10:00:00 +0200
Subject: [PATCH 1/2] first
body one
---
a.txt | 1 +
1 file changed, 1 insertion(+)
diff --git a/a.txt b/a.txt
@@ -1 +1,2 @@
a
+b
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
From: Bob <bob@example.com>
Date: Wed, 2 Aug 2023 11:30:00 +0000
Subject: [PATCH 2/2] second
body two
---
b.txt | 1 +
1 file changed, 1 insertion(+)
diff --git a/b.txt b/b.txt
@@ -1 +1,2 @@
x
+y
"#;
let commits = PatchParser::patch_commits(patch);
assert_eq!(commits.len(), 2);
assert_eq!(commits[0].id, "1111111111111111111111111111111111111111");
assert_eq!(commits[0].summary, "first");
assert_eq!(commits[0].author, "Alice");
assert_eq!(commits[0].time, 1690876800);
assert_eq!(commits[1].id, "2222222222222222222222222222222222222222");
assert_eq!(commits[1].summary, "second");
assert_eq!(commits[1].author, "Bob");
assert_eq!(commits[1].time, 1690975800);
}
#[test]
fn parses_real_format_patch_output() {
let (dir, repo) = fixture(&[
("src/main.rs", b"fn main() {\n println!(\"one\");\n}\n"),
("my file.txt", b"hello\n"),
("\u{8bf4}\u{660e}.md", "# \u{8bf4}\u{660e}\n".as_bytes()),
("img.png", b"\x89PNG\r\n\x1a\n\x00binary"),
]);
commit_all(&repo, "initial");
std::fs::write(
dir.path().join("src/main.rs"),
b"fn main() {\n println!(\"two\");\n println!(\"three\");\n}\n",
)
.expect("write");
std::fs::write(dir.path().join("my file.txt"), b"hello world\n").expect("write");
std::fs::write(
dir.path().join("\u{8bf4}\u{660e}.md"),
"# \u{8bf4}\u{660e}\nupdated\n",
)
.expect("write");
std::fs::remove_file(dir.path().join("img.png")).expect("remove");
std::fs::write(dir.path().join("new file.md"), b"# new\n").expect("write");
commit_all(&repo, "changes");
let output = git_run(dir.path(), &["format-patch", "-1", "--stdout"]);
let patch = String::from_utf8(output.stdout).expect("patch is utf-8");
let diff = PatchParser::patch_diffs(&patch).expect("parse real format-patch output");
let by_path = |path: &str| {
diff.files
.iter()
.find(|file| file.path == path)
.unwrap_or_else(|| panic!("missing file {path:?}"))
};
let file = by_path("my file.txt");
assert_eq!(file.status, DiffStatus::Modified);
assert_eq!(file.insertions, 1);
let file = by_path("\u{8bf4}\u{660e}.md");
assert_eq!(file.status, DiffStatus::Modified);
assert_eq!(file.insertions, 1);
let file = by_path("src/main.rs");
assert_eq!(file.status, DiffStatus::Modified);
assert_eq!(file.insertions, 2);
assert_eq!(file.deletions, 1);
assert!(!file.hunks.is_empty());
let file = by_path("new file.md");
assert_eq!(file.status, DiffStatus::Added);
assert_eq!(file.insertions, 1);
let file = by_path("img.png");
assert_eq!(file.status, DiffStatus::Deleted);
assert!(file.binary);
assert!(file.hunks.is_empty());
assert_eq!(file.insertions, 0);
assert_eq!(file.deletions, 0);
}
-36
View File
@@ -1,36 +0,0 @@
use std::path::PathBuf;
use crate::history::FileCommit;
pub struct WorktreeSnapshot {
pub entries: Vec<PathBuf>,
pub readme_path: Option<PathBuf>,
pub readme: Option<Vec<u8>>,
pub current_branch: Option<String>,
pub head_commit: Option<FileCommit>,
pub branches: Vec<String>,
pub tags: Vec<String>,
}
impl WorktreeSnapshot {
/// Creates a snapshot of the worktree contents and ref state.
pub(crate) fn new(
entries: Vec<PathBuf>,
readme_path: Option<PathBuf>,
readme: Option<Vec<u8>>,
current_branch: Option<String>,
head_commit: Option<FileCommit>,
branches: Vec<String>,
tags: Vec<String>,
) -> Self {
Self {
entries,
readme_path,
readme,
current_branch,
head_commit,
branches,
tags,
}
}
}

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