chore: refactor the backend (#17)
Reviewed-on: #17
This commit was merged in pull request #17.
This commit is contained in:
@@ -0,0 +1,174 @@
|
|||||||
|
# Rust coding guidelines
|
||||||
|
|
||||||
|
* Prioritize code correctness and clarity. Speed and efficiency are secondary priorities unless otherwise specified.
|
||||||
|
* Do not write organizational or comments that summarize the code. Comments should only be written in order to explain "why" the code is written in some way in the case there is a reason that is tricky / non-obvious.
|
||||||
|
* Prefer implementing functionality in existing files unless it is a new logical component. Avoid creating many small files.
|
||||||
|
* Avoid using functions that panic like `unwrap()`, instead use mechanisms like `?` to propagate errors.
|
||||||
|
* Be careful with operations like indexing which may panic if the indexes are out of bounds.
|
||||||
|
* Never silently discard errors with `let _ =` on fallible operations. Always handle errors appropriately:
|
||||||
|
- Propagate errors with `?` when the calling function should handle them
|
||||||
|
- Use `.log_err()` or similar when you need to ignore errors but want visibility
|
||||||
|
- Use explicit error handling with `match` or `if let Err(...)` when you need custom logic
|
||||||
|
- Example: avoid `let _ = client.request(...).await?;` - use `client.request(...).await?;` instead
|
||||||
|
* When implementing async operations that may fail, ensure errors propagate to the UI layer so users get meaningful feedback.
|
||||||
|
* Avoid creative additions unless explicitly requested
|
||||||
|
* Use full words for variable names (no abbreviations like "q" for "queue")
|
||||||
|
* Use variable shadowing to scope clones in async contexts for clarity, minimizing the lifetime of borrowed references.
|
||||||
|
Example:
|
||||||
|
```rust
|
||||||
|
executor.spawn({
|
||||||
|
let task_ran = task_ran.clone();
|
||||||
|
async move {
|
||||||
|
*task_ran.borrow_mut() = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
# Timers in tests
|
||||||
|
|
||||||
|
* In GPUI tests, prefer GPUI executor timers over `smol::Timer::after(...)` when you need timeouts, delays, or to drive `run_until_parked()`:
|
||||||
|
- Use `cx.background_executor().timer(duration).await` (or `cx.background_executor.timer(duration).await` in `TestAppContext`) so the work is scheduled on GPUI's dispatcher.
|
||||||
|
- Avoid `smol::Timer::after(...)` for test timeouts when you rely on `run_until_parked()`, because it may not be tracked by GPUI's scheduler and can lead to "nothing left to run" when pumping.
|
||||||
|
|
||||||
|
# GPUI
|
||||||
|
|
||||||
|
GPUI is a UI framework which also provides primitives for state and concurrency management.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Context types allow interaction with global state, windows, entities, and system services. They are typically passed to functions as the argument named `cx`. When a function takes callbacks they come after the `cx` parameter.
|
||||||
|
|
||||||
|
* `App` is the root context type, providing access to global state and read and update of entities.
|
||||||
|
* `Context<T>` is provided when updating an `Entity<T>`. This context dereferences into `App`, so functions which take `&App` can also take `&Context<T>`.
|
||||||
|
* `AsyncApp` and `AsyncWindowContext` are provided by `cx.spawn` and `cx.spawn_in`. These can be held across await points.
|
||||||
|
|
||||||
|
## `Window`
|
||||||
|
|
||||||
|
`Window` provides access to the state of an application window. It is passed to functions as an argument named `window` and comes before `cx` when present. It is used for managing focus, dispatching actions, directly drawing, getting user input state, etc.
|
||||||
|
|
||||||
|
## Entities
|
||||||
|
|
||||||
|
An `Entity<T>` is a handle to state of type `T`. With `thing: Entity<T>`:
|
||||||
|
|
||||||
|
* `thing.entity_id()` returns `EntityId`
|
||||||
|
* `thing.downgrade()` returns `WeakEntity<T>`
|
||||||
|
* `thing.read(cx: &App)` returns `&T`.
|
||||||
|
* `thing.read_with(cx, |thing: &T, cx: &App| ...)` returns the closure's return value.
|
||||||
|
* `thing.update(cx, |thing: &mut T, cx: &mut Context<T>| ...)` allows the closure to mutate the state, and provides a `Context<T>` for interacting with the entity. It returns the closure's return value.
|
||||||
|
* `thing.update_in(cx, |thing: &mut T, window: &mut Window, cx: &mut Context<T>| ...)` takes a `AsyncWindowContext` or `VisualTestContext`. It's the same as `update` while also providing the `Window`.
|
||||||
|
|
||||||
|
Within the closures, the inner `cx` provided to the closure must be used instead of the outer `cx` to avoid issues with multiple borrows.
|
||||||
|
|
||||||
|
Trying to update an entity while it's already being updated must be avoided as this will cause a panic.
|
||||||
|
|
||||||
|
`WeakEntity<T>` is a weak handle. It has `read_with`, `update`, and `update_in` methods that work the same, but always return an `anyhow::Result` so that they can fail if the entity no longer exists. This can be useful to avoid memory leaks - if entities have mutually recursive handles to each other they will never be dropped.
|
||||||
|
|
||||||
|
## Concurrency
|
||||||
|
|
||||||
|
All use of entities and UI rendering occurs on a single foreground thread.
|
||||||
|
|
||||||
|
`cx.spawn(async move |cx| ...)` runs an async closure on the foreground thread. Within the closure, `cx` is `&mut AsyncApp`.
|
||||||
|
|
||||||
|
When the outer cx is a `Context<T>`, the use of `spawn` instead looks like `cx.spawn(async move |this, cx| ...)`, where `this: WeakEntity<T>` and `cx: &mut AsyncApp`.
|
||||||
|
|
||||||
|
To do work on other threads, `cx.background_spawn(async move { ... })` is used. Often this background task is awaited on by a foreground task which uses the results to update state.
|
||||||
|
|
||||||
|
Both `cx.spawn` and `cx.background_spawn` return a `Task<R>`, which is a future that can be awaited upon. If this task is dropped, then its work is cancelled. To prevent this one of the following must be done:
|
||||||
|
|
||||||
|
* Awaiting the task in some other async context.
|
||||||
|
* Detaching the task via `task.detach()` or `task.detach_and_log_err(cx)`, allowing it to run indefinitely.
|
||||||
|
* Storing the task in a field, if the work should be halted when the struct is dropped.
|
||||||
|
|
||||||
|
A task which doesn't do anything but provide a value can be created with `Task::ready(value)`.
|
||||||
|
|
||||||
|
## Elements
|
||||||
|
|
||||||
|
The `Render` trait is used to render some state into an element tree that is laid out using flexbox layout. An `Entity<T>` where `T` implements `Render` is sometimes called a "view".
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```
|
||||||
|
struct TextWithBorder(SharedString);
|
||||||
|
|
||||||
|
impl Render for TextWithBorder {
|
||||||
|
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
|
div().border_1().child(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Since `impl IntoElement for SharedString` exists, it can be used as an argument to `child`. `SharedString` is used to avoid copying strings, and is either an `&'static str` or `Arc<str>`.
|
||||||
|
|
||||||
|
UI components that are constructed just to be turned into elements can instead implement the `RenderOnce` trait, which is similar to `Render`, but its `render` method takes ownership of `self` and receives `&mut App` instead of `&mut Context<Self>`. Types that implement this trait can use `#[derive(IntoElement)]` to use them directly as children.
|
||||||
|
|
||||||
|
The style methods on elements are similar to those used by Tailwind CSS.
|
||||||
|
|
||||||
|
If some attributes or children of an element tree are conditional, `.when(condition, |this| ...)` can be used to run the closure only when `condition` is true. Similarly, `.when_some(option, |this, value| ...)` runs the closure when the `Option` has a value.
|
||||||
|
|
||||||
|
## Input events
|
||||||
|
|
||||||
|
Input event handlers can be registered on an element via methods like `.on_click(|event, window, cx: &mut App| ...)`.
|
||||||
|
|
||||||
|
Often event handlers will want to update the entity that's in the current `Context<T>`. The `cx.listener` method provides this - its use looks like `.on_click(cx.listener(|this: &mut T, event, window, cx: &mut Context<T>| ...)`.
|
||||||
|
|
||||||
|
## Actions
|
||||||
|
|
||||||
|
Actions are dispatched via user keyboard interaction or in code via `window.dispatch_action(SomeAction.boxed_clone(), cx)` or `focus_handle.dispatch_action(&SomeAction, window, cx)`.
|
||||||
|
|
||||||
|
Actions with no data are defined with the `actions!(some_namespace, [SomeAction, AnotherAction])` macro call. Otherwise the `Action` derive macro is used. Doc comments on actions are displayed to the user.
|
||||||
|
|
||||||
|
Action handlers can be registered on an element via the event handler `.on_action(|action, window, cx| ...)`. Like other event handlers, this is often used with `cx.listener`.
|
||||||
|
|
||||||
|
## Notify
|
||||||
|
|
||||||
|
When a view's state has changed in a way that may affect its rendering, it should call `cx.notify()`. This will cause the view to be rerendered. It will also cause any observe callbacks registered for the entity with `cx.observe` to be called.
|
||||||
|
|
||||||
|
## Entity events
|
||||||
|
|
||||||
|
While updating an entity (`cx: Context<T>`), it can emit an event using `cx.emit(event)`. Entities register which events they can emit by declaring `impl EventEmitter<EventType> for EntityType {}`.
|
||||||
|
|
||||||
|
Other entities can then register a callback to handle these events by doing `cx.subscribe(other_entity, |this, other_entity, event, cx| ...)`. This will return a `Subscription` which deregisters the callback when dropped. Typically `cx.subscribe` happens when creating a new entity and the subscriptions are stored in a `_subscriptions: Vec<Subscription>` field.
|
||||||
|
|
||||||
|
# Pull request hygiene
|
||||||
|
|
||||||
|
When an agent opens or updates a pull request, it must:
|
||||||
|
|
||||||
|
- Use a clear, correctly capitalized, imperative PR title (for example, `Fix crash in project panel`).
|
||||||
|
- Avoid conventional commit prefixes in PR titles (`fix:`, `feat:`, `docs:`, etc.).
|
||||||
|
- Avoid trailing punctuation in PR titles.
|
||||||
|
- Optionally prefix the title with a crate name when one crate is the clear scope (for example, `git_ui: Add history view`).
|
||||||
|
- Include a `Release Notes:` section as the final section in the PR body.
|
||||||
|
- Use one bullet under `Release Notes:`:
|
||||||
|
- `- Added ...`, `- Fixed ...`, or `- Improved ...` for user-facing changes, or
|
||||||
|
- `- N/A` for docs-only and other non-user-facing changes.
|
||||||
|
- Format release notes exactly with a blank line after the heading, for example:
|
||||||
|
|
||||||
|
```
|
||||||
|
Release Notes:
|
||||||
|
|
||||||
|
- N/A
|
||||||
|
```
|
||||||
|
|
||||||
|
# Rules Hygiene
|
||||||
|
|
||||||
|
These `.rules` files are read by every agent session. Keep them high-signal.
|
||||||
|
|
||||||
|
## After any agentic session
|
||||||
|
If you discover a non-obvious pattern that would help future sessions, include a **"Suggested .rules additions"** heading in your PR description with the proposed text. Do **not** edit `.rules` inline during normal feature/fix work. Reviewers decide what gets merged.
|
||||||
|
|
||||||
|
## High bar for new rules
|
||||||
|
Editing or clarifying existing rules is always welcome. New rules must meet **all three** criteria:
|
||||||
|
1. **Non-obvious** — someone familiar with the codebase would still get it wrong without the rule.
|
||||||
|
2. **Repeatedly encountered** — it came up more than once (multiple hits in one session counts).
|
||||||
|
3. **Specific enough to act on** — a concrete instruction, not a vague principle.
|
||||||
|
|
||||||
|
Rules that apply to a single crate belong in that crate's own `.rules` file, not the repo root.
|
||||||
|
|
||||||
|
## What NOT to put in `.rules`
|
||||||
|
Avoid architectural descriptions of a crate (module layout, data flow, key types). These go stale fast and the agent can gather them by reading the code. Rules should be **traps to avoid**, not **maps to follow**.
|
||||||
|
|
||||||
|
## No drive-by additions
|
||||||
|
Rules emerge from validated patterns, not one-off observations. The workflow is:
|
||||||
|
1. Agent notes a pattern during a session.
|
||||||
|
2. Team validates the pattern in code review.
|
||||||
|
3. A dedicated commit adds the rule with context on *why* it exists.
|
||||||
Generated
+11
@@ -1690,6 +1690,15 @@ dependencies = [
|
|||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "diffy"
|
||||||
|
version = "0.5.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3e3dc2f773b6aaa63b1a7684b8589f670a8a0146a510b74d23a401c882364b49"
|
||||||
|
dependencies = [
|
||||||
|
"hashbrown 0.17.1",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "digest"
|
name = "digest"
|
||||||
version = "0.10.7"
|
version = "0.10.7"
|
||||||
@@ -7958,9 +7967,11 @@ name = "signed_git"
|
|||||||
version = "0.1.0-alpha"
|
version = "0.1.0-alpha"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
"diffy",
|
||||||
"gix",
|
"gix",
|
||||||
"gix-worktree",
|
"gix-worktree",
|
||||||
"gix-worktree-state",
|
"gix-worktree-state",
|
||||||
|
"ignore",
|
||||||
"nostr",
|
"nostr",
|
||||||
"signed_core",
|
"signed_core",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ pub use addr::{RepoAddr, identifier_from_name, repo_addr};
|
|||||||
pub use annotations::{COVER_NOTE_KIND, cover_note, labels_and_subject, subject_override};
|
pub use annotations::{COVER_NOTE_KIND, cover_note, labels_and_subject, subject_override};
|
||||||
pub use clone_url::{CloneTarget, parse_clone_url};
|
pub use clone_url::{CloneTarget, parse_clone_url};
|
||||||
pub use deletions::Deletions;
|
pub use deletions::Deletions;
|
||||||
pub use model::{Announcement, activity_subject, pull_request_patch, pull_request_patches};
|
pub use model::{
|
||||||
|
Announcement, activity_subject, branch_name_of, clone_urls_of, current_commit_of,
|
||||||
|
fork_candidates, latest_update, merge_base_of, pull_request_patch, pull_request_patches,
|
||||||
|
};
|
||||||
pub use state::{build_state, parse_state};
|
pub use state::{build_state, parse_state};
|
||||||
pub use status::{RepoStatus, references_root, resolve_status};
|
pub use status::{RepoStatus, references_root, resolve_status};
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ fn forward_series<'a>(root: &'a Event, patches: &[&'a Event]) -> Vec<&'a Event>
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The `c` tag of an event, the tip of the proposed branch, as hex.
|
/// The `c` tag of an event, the tip of the proposed branch, as hex.
|
||||||
fn current_commit_of(event: &Event) -> Option<String> {
|
pub fn current_commit_of(event: &Event) -> Option<String> {
|
||||||
event
|
event
|
||||||
.tags
|
.tags
|
||||||
.iter()
|
.iter()
|
||||||
@@ -190,6 +190,82 @@ fn current_commit_of(event: &Event) -> Option<String> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The `merge-base` tag of an event, the base commit a pull request diffs against.
|
||||||
|
pub fn merge_base_of(event: &Event) -> Option<String> {
|
||||||
|
event
|
||||||
|
.tags
|
||||||
|
.iter()
|
||||||
|
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
|
||||||
|
Ok(Nip34Tag::MergeBase(commit)) => Some(commit.to_string()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `clone` tag of an event, URLs the tip commit can be fetched from.
|
||||||
|
pub fn clone_urls_of(event: &Event) -> Option<Vec<Url>> {
|
||||||
|
event
|
||||||
|
.tags
|
||||||
|
.iter()
|
||||||
|
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
|
||||||
|
Ok(Nip34Tag::Clone(urls)) => Some(urls),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `branch-name` tag of an event, the proposed branch's name.
|
||||||
|
pub fn branch_name_of(event: &Event) -> Option<String> {
|
||||||
|
event
|
||||||
|
.tags
|
||||||
|
.iter()
|
||||||
|
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
|
||||||
|
Ok(Nip34Tag::BranchName(name)) => Some(name),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The newest `GitPullRequestUpdate` revising `root`, from the root's own author.
|
||||||
|
///
|
||||||
|
/// A pull request's tip is only mutable by its author, per NIP-34; updates
|
||||||
|
/// from anyone else are ignored even if they are newer.
|
||||||
|
pub fn latest_update<'a>(
|
||||||
|
events: impl Iterator<Item = &'a Event>,
|
||||||
|
root: &Event,
|
||||||
|
) -> Option<&'a Event> {
|
||||||
|
let root_hex = root.id.to_hex();
|
||||||
|
events
|
||||||
|
.filter(|e| e.kind == Kind::GitPullRequestUpdate)
|
||||||
|
.filter(|e| e.pubkey == root.pubkey)
|
||||||
|
.filter(|e| {
|
||||||
|
e.tags
|
||||||
|
.iter()
|
||||||
|
.any(|t| t.kind() == "E" && t.content() == Some(root_hex.as_str()))
|
||||||
|
})
|
||||||
|
.max_by_key(|e| e.created_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The announced forks of `base` a new pull request compare can be built from.
|
||||||
|
///
|
||||||
|
/// The user's own forks are listed first.
|
||||||
|
pub fn fork_candidates<'a>(
|
||||||
|
announcements: &'a [Announcement],
|
||||||
|
base: &RepoAddr,
|
||||||
|
base_euc: Option<&str>,
|
||||||
|
user: Option<PublicKey>,
|
||||||
|
) -> Vec<&'a Announcement> {
|
||||||
|
let (mut own, mut others) = (Vec::new(), Vec::new());
|
||||||
|
for announcement in announcements {
|
||||||
|
if announcement.clone.is_empty() || !announcement.is_fork_of(base, base_euc) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if Some(announcement.owner) == user {
|
||||||
|
own.push(announcement);
|
||||||
|
} else {
|
||||||
|
others.push(announcement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
own.into_iter().chain(others).collect()
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether `patch` produces `commit`, found via its `commit` or `r` tag.
|
/// Whether `patch` produces `commit`, found via its `commit` or `r` tag.
|
||||||
///
|
///
|
||||||
/// It lets clients find existing patches for a specific commit.
|
/// It lets clients find existing patches for a specific commit.
|
||||||
@@ -727,4 +803,221 @@ mod tests {
|
|||||||
vec!["patch-one", "patch-two"]
|
vec!["patch-one", "patch-two"]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const COMMIT_HEX: &str = "1111111111111111111111111111111111111111";
|
||||||
|
const OTHER_ROOT_HEX: &str = "2222222222222222222222222222222222222222";
|
||||||
|
|
||||||
|
/// Build a signed event of `kind` with the given tags and `created_at`.
|
||||||
|
fn signed_at(kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
|
||||||
|
EventBuilder::new(kind, "")
|
||||||
|
.tags(tags)
|
||||||
|
.custom_created_at(Timestamp::from(created_at))
|
||||||
|
.finalize(&keys())
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pr_root() -> Event {
|
||||||
|
signed_at(
|
||||||
|
Kind::GitPullRequest,
|
||||||
|
vec![
|
||||||
|
Tag::parse(["c", COMMIT_HEX]).expect("valid tag"),
|
||||||
|
Tag::parse(["branch-name", "feature/x"]).expect("valid tag"),
|
||||||
|
],
|
||||||
|
100,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reads_current_commit_and_branch_name() {
|
||||||
|
let pr = pr_root();
|
||||||
|
assert_eq!(current_commit_of(&pr).as_deref(), Some(COMMIT_HEX));
|
||||||
|
assert_eq!(branch_name_of(&pr).as_deref(), Some("feature/x"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn returns_none_without_pr_tags() {
|
||||||
|
let pr = signed_at(Kind::GitPullRequest, vec![], 100);
|
||||||
|
assert_eq!(current_commit_of(&pr), None);
|
||||||
|
assert_eq!(branch_name_of(&pr), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn latest_update_picks_newest_revision_of_the_root() {
|
||||||
|
let root = pr_root();
|
||||||
|
let root_hex = root.id.to_hex();
|
||||||
|
|
||||||
|
let revision = |created_at: u64| {
|
||||||
|
signed_at(
|
||||||
|
Kind::GitPullRequestUpdate,
|
||||||
|
vec![Tag::parse(["E", &root_hex]).expect("valid tag")],
|
||||||
|
created_at,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
// An update revising a different PR must be ignored even though it is newer.
|
||||||
|
let unrelated = signed_at(
|
||||||
|
Kind::GitPullRequestUpdate,
|
||||||
|
vec![Tag::parse(["E", OTHER_ROOT_HEX]).expect("valid tag")],
|
||||||
|
999,
|
||||||
|
);
|
||||||
|
|
||||||
|
let events = [unrelated, revision(200), root.clone(), revision(300)];
|
||||||
|
let latest = latest_update(events.iter(), &root).expect("an update");
|
||||||
|
|
||||||
|
assert_eq!(latest.created_at.as_secs(), 300);
|
||||||
|
assert_eq!(latest.kind, Kind::GitPullRequestUpdate);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn latest_update_ignores_other_authors() {
|
||||||
|
let root = pr_root();
|
||||||
|
let root_hex = root.id.to_hex();
|
||||||
|
let other = Keys::new(
|
||||||
|
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000002")
|
||||||
|
.expect("valid secret key"),
|
||||||
|
);
|
||||||
|
let stranger = EventBuilder::new(Kind::GitPullRequestUpdate, "")
|
||||||
|
.tags([Tag::parse(["E", &root_hex]).expect("valid tag")])
|
||||||
|
.custom_created_at(Timestamp::from(999))
|
||||||
|
.finalize(&other)
|
||||||
|
.expect("signed event");
|
||||||
|
|
||||||
|
// The tip of a PR is only mutable by its author.
|
||||||
|
// A newer update from anyone else must not win.
|
||||||
|
assert!(latest_update([&stranger, &root].into_iter(), &root).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn latest_update_ignores_roots_without_revisions() {
|
||||||
|
let root = pr_root();
|
||||||
|
assert!(latest_update([&root].into_iter(), &root).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
const OWNER_KEYS: [&str; 3] = [
|
||||||
|
"0000000000000000000000000000000000000000000000000000000000000001",
|
||||||
|
"0000000000000000000000000000000000000000000000000000000000000002",
|
||||||
|
"0000000000000000000000000000000000000000000000000000000000000003",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Build a signed kind-30617 event for `owner` with the given tags.
|
||||||
|
fn owned_announcement_event(owner: &str, tags: &[&[&str]]) -> Event {
|
||||||
|
let keys = Keys::new(SecretKey::from_hex(owner).expect("valid secret key"));
|
||||||
|
let tags: Vec<Tag> = tags
|
||||||
|
.iter()
|
||||||
|
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
|
||||||
|
.collect();
|
||||||
|
EventBuilder::new(Kind::GitRepoAnnouncement, "")
|
||||||
|
.tags(tags)
|
||||||
|
.finalize(&keys)
|
||||||
|
.expect("signed event")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned_announcements(owner_ix: usize, tags: &[&[&str]]) -> Vec<Announcement> {
|
||||||
|
vec![
|
||||||
|
Announcement::from_event(&owned_announcement_event(OWNER_KEYS[owner_ix], tags))
|
||||||
|
.expect("parses"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fork_candidates_orders_own_forks_first() {
|
||||||
|
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
||||||
|
let clone = "https://grasp.example/npub1x/my-fork.git";
|
||||||
|
|
||||||
|
let base_addr = crate::repo_addr(
|
||||||
|
PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey"),
|
||||||
|
"upstream",
|
||||||
|
);
|
||||||
|
// Newest first, as RepoListStore keeps them.
|
||||||
|
// Unrelated repo, the user's fork with the shared EUC, another fork with a `u` tag.
|
||||||
|
let all = vec![
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "other-project"],
|
||||||
|
&["r", "bb231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(
|
||||||
|
1,
|
||||||
|
&[&["d", "my-fork"], &["r", euc, "euc"], &["clone", clone]],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "their-fork"],
|
||||||
|
&["u", &base_addr.to_string()],
|
||||||
|
&["clone", clone],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let user = PublicKey::from_hex(OWNER_KEYS[1]).expect("pubkey");
|
||||||
|
let forks = fork_candidates(&all, &base_addr, Some(euc), Some(user));
|
||||||
|
|
||||||
|
// The user's fork comes first, then the other author's.
|
||||||
|
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
|
||||||
|
assert_eq!(ids, vec!["my-fork", "their-fork"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fork_candidates_excludes_base_unrelated_and_unfetchable() {
|
||||||
|
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
||||||
|
let base_owner = PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey");
|
||||||
|
let base_addr = crate::repo_addr(base_owner, "upstream");
|
||||||
|
|
||||||
|
let mut all = vec![
|
||||||
|
owned_announcements(0, &[&["d", "upstream"], &["r", euc, "euc"]])
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(1, &[&["d", "no-clone-fork"], &["r", euc, "euc"]])
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "other"],
|
||||||
|
&["r", "cc231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "mirror"],
|
||||||
|
&["r", euc, "euc"],
|
||||||
|
&["clone", "https://grasp.example/x/mirror.git"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let forks = fork_candidates(&all, &base_addr, Some(euc), Some(base_owner));
|
||||||
|
assert_eq!(forks.len(), 1);
|
||||||
|
assert_eq!(forks[0].id, "mirror");
|
||||||
|
|
||||||
|
// Without a base EUC only `u`-tag forks match.
|
||||||
|
all.push(
|
||||||
|
owned_announcements(
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&["d", "u-fork"],
|
||||||
|
&["u", &base_addr.to_string()],
|
||||||
|
&["clone", "https://grasp.example/x/u-fork.git"],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.pop()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
let forks = fork_candidates(&all, &base_addr, None, Some(base_owner));
|
||||||
|
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
|
||||||
|
assert_eq!(ids, vec!["u-fork"]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ gix = { workspace = true, features = ["revision", "blob-diff"] }
|
|||||||
gix-worktree = "0.56"
|
gix-worktree = "0.56"
|
||||||
gix-worktree-state = "0.34"
|
gix-worktree-state = "0.34"
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
|
diffy = "0.5"
|
||||||
|
ignore = "0.4"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use signed_core::{Announcement, RepoAddr};
|
||||||
|
|
||||||
|
use crate::remote::{clone_repo, fetch_all};
|
||||||
|
|
||||||
|
/// On-disk cache of cloned repositories, keyed by owner pubkey / repo id.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct GitCache {
|
||||||
|
root: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GitCache {
|
||||||
|
pub fn new(root: PathBuf) -> Self {
|
||||||
|
Self { root }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The root directory holding the mirror clones.
|
||||||
|
pub fn root(&self) -> &Path {
|
||||||
|
&self.root
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Local path of the clone for a repository.
|
||||||
|
pub fn repo_path(&self, addr: &RepoAddr) -> PathBuf {
|
||||||
|
self.root
|
||||||
|
.join(addr.public_key.to_hex())
|
||||||
|
.join(sanitize_path_component(&addr.identifier))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open the existing clone, fetching it first.
|
||||||
|
pub fn ensure_clone<U: AsRef<str>>(
|
||||||
|
&self,
|
||||||
|
addr: &RepoAddr,
|
||||||
|
clone_urls: &[U],
|
||||||
|
) -> Result<gix::Repository> {
|
||||||
|
let path = self.repo_path(addr);
|
||||||
|
|
||||||
|
if let Some(repo) = self.open(addr)? {
|
||||||
|
fetch_all(&repo).ok();
|
||||||
|
return Ok(repo);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
std::fs::create_dir_all(parent)
|
||||||
|
.with_context(|| format!("failed to create {}", parent.display()))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
clone_repo(clone_urls, &path)?;
|
||||||
|
self.open(addr)?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("clone finished but the repository cannot be opened"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map an untrusted repository id or display name to a safe single path component.
|
||||||
|
///
|
||||||
|
/// Everything outside `[A-Za-z0-9._-]` becomes `_`.
|
||||||
|
/// An id that maps to exactly `.` or `..` becomes `_`.
|
||||||
|
pub fn sanitize_path_component(id: &str) -> String {
|
||||||
|
let sanitized: String = id
|
||||||
|
.chars()
|
||||||
|
.map(|c| {
|
||||||
|
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
|
||||||
|
c
|
||||||
|
} else {
|
||||||
|
'_'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if sanitized == "." || sanitized == ".." {
|
||||||
|
return "_".to_owned();
|
||||||
|
}
|
||||||
|
|
||||||
|
sanitized
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The refs namespace of a fork's import in the target mirror.
|
||||||
|
pub fn fork_namespace(announcement: &Announcement) -> String {
|
||||||
|
format!(
|
||||||
|
"{}/{}",
|
||||||
|
announcement.owner.to_hex(),
|
||||||
|
sanitize_path_component(&announcement.id)
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use gix::diff::blob::unified_diff::{ConsumeHunk, DiffLineKind as GixLineKind, HunkHeader};
|
||||||
|
|
||||||
|
/// The kind of a [`DiffLine`].
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum DiffLineKind {
|
||||||
|
/// An unchanged context line, present on both sides.
|
||||||
|
Context,
|
||||||
|
/// A line added by the commit.
|
||||||
|
Addition,
|
||||||
|
/// A line removed by the commit.
|
||||||
|
Deletion,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One line of a file diff.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DiffLine {
|
||||||
|
pub kind: DiffLineKind,
|
||||||
|
/// 1-based line number in the old version, if the line exists there.
|
||||||
|
pub old: Option<u32>,
|
||||||
|
/// 1-based line number in the new version, if the line exists there.
|
||||||
|
pub new: Option<u32>,
|
||||||
|
/// Line content without the trailing newline.
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A hunk of a file diff, like `@@ -a,b +c,d @@`.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DiffHunk {
|
||||||
|
/// 1-based start line in the old version.
|
||||||
|
pub old_start: u32,
|
||||||
|
/// Number of old lines covered by the hunk.
|
||||||
|
pub old_lines: u32,
|
||||||
|
/// 1-based start line in the new version.
|
||||||
|
pub new_start: u32,
|
||||||
|
/// Number of new lines covered by the hunk.
|
||||||
|
pub new_lines: u32,
|
||||||
|
pub lines: Vec<DiffLine>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a file changed in a commit.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum DiffStatus {
|
||||||
|
Added,
|
||||||
|
Modified,
|
||||||
|
Deleted,
|
||||||
|
Renamed,
|
||||||
|
Copied,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The diff of one file in a commit.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct FileDiff {
|
||||||
|
/// Path of the file relative to the repo root.
|
||||||
|
///
|
||||||
|
/// For renames and copies, this is the destination path.
|
||||||
|
pub path: String,
|
||||||
|
/// Previous path, for renames and copies.
|
||||||
|
pub old_path: Option<String>,
|
||||||
|
pub status: DiffStatus,
|
||||||
|
/// Number of added lines, 0 for binary files.
|
||||||
|
pub insertions: usize,
|
||||||
|
/// Number of removed lines, 0 for binary files.
|
||||||
|
pub deletions: usize,
|
||||||
|
/// True if either version is binary, then `hunks` is empty.
|
||||||
|
pub binary: bool,
|
||||||
|
pub hunks: Vec<DiffHunk>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The changes of one commit.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct CommitDiff {
|
||||||
|
pub files: Vec<FileDiff>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The changes of the commit `id`, short or full, in the repository at `workdir`.
|
||||||
|
///
|
||||||
|
/// Compared against its first parent, the empty tree for the root commit.
|
||||||
|
pub fn worktree_commit_diff(workdir: &Path, id: &str) -> Result<CommitDiff> {
|
||||||
|
commit_diff(&gix::open(workdir)?, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit_diff(repo: &gix::Repository, id: &str) -> Result<CommitDiff> {
|
||||||
|
let commit_id = repo.rev_parse_single(id.as_bytes())?;
|
||||||
|
let commit = commit_id.object()?.into_commit();
|
||||||
|
let new_tree = commit.tree()?;
|
||||||
|
let old_tree = match commit.parent_ids().next() {
|
||||||
|
Some(parent) => Some(parent.object()?.into_commit().tree()?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
tree_diff(repo, old_tree.as_ref(), &new_tree)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The changes between two commits, `base`..`tip`, like `git diff base tip`.
|
||||||
|
///
|
||||||
|
/// Directories and submodules are skipped, files are sorted by path.
|
||||||
|
pub fn worktree_commit_range_diff(workdir: &Path, base: &str, tip: &str) -> Result<CommitDiff> {
|
||||||
|
let repo = gix::open(workdir)?;
|
||||||
|
let base_tree = repo
|
||||||
|
.rev_parse_single(base.as_bytes())?
|
||||||
|
.object()?
|
||||||
|
.into_commit()
|
||||||
|
.tree()?;
|
||||||
|
let tip_tree = repo
|
||||||
|
.rev_parse_single(tip.as_bytes())?
|
||||||
|
.object()?
|
||||||
|
.into_commit()
|
||||||
|
.tree()?;
|
||||||
|
tree_diff(&repo, Some(&base_tree), &tip_tree)
|
||||||
|
}
|
||||||
|
/// The changes between two trees. Used by both [`commit_diff`] and [`worktree_commit_range_diff`].
|
||||||
|
fn tree_diff(
|
||||||
|
repo: &gix::Repository,
|
||||||
|
old_tree: Option<&gix::Tree<'_>>,
|
||||||
|
new_tree: &gix::Tree<'_>,
|
||||||
|
) -> Result<CommitDiff> {
|
||||||
|
use gix::diff::blob::platform::prepare_diff::Operation;
|
||||||
|
use gix::object::tree::diff::Change;
|
||||||
|
use gix::objs::tree::EntryKind;
|
||||||
|
|
||||||
|
let changes = repo.diff_tree_to_tree(old_tree, Some(new_tree), None)?;
|
||||||
|
|
||||||
|
let mut cache = repo.diff_resource_cache_for_tree_diff()?;
|
||||||
|
let mut files = Vec::new();
|
||||||
|
|
||||||
|
for change in changes {
|
||||||
|
let attached = Change::from_change_ref(change.to_ref(), repo, repo);
|
||||||
|
|
||||||
|
// Skip directory trees and submodule gitlinks, only files are listed.
|
||||||
|
let (path, old_path, status) = match attached {
|
||||||
|
Change::Addition {
|
||||||
|
location,
|
||||||
|
entry_mode,
|
||||||
|
..
|
||||||
|
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) => {
|
||||||
|
(location.to_owned(), None, DiffStatus::Added)
|
||||||
|
}
|
||||||
|
Change::Deletion {
|
||||||
|
location,
|
||||||
|
entry_mode,
|
||||||
|
..
|
||||||
|
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) => {
|
||||||
|
(location.to_owned(), None, DiffStatus::Deleted)
|
||||||
|
}
|
||||||
|
Change::Modification {
|
||||||
|
location,
|
||||||
|
previous_entry_mode,
|
||||||
|
entry_mode,
|
||||||
|
..
|
||||||
|
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit)
|
||||||
|
&& !matches!(
|
||||||
|
previous_entry_mode.kind(),
|
||||||
|
EntryKind::Tree | EntryKind::Commit
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
(location.to_owned(), None, DiffStatus::Modified)
|
||||||
|
}
|
||||||
|
Change::Rewrite {
|
||||||
|
location,
|
||||||
|
source_location,
|
||||||
|
source_entry_mode,
|
||||||
|
entry_mode,
|
||||||
|
copy,
|
||||||
|
..
|
||||||
|
} if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit)
|
||||||
|
&& !matches!(
|
||||||
|
source_entry_mode.kind(),
|
||||||
|
EntryKind::Tree | EntryKind::Commit
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
let status = if copy {
|
||||||
|
DiffStatus::Copied
|
||||||
|
} else {
|
||||||
|
DiffStatus::Renamed
|
||||||
|
};
|
||||||
|
(
|
||||||
|
location.to_owned(),
|
||||||
|
Some(source_location.to_owned()),
|
||||||
|
status,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Always diff with the built-in algorithm.
|
||||||
|
// External diff drivers would shell out, out of scope for a read-only viewer.
|
||||||
|
let platform = attached.diff(&mut cache)?;
|
||||||
|
platform
|
||||||
|
.resource_cache
|
||||||
|
.options
|
||||||
|
.skip_internal_diff_if_external_is_configured = true;
|
||||||
|
let outcome = platform.resource_cache.prepare_diff()?;
|
||||||
|
|
||||||
|
let (binary, hunks, insertions, deletions) = match outcome.operation {
|
||||||
|
Operation::InternalDiff { algorithm } => {
|
||||||
|
let input = outcome.interned_input();
|
||||||
|
let diff = gix::diff::blob::diff_with_slider_heuristics(algorithm, &input);
|
||||||
|
|
||||||
|
let mut hunks = Vec::new();
|
||||||
|
let mut insertions = 0usize;
|
||||||
|
let mut deletions = 0usize;
|
||||||
|
let collector = HunkCollector {
|
||||||
|
hunks: &mut hunks,
|
||||||
|
insertions: &mut insertions,
|
||||||
|
deletions: &mut deletions,
|
||||||
|
};
|
||||||
|
gix::diff::blob::UnifiedDiff::new(&diff, &input, collector, Default::default())
|
||||||
|
.consume()?;
|
||||||
|
(false, hunks, insertions, deletions)
|
||||||
|
}
|
||||||
|
Operation::SourceOrDestinationIsBinary => (true, Vec::new(), 0, 0),
|
||||||
|
Operation::ExternalCommand { .. } => unreachable!("external diff drivers are disabled"),
|
||||||
|
};
|
||||||
|
|
||||||
|
files.push(FileDiff {
|
||||||
|
path: String::from_utf8_lossy(&path).into_owned(),
|
||||||
|
old_path: old_path.map(|p| String::from_utf8_lossy(&p).into_owned()),
|
||||||
|
status,
|
||||||
|
insertions,
|
||||||
|
deletions,
|
||||||
|
binary,
|
||||||
|
hunks,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||||
|
|
||||||
|
Ok(CommitDiff { files })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collects the hunks of one blob diff while tracking per-line numbers.
|
||||||
|
struct HunkCollector<'a> {
|
||||||
|
hunks: &'a mut Vec<DiffHunk>,
|
||||||
|
insertions: &'a mut usize,
|
||||||
|
deletions: &'a mut usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConsumeHunk for HunkCollector<'_> {
|
||||||
|
type Out = ();
|
||||||
|
|
||||||
|
fn consume_hunk(
|
||||||
|
&mut self,
|
||||||
|
header: HunkHeader,
|
||||||
|
lines: &[(GixLineKind, &[u8])],
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let mut old_ln = header.before_hunk_start;
|
||||||
|
let mut new_ln = header.after_hunk_start;
|
||||||
|
let mut out = Vec::with_capacity(lines.len());
|
||||||
|
|
||||||
|
for (kind, content) in lines {
|
||||||
|
let text = String::from_utf8_lossy(content).into_owned();
|
||||||
|
let line = match kind {
|
||||||
|
GixLineKind::Context => {
|
||||||
|
let line = DiffLine {
|
||||||
|
kind: DiffLineKind::Context,
|
||||||
|
old: Some(old_ln),
|
||||||
|
new: Some(new_ln),
|
||||||
|
text,
|
||||||
|
};
|
||||||
|
old_ln += 1;
|
||||||
|
new_ln += 1;
|
||||||
|
line
|
||||||
|
}
|
||||||
|
GixLineKind::Remove => {
|
||||||
|
*self.deletions += 1;
|
||||||
|
let line = DiffLine {
|
||||||
|
kind: DiffLineKind::Deletion,
|
||||||
|
old: Some(old_ln),
|
||||||
|
new: None,
|
||||||
|
text,
|
||||||
|
};
|
||||||
|
old_ln += 1;
|
||||||
|
line
|
||||||
|
}
|
||||||
|
GixLineKind::Add => {
|
||||||
|
*self.insertions += 1;
|
||||||
|
let line = DiffLine {
|
||||||
|
kind: DiffLineKind::Addition,
|
||||||
|
old: None,
|
||||||
|
new: Some(new_ln),
|
||||||
|
text,
|
||||||
|
};
|
||||||
|
new_ln += 1;
|
||||||
|
line
|
||||||
|
}
|
||||||
|
};
|
||||||
|
out.push(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.hunks.push(DiffHunk {
|
||||||
|
old_start: header.before_hunk_start,
|
||||||
|
old_lines: header.before_hunk_len,
|
||||||
|
new_start: header.after_hunk_start,
|
||||||
|
new_lines: header.after_hunk_len,
|
||||||
|
lines: out,
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish(self) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
|
/// In-memory object cache for history walks, see [`open_with_cache`].
|
||||||
|
///
|
||||||
|
/// Without one, a walk re-decodes the same commit objects from the object database.
|
||||||
|
/// Sized generously: a walk can cover a large portion of the repository's history.
|
||||||
|
const OBJECT_CACHE_BYTES: usize = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// Metadata of a commit, as shown in the repository browser's file header.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct FileCommit {
|
||||||
|
/// Shortened commit id, 7+ hex chars, disambiguated if needed.
|
||||||
|
pub id: String,
|
||||||
|
/// First line of the commit message.
|
||||||
|
pub summary: String,
|
||||||
|
/// Rest of the commit message after the title.
|
||||||
|
///
|
||||||
|
/// `None` for single-line commit messages.
|
||||||
|
pub description: Option<String>,
|
||||||
|
/// Author name.
|
||||||
|
pub author: String,
|
||||||
|
/// Author time, seconds since the Unix epoch.
|
||||||
|
pub time: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open the repository at `workdir` with an in-memory object cache.
|
||||||
|
///
|
||||||
|
/// Only history walks use it, they re-decode the same commit objects repeatedly.
|
||||||
|
/// Single-object reads open the repository plain.
|
||||||
|
pub(crate) fn open_with_cache(workdir: &Path) -> Result<gix::Repository> {
|
||||||
|
let mut repo = gix::open(workdir)?;
|
||||||
|
repo.object_cache_size_if_unset(OBJECT_CACHE_BYTES);
|
||||||
|
Ok(repo)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [`FileCommit`] from a commit, with author, message title, body and shortened id.
|
||||||
|
///
|
||||||
|
/// The diff panel fetches the full commit on demand.
|
||||||
|
fn file_commit(commit: &gix::Commit<'_>) -> Result<FileCommit> {
|
||||||
|
file_commit_with_description(commit, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [`FileCommit`] without the message body, for history lists that never display it.
|
||||||
|
///
|
||||||
|
/// Skipping the body saves an allocation per listed commit.
|
||||||
|
fn file_commit_summary(commit: &gix::Commit<'_>) -> Result<FileCommit> {
|
||||||
|
file_commit_with_description(commit, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`file_commit`] and [`file_commit_summary`], `include_description` picks the body.
|
||||||
|
fn file_commit_with_description(
|
||||||
|
commit: &gix::Commit<'_>,
|
||||||
|
include_description: bool,
|
||||||
|
) -> Result<FileCommit> {
|
||||||
|
let author = commit.author()?;
|
||||||
|
let message = commit.message()?;
|
||||||
|
|
||||||
|
Ok(FileCommit {
|
||||||
|
id: commit.id().shorten_or_id().to_string(),
|
||||||
|
summary: String::from_utf8_lossy(message.title).trim().to_string(),
|
||||||
|
description: if include_description {
|
||||||
|
message
|
||||||
|
.body
|
||||||
|
.map(|body| String::from_utf8_lossy(body).trim().to_string())
|
||||||
|
.filter(|body| !body.is_empty())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
|
author: String::from_utf8_lossy(author.name).trim().to_string(),
|
||||||
|
time: author.time()?.seconds,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find the most recent commit that changed `rel`, a path relative to the worktree.
|
||||||
|
///
|
||||||
|
/// `Ok(None)` when no commit touched the file, e.g. an untracked file.
|
||||||
|
pub fn last_commit(repo: &gix::Repository, rel: &Path) -> Result<Option<FileCommit>> {
|
||||||
|
let rel = rel.to_path_buf();
|
||||||
|
Ok(last_commits(repo, std::slice::from_ref(&rel))?
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.map(|(_, commit)| commit))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Newest commit touching each of `rels`, like `git log -1 -- <rel>` per path.
|
||||||
|
/// `rels` are paths relative to the worktree.
|
||||||
|
///
|
||||||
|
/// Paths without any commit, like untracked files, are absent from the result.
|
||||||
|
pub fn worktree_last_commits(
|
||||||
|
workdir: &Path,
|
||||||
|
rels: &[PathBuf],
|
||||||
|
) -> Result<Vec<(PathBuf, FileCommit)>> {
|
||||||
|
last_commits(&open_with_cache(workdir)?, rels)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The walk behind [`last_commit`] and [`worktree_last_commits`].
|
||||||
|
///
|
||||||
|
/// Stops as soon as every pending path has its commit.
|
||||||
|
fn last_commits(repo: &gix::Repository, rels: &[PathBuf]) -> Result<Vec<(PathBuf, FileCommit)>> {
|
||||||
|
use gix::traverse::commit::simple::CommitTimeOrder;
|
||||||
|
|
||||||
|
let Some(head) = repo.head_id().ok() else {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
};
|
||||||
|
|
||||||
|
// De-duplicate while preserving order.
|
||||||
|
let mut pending: Vec<PathBuf> = Vec::with_capacity(rels.len());
|
||||||
|
let mut seen: HashSet<&Path> = HashSet::with_capacity(rels.len());
|
||||||
|
|
||||||
|
for rel in rels {
|
||||||
|
if seen.insert(rel.as_path()) {
|
||||||
|
pending.push(rel.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let walk = repo
|
||||||
|
.rev_walk([head])
|
||||||
|
.sorting(gix::revision::walk::Sorting::ByCommitTime(
|
||||||
|
CommitTimeOrder::NewestFirst,
|
||||||
|
));
|
||||||
|
|
||||||
|
let mut found = Vec::new();
|
||||||
|
for info in walk.all()? {
|
||||||
|
if pending.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let info = info?;
|
||||||
|
let commit = info.object()?;
|
||||||
|
let tree = commit.tree()?;
|
||||||
|
let parent_tree = match info.parent_ids().next() {
|
||||||
|
Some(parent) => Some(parent.object()?.into_commit().tree()?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Compare each unresolved path against this commit and its first parent.
|
||||||
|
// Resolved paths leave the pending set.
|
||||||
|
let mut ix = 0;
|
||||||
|
while ix < pending.len() {
|
||||||
|
let rel = &pending[ix];
|
||||||
|
let blob = tree.lookup_entry_by_path(rel)?;
|
||||||
|
let parent_blob = match &parent_tree {
|
||||||
|
Some(tree) => tree.lookup_entry_by_path(rel)?,
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if blob.map(|entry| entry.id().detach()) != parent_blob.map(|entry| entry.id().detach())
|
||||||
|
{
|
||||||
|
found.push((rel.clone(), file_commit(&commit)?));
|
||||||
|
pending.swap_remove(ix);
|
||||||
|
} else {
|
||||||
|
ix += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(found)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cap on [`CommitList::commits`]. The virtual list renders a window at a time,
|
||||||
|
/// the tab badge shows the real count.
|
||||||
|
///
|
||||||
|
/// A huge history is never fully materialized in memory.
|
||||||
|
pub const MAX_LISTED_COMMITS: usize = 20_000;
|
||||||
|
|
||||||
|
/// Commits reachable from `HEAD`, newest first, possibly capped.
|
||||||
|
pub struct CommitList {
|
||||||
|
/// Number of commits reachable from HEAD.
|
||||||
|
pub total: usize,
|
||||||
|
/// Newest commits, capped at [`MAX_LISTED_COMMITS`].
|
||||||
|
pub commits: Vec<FileCommit>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All commits reachable from `HEAD`, newest first, with author and summary.
|
||||||
|
///
|
||||||
|
/// Returns an empty list for a repository without any commits yet.
|
||||||
|
pub fn all_commits(repo: &gix::Repository) -> Result<CommitList> {
|
||||||
|
use gix::traverse::commit::simple::CommitTimeOrder;
|
||||||
|
|
||||||
|
let Some(head) = repo.head_id().ok() else {
|
||||||
|
return Ok(CommitList {
|
||||||
|
total: 0,
|
||||||
|
commits: Vec::new(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
let walk = repo
|
||||||
|
.rev_walk([head])
|
||||||
|
.sorting(gix::revision::walk::Sorting::ByCommitTime(
|
||||||
|
CommitTimeOrder::NewestFirst,
|
||||||
|
));
|
||||||
|
|
||||||
|
let mut commits = Vec::new();
|
||||||
|
let mut total = 0;
|
||||||
|
|
||||||
|
for info in walk.all()? {
|
||||||
|
let info = info?;
|
||||||
|
total += 1;
|
||||||
|
if commits.len() < MAX_LISTED_COMMITS {
|
||||||
|
commits.push(file_commit_summary(&info.object()?)?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(CommitList { total, commits })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`all_commits`], but opens the repository at `workdir` first.
|
||||||
|
///
|
||||||
|
/// For non-bare clones the clone root is the worktree.
|
||||||
|
pub fn worktree_all_commits(workdir: &Path) -> Result<CommitList> {
|
||||||
|
all_commits(&open_with_cache(workdir)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commits in the range `base`..`tip`, newest first, like `git log base..tip`.
|
||||||
|
pub fn worktree_commit_range_commits(
|
||||||
|
workdir: &Path,
|
||||||
|
base: &str,
|
||||||
|
tip: &str,
|
||||||
|
) -> Result<Vec<FileCommit>> {
|
||||||
|
use gix::traverse::commit::simple::CommitTimeOrder;
|
||||||
|
|
||||||
|
let repo = open_with_cache(workdir)?;
|
||||||
|
let base_id = repo.rev_parse_single(base.as_bytes())?;
|
||||||
|
let tip_id = repo.rev_parse_single(tip.as_bytes())?;
|
||||||
|
let walk = repo
|
||||||
|
.rev_walk([tip_id])
|
||||||
|
.sorting(gix::revision::walk::Sorting::ByCommitTime(
|
||||||
|
CommitTimeOrder::NewestFirst,
|
||||||
|
))
|
||||||
|
.with_hidden([base_id]);
|
||||||
|
|
||||||
|
let mut commits = Vec::new();
|
||||||
|
|
||||||
|
for info in walk.all()? {
|
||||||
|
let info = info?;
|
||||||
|
commits.push(file_commit_summary(&info.object()?)?);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(commits)
|
||||||
|
}
|
||||||
|
/// The commit HEAD points to, like `git log -1`.
|
||||||
|
///
|
||||||
|
/// `Ok(None)` for a repository without commits yet, an unborn HEAD.
|
||||||
|
pub fn head_commit(repo: &gix::Repository) -> Result<Option<FileCommit>> {
|
||||||
|
let Some(head) = repo.head_id().ok() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let commit = head.object()?.into_commit();
|
||||||
|
Ok(Some(file_commit(&commit)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full metadata of the commit `id`, short or full, in the repository at `workdir`.
|
||||||
|
/// Like [`head_commit`] for an arbitrary commit.
|
||||||
|
///
|
||||||
|
/// `Ok(None)` when the id cannot be resolved.
|
||||||
|
pub fn worktree_commit(workdir: &Path, id: &str) -> Result<Option<FileCommit>> {
|
||||||
|
let repo = gix::open(workdir)?;
|
||||||
|
match repo.rev_parse_single(id.as_bytes()) {
|
||||||
|
Ok(commit_id) => {
|
||||||
|
let commit = commit_id.object()?.into_commit();
|
||||||
|
Ok(Some(file_commit(&commit)?))
|
||||||
|
}
|
||||||
|
Err(_) => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
-4103
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,323 @@
|
|||||||
|
use std::io::Write;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use diffy::patch_set::{FileOperation, FilePatch, ParseOptions, PatchSet};
|
||||||
|
use diffy::{Hunk, Line};
|
||||||
|
|
||||||
|
use crate::diff::{CommitDiff, DiffHunk, DiffLine, DiffLineKind, DiffStatus, FileDiff};
|
||||||
|
use crate::history::FileCommit;
|
||||||
|
|
||||||
|
/// Apply a `git format-patch` patch or series with `git am`,
|
||||||
|
/// uses the git CLI because it handles the mbox format natively.
|
||||||
|
///
|
||||||
|
/// TODO: 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() {
|
||||||
|
bail!("git am failed: {}", String::from_utf8_lossy(&output.stderr));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `git format-patch` mbox series of `base..tip`, like `git format-patch --stdout`.
|
||||||
|
/// Fails when the range has no commits.
|
||||||
|
///
|
||||||
|
/// The mbox is returned untrimmed. Trailing newlines are part of the format.
|
||||||
|
pub fn format_patch_between(repo_path: &Path, base: &str, tip: &str) -> Result<String> {
|
||||||
|
let output = Command::new("git")
|
||||||
|
.arg("-C")
|
||||||
|
.arg(repo_path)
|
||||||
|
.args(["format-patch", "--stdout", &format!("{base}..{tip}")])
|
||||||
|
.env("GIT_TERMINAL_PROMPT", "0")
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.output()
|
||||||
|
.context("failed to spawn `git format-patch`")?;
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
bail!(
|
||||||
|
"git format-patch failed: {}",
|
||||||
|
String::from_utf8_lossy(&output.stderr).trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let patch = String::from_utf8_lossy(&output.stdout).into_owned();
|
||||||
|
|
||||||
|
if patch.trim().is_empty() {
|
||||||
|
bail!("no commits between {base} and {tip}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(patch)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Split a `git format-patch` series into its individual patches, mbox messages.
|
||||||
|
///
|
||||||
|
/// A single patch yields one element.
|
||||||
|
/// A malformed input yields one element covering it.
|
||||||
|
pub fn split_patch_series(patch: &str) -> Vec<&str> {
|
||||||
|
let mut starts = vec![0usize];
|
||||||
|
let mut search_from = 1;
|
||||||
|
|
||||||
|
while let Some(rel) = patch[search_from..].find("\nFrom ") {
|
||||||
|
let ix = search_from + rel + 1;
|
||||||
|
let hex = patch[ix + 5..]
|
||||||
|
.split(|c: char| !c.is_ascii_hexdigit())
|
||||||
|
.next()
|
||||||
|
.unwrap_or("");
|
||||||
|
if hex.len() == 40 {
|
||||||
|
starts.push(ix);
|
||||||
|
}
|
||||||
|
search_from = ix + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
starts
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, &start)| {
|
||||||
|
let end = starts.get(i + 1).copied().unwrap_or(patch.len());
|
||||||
|
&patch[start..end]
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse `git format-patch` output, a single patch or a series.
|
||||||
|
///
|
||||||
|
/// Backed by [`diffy::patch_set`], which implements git's extended diff format:
|
||||||
|
/// `diff --git` headers, rename and copy detection, binary detection, and
|
||||||
|
/// C-style quoted or octal-escaped paths.
|
||||||
|
pub fn patch_diffs(patch: &str) -> Result<CommitDiff> {
|
||||||
|
if !patch.lines().any(|line| line.starts_with("diff --git ")) {
|
||||||
|
return Ok(CommitDiff { files: Vec::new() });
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut files = Vec::new();
|
||||||
|
|
||||||
|
for file in PatchSet::parse(patch, ParseOptions::gitdiff()) {
|
||||||
|
files.push(file_diff(file?)?);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(CommitDiff { files })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The [`FileDiff`] of one parsed file patch.
|
||||||
|
fn file_diff(file: FilePatch<'_, str>) -> Result<FileDiff> {
|
||||||
|
// The `---`/`+++` paths carry the `a/`/`b/` prefix, so the first path
|
||||||
|
// component is dropped, the same way `git apply -p1` does.
|
||||||
|
// Rename and copy paths come from their own headers, unprefixed.
|
||||||
|
let stripped;
|
||||||
|
let operation = match file.operation() {
|
||||||
|
operation @ (FileOperation::Rename { .. } | FileOperation::Copy { .. }) => operation,
|
||||||
|
operation => {
|
||||||
|
stripped = operation.strip_prefix(1);
|
||||||
|
&stripped
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (path, old_path, status) = match operation {
|
||||||
|
FileOperation::Create(path) => (path.as_ref(), None, DiffStatus::Added),
|
||||||
|
FileOperation::Delete(path) => (path.as_ref(), None, DiffStatus::Deleted),
|
||||||
|
FileOperation::Modify { modified, .. } => (modified.as_ref(), None, DiffStatus::Modified),
|
||||||
|
FileOperation::Rename { from, to } => {
|
||||||
|
(to.as_ref(), Some(from.as_ref()), DiffStatus::Renamed)
|
||||||
|
}
|
||||||
|
FileOperation::Copy { from, to } => (to.as_ref(), Some(from.as_ref()), DiffStatus::Copied),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut insertions = 0usize;
|
||||||
|
let mut deletions = 0usize;
|
||||||
|
let mut hunks = Vec::new();
|
||||||
|
|
||||||
|
let patch = file.patch();
|
||||||
|
|
||||||
|
if let Some(text) = patch.as_text() {
|
||||||
|
for hunk in text.hunks() {
|
||||||
|
let hunk = hunk_diff(hunk);
|
||||||
|
insertions += hunk
|
||||||
|
.lines
|
||||||
|
.iter()
|
||||||
|
.filter(|line| line.kind == DiffLineKind::Addition)
|
||||||
|
.count();
|
||||||
|
deletions += hunk
|
||||||
|
.lines
|
||||||
|
.iter()
|
||||||
|
.filter(|line| line.kind == DiffLineKind::Deletion)
|
||||||
|
.count();
|
||||||
|
hunks.push(hunk);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(FileDiff {
|
||||||
|
path: path.to_owned(),
|
||||||
|
old_path: old_path.map(str::to_owned),
|
||||||
|
status,
|
||||||
|
insertions,
|
||||||
|
deletions,
|
||||||
|
binary: patch.is_binary(),
|
||||||
|
hunks,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The [`DiffHunk`] of one parsed hunk, including the line number of every line.
|
||||||
|
///
|
||||||
|
/// `diffy` reports only the hunk header ranges. The per-line numbers are
|
||||||
|
/// counted from them the way the header encodes them: context lines advance
|
||||||
|
/// both sides, deletions only the old, insertions only the new.
|
||||||
|
fn hunk_diff(hunk: &Hunk<'_, str>) -> DiffHunk {
|
||||||
|
let old_range = hunk.old_range();
|
||||||
|
let new_range = hunk.new_range();
|
||||||
|
|
||||||
|
let mut old = old_range.start() as u32;
|
||||||
|
let mut new = new_range.start() as u32;
|
||||||
|
let mut lines = Vec::with_capacity(hunk.lines().len());
|
||||||
|
|
||||||
|
for line in hunk.lines() {
|
||||||
|
let (kind, text) = match line {
|
||||||
|
Line::Context(text) => (DiffLineKind::Context, *text),
|
||||||
|
Line::Delete(text) => (DiffLineKind::Deletion, *text),
|
||||||
|
Line::Insert(text) => (DiffLineKind::Addition, *text),
|
||||||
|
};
|
||||||
|
|
||||||
|
let (old_no, new_no) = match kind {
|
||||||
|
DiffLineKind::Context => {
|
||||||
|
let numbers = (Some(old), Some(new));
|
||||||
|
old += 1;
|
||||||
|
new += 1;
|
||||||
|
numbers
|
||||||
|
}
|
||||||
|
DiffLineKind::Addition => {
|
||||||
|
let number = Some(new);
|
||||||
|
new += 1;
|
||||||
|
(None, number)
|
||||||
|
}
|
||||||
|
DiffLineKind::Deletion => {
|
||||||
|
let number = Some(old);
|
||||||
|
old += 1;
|
||||||
|
(number, None)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
lines.push(DiffLine {
|
||||||
|
kind,
|
||||||
|
old: old_no,
|
||||||
|
new: new_no,
|
||||||
|
text: line_text(text),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
DiffHunk {
|
||||||
|
old_start: old_range.start() as u32,
|
||||||
|
old_lines: old_range.len() as u32,
|
||||||
|
new_start: new_range.start() as u32,
|
||||||
|
new_lines: new_range.len() as u32,
|
||||||
|
lines,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The content of a parsed line without its line ending.
|
||||||
|
///
|
||||||
|
/// `diffy` keeps the trailing `\n`, the way `str::lines` splits it off.
|
||||||
|
fn line_text(text: &str) -> String {
|
||||||
|
let text = text.strip_suffix('\n').unwrap_or(text);
|
||||||
|
text.strip_suffix('\r').unwrap_or(text).to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commits of a `git format-patch` output, a single patch or a series.
|
||||||
|
///
|
||||||
|
/// Entries appear in patch order, oldest first as `git format-patch` produces them.
|
||||||
|
pub fn patch_commits(patch: &str) -> Vec<FileCommit> {
|
||||||
|
let lines: Vec<&str> = patch.lines().collect();
|
||||||
|
|
||||||
|
let mut commits = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
|
||||||
|
while i < lines.len() {
|
||||||
|
// A patch starts with its `From <id> <date>` envelope line.
|
||||||
|
let Some(rest) = lines[i].strip_prefix("From ") else {
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(id) = rest.split_whitespace().next() else {
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
if id.len() != 40 {
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut author = String::new();
|
||||||
|
let mut summary = String::new();
|
||||||
|
let mut time = 0i64;
|
||||||
|
|
||||||
|
// Envelope headers run up to the blank line before the commit message.
|
||||||
|
i += 1;
|
||||||
|
while i < lines.len() && !lines[i].is_empty() {
|
||||||
|
let header = lines[i];
|
||||||
|
if let Some(value) = header.strip_prefix("From: ") {
|
||||||
|
author = name_from_address(value);
|
||||||
|
} else if let Some(value) = header.strip_prefix("Subject: ") {
|
||||||
|
summary = strip_patch_prefix(value);
|
||||||
|
} else if let Some(value) = header.strip_prefix("Date: ") {
|
||||||
|
time = gix::date::parse(value.trim(), None)
|
||||||
|
.map(|t| t.seconds)
|
||||||
|
.unwrap_or(0);
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
commits.push(FileCommit {
|
||||||
|
id: id.to_string(),
|
||||||
|
summary,
|
||||||
|
description: None,
|
||||||
|
author,
|
||||||
|
time,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
commits
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name part of a `From: Name <email>` 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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strip the patch prefix from a `Subject:` header.
|
||||||
|
///
|
||||||
|
/// Examples are `[PATCH]`, `[PATCH 1/2]` and `[RFC PATCH]`.
|
||||||
|
fn strip_patch_prefix(subject: &str) -> String {
|
||||||
|
let trimmed = subject.trim();
|
||||||
|
let Some(rest) = trimmed.strip_prefix('[') else {
|
||||||
|
return trimmed.to_string();
|
||||||
|
};
|
||||||
|
let Some(end) = rest.find(']') else {
|
||||||
|
return trimmed.to_string();
|
||||||
|
};
|
||||||
|
if rest[..end].to_ascii_lowercase().contains("patch") {
|
||||||
|
rest[end + 1..].trim().to_string()
|
||||||
|
} else {
|
||||||
|
trimmed.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use gix::interrupt::IS_INTERRUPTED;
|
||||||
|
use gix::progress::Discard;
|
||||||
|
|
||||||
|
/// Clone into `path` from the first working URL in `clone_urls`.
|
||||||
|
///
|
||||||
|
/// Unlike [`GitCache::ensure_clone`], the clone is not kept in any cache.
|
||||||
|
pub fn clone_repo<U: AsRef<str>>(clone_urls: &[U], path: &Path) -> Result<()> {
|
||||||
|
if path.exists() {
|
||||||
|
bail!("destination {} already exists", path.display());
|
||||||
|
}
|
||||||
|
|
||||||
|
try_each_url(clone_urls, "clone", |url| {
|
||||||
|
let repo = clone(url, path)?;
|
||||||
|
// The initial clone uses the default refspecs. Also fetch the `refs/nostr/*` PR refs.
|
||||||
|
fetch_all(&repo).ok();
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch all configured refspecs from `origin`, plus the `refs/nostr/*` namespace.
|
||||||
|
pub fn fetch_all(repo: &gix::Repository) -> Result<()> {
|
||||||
|
let options = gix::remote::ref_map::Options {
|
||||||
|
extra_refspecs: vec![
|
||||||
|
gix::refspec::parse(
|
||||||
|
gix::bstr::BStr::new("+refs/nostr/*:refs/nostr/*"),
|
||||||
|
gix::refspec::parse::Operation::Fetch,
|
||||||
|
)?
|
||||||
|
.to_owned(),
|
||||||
|
],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
repo.find_remote("origin")?
|
||||||
|
.connect(gix::remote::Direction::Fetch)?
|
||||||
|
.prepare_fetch(Discard, options)?
|
||||||
|
.receive(Discard, &IS_INTERRUPTED)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Push `commit` to `reference` on the server at `url`, from `repo_path`.
|
||||||
|
pub fn push_commit_ref(repo_path: &Path, url: &str, commit: &str, reference: &str) -> Result<()> {
|
||||||
|
let output = Command::new("git")
|
||||||
|
.arg("-C")
|
||||||
|
.arg(repo_path)
|
||||||
|
.args(["push"])
|
||||||
|
.arg(url)
|
||||||
|
.arg(format!("{commit}:{reference}"))
|
||||||
|
.env("GIT_TERMINAL_PROMPT", "0")
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.output()
|
||||||
|
.context("failed to spawn `git push`")?;
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
bail!(
|
||||||
|
"git push failed: {}",
|
||||||
|
String::from_utf8_lossy(&output.stderr).trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rewrite a grasp server URL to the https URL the git transport actually uses.
|
||||||
|
///
|
||||||
|
/// GRASP servers announce `grasp://<host>/<owner>/<repo>` clone URLs.
|
||||||
|
/// The transport is git smart HTTP, so the scheme is rewritten for gix.
|
||||||
|
fn transport_url(url: &str) -> String {
|
||||||
|
url.strip_prefix("grasp://")
|
||||||
|
.map(|rest| format!("https://{rest}"))
|
||||||
|
.unwrap_or_else(|| url.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `attempt` against each URL in `urls` until one succeeds.
|
||||||
|
///
|
||||||
|
/// Returns the last error wrapped in `failed to {verb} from any mirror`,
|
||||||
|
/// or `no clone URLs provided` when the list is empty.
|
||||||
|
fn try_each_url<U: AsRef<str>, F>(urls: &[U], verb: &str, mut attempt: F) -> Result<()>
|
||||||
|
where
|
||||||
|
F: FnMut(&str) -> Result<()>,
|
||||||
|
{
|
||||||
|
let mut last_err: Option<anyhow::Error> = None;
|
||||||
|
|
||||||
|
for url in urls {
|
||||||
|
match attempt(url.as_ref()) {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(e) => last_err = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match last_err {
|
||||||
|
Some(e) => Err(e).context(format!("failed to {verb} from any mirror")),
|
||||||
|
None => bail!("no clone URLs provided"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clone(url: &str, path: &Path) -> Result<gix::Repository> {
|
||||||
|
let url = transport_url(url);
|
||||||
|
let url = gix::url::parse(url).context("invalid clone URL")?;
|
||||||
|
|
||||||
|
let mut prepare = gix::prepare_clone(url, path)?;
|
||||||
|
let (mut checkout, _fetch) = prepare.fetch_then_checkout(Discard, &IS_INTERRUPTED)?;
|
||||||
|
let (repo, _checkout) = checkout.main_worktree(Discard, &IS_INTERRUPTED)?;
|
||||||
|
|
||||||
|
Ok(repo)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Push the `main` branch of the repository at `repo_path` to a grasp server.
|
||||||
|
pub fn push_main(repo_path: &Path, base_url: &str, owner: &str, repo_id: &str) -> Result<()> {
|
||||||
|
push_refspecs(
|
||||||
|
repo_path,
|
||||||
|
base_url,
|
||||||
|
owner,
|
||||||
|
repo_id,
|
||||||
|
&["refs/heads/main:refs/heads/main"],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Push every local branch and tag of the repository at `repo_path` to a grasp server.
|
||||||
|
///
|
||||||
|
/// This mirrors an initialized repository's whole history.
|
||||||
|
pub fn push_all(repo_path: &Path, base_url: &str, owner: &str, repo_id: &str) -> Result<()> {
|
||||||
|
push_refspecs(
|
||||||
|
repo_path,
|
||||||
|
base_url,
|
||||||
|
owner,
|
||||||
|
repo_id,
|
||||||
|
&["refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*"],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Push `refspecs` to the grasp server URL derived from `base_url`, `owner` and `repo_id`.
|
||||||
|
fn push_refspecs(
|
||||||
|
repo_path: &Path,
|
||||||
|
base_url: &str,
|
||||||
|
owner: &str,
|
||||||
|
repo_id: &str,
|
||||||
|
refspecs: &[&str],
|
||||||
|
) -> Result<()> {
|
||||||
|
let url = format!("{base_url}/{owner}/{repo_id}.git");
|
||||||
|
|
||||||
|
let mut args: Vec<&str> = Vec::with_capacity(refspecs.len() + 2);
|
||||||
|
args.push("push");
|
||||||
|
args.push(&url);
|
||||||
|
args.extend_from_slice(refspecs);
|
||||||
|
|
||||||
|
let output = git_output(repo_path, &args, "git push")?;
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
bail!(
|
||||||
|
"git push to {base_url} failed: {}",
|
||||||
|
String::from_utf8_lossy(&output.stderr).trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `url` advertises every ref in `expected` at the given commit.
|
||||||
|
///
|
||||||
|
/// Extra advertised refs are ignored: the question is whether the data this
|
||||||
|
/// push wanted to land is already there, not whether the remote is an exact mirror.
|
||||||
|
/// This is the convergence probe for a push that lost the compare-and-swap race
|
||||||
|
/// to the grasp server's own background ref alignment.
|
||||||
|
pub fn remote_has_refs(repo_path: &Path, url: &str, expected: &[(String, String)]) -> Result<bool> {
|
||||||
|
if expected.is_empty() {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
let repo = gix::open(repo_path)?;
|
||||||
|
let url = transport_url(url);
|
||||||
|
|
||||||
|
// A URL-created remote has no configured fetch refspecs, and `ref_map` only
|
||||||
|
// keeps refs that match one. Match each expected ref by its exact name,
|
||||||
|
// like `git ls-remote <url> <name>` would; ref maps never write to the repository.
|
||||||
|
let refspecs = expected
|
||||||
|
.iter()
|
||||||
|
.map(|(name, _)| {
|
||||||
|
gix::refspec::parse(
|
||||||
|
gix::bstr::BStr::new(format!("+{name}:{name}").as_bytes()),
|
||||||
|
gix::refspec::parse::Operation::Fetch,
|
||||||
|
)
|
||||||
|
.map(|spec| spec.to_owned())
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>, _>>()
|
||||||
|
.context("invalid refspec")?;
|
||||||
|
|
||||||
|
let options = gix::remote::ref_map::Options {
|
||||||
|
extra_refspecs: refspecs,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let (refs, _) = repo
|
||||||
|
.remote_at(url.as_str())
|
||||||
|
.with_context(|| format!("cannot use remote {url}"))?
|
||||||
|
.connect(gix::remote::Direction::Fetch)
|
||||||
|
.with_context(|| format!("cannot connect to {url}"))?
|
||||||
|
.ref_map(Discard, options)
|
||||||
|
.with_context(|| format!("listing refs of {url} failed"))?;
|
||||||
|
|
||||||
|
// Peeled tag entries carry the tag object in their direct oid, so mapping
|
||||||
|
// each advertised ref to its direct oid matches `git ls-remote` while
|
||||||
|
// skipping the duplicated `^{}` lines.
|
||||||
|
let advertised: HashMap<String, String> = refs
|
||||||
|
.remote_refs
|
||||||
|
.iter()
|
||||||
|
.filter_map(|reference| {
|
||||||
|
let (name, object, _peeled) = reference.unpack();
|
||||||
|
object.map(|oid| (String::from_utf8_lossy(name).into_owned(), oid.to_string()))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(expected
|
||||||
|
.iter()
|
||||||
|
.all(|(name, oid)| advertised.get(name.as_str()) == Some(oid)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add `origin` pointing at `url` when the repository has no remote yet.
|
||||||
|
///
|
||||||
|
/// No-op if `origin` already exists.
|
||||||
|
pub fn ensure_origin(repo_path: &Path, url: &str) -> Result<()> {
|
||||||
|
let repo = gix::open(repo_path)?;
|
||||||
|
if repo.find_remote("origin").is_ok() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// `git remote add` also configures the default fetch refspec.
|
||||||
|
edit_local_config(&repo, |config| {
|
||||||
|
config.set_raw_value("remote.origin.url", url)?;
|
||||||
|
config.set_raw_value("remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*")?;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Point `origin` at `url`, replacing an existing remote,
|
||||||
|
/// used after a clone whose `origin` points at the cloned-from path.
|
||||||
|
///
|
||||||
|
/// A working copy cloned from a local mirror is re-targeted at the grasp server.
|
||||||
|
pub fn set_origin(repo_path: &Path, url: &str) -> Result<()> {
|
||||||
|
let repo = gix::open(repo_path)?;
|
||||||
|
let had_origin = repo.find_remote("origin").is_ok();
|
||||||
|
|
||||||
|
edit_local_config(&repo, |config| {
|
||||||
|
// Replaces the existing url, like `git remote set-url origin <url>`.
|
||||||
|
// A pre-existing fetch refspec is left untouched.
|
||||||
|
config.set_raw_value("remote.origin.url", url)?;
|
||||||
|
|
||||||
|
if !had_origin {
|
||||||
|
config.set_raw_value("remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply `edit` to the repository-local configuration and persist it.
|
||||||
|
///
|
||||||
|
/// The config file is locked while it is read, edited and written back,
|
||||||
|
/// like git would when running `git config` or `git remote`.
|
||||||
|
fn edit_local_config(
|
||||||
|
repo: &gix::Repository,
|
||||||
|
edit: impl FnOnce(&mut gix::config::File) -> Result<()>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let config_path = repo.common_dir().join("config");
|
||||||
|
|
||||||
|
let mut lock = gix::lock::File::acquire_to_update_resource(
|
||||||
|
&config_path,
|
||||||
|
gix::lock::acquire::Fail::Immediately,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.context("failed to lock repository config")?;
|
||||||
|
|
||||||
|
let mut config =
|
||||||
|
match gix::config::File::from_path_no_includes(config_path, gix::config::Source::Local) {
|
||||||
|
Ok(config) => config,
|
||||||
|
// A repository without a config file yet starts from scratch.
|
||||||
|
Err(gix::config::file::init::from_paths::Error::Io { source, .. })
|
||||||
|
if source.kind() == std::io::ErrorKind::NotFound =>
|
||||||
|
{
|
||||||
|
gix::config::File::default()
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error).context("failed to read repository config"),
|
||||||
|
};
|
||||||
|
|
||||||
|
edit(&mut config)?;
|
||||||
|
|
||||||
|
config
|
||||||
|
.write_to(&mut lock)
|
||||||
|
.context("failed to write repository config")?;
|
||||||
|
|
||||||
|
lock.commit().context("failed to save repository config")?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch `refspec` into `repo_path` from the first working URL in `urls`.
|
||||||
|
/// When no URL works, the last error is returned.
|
||||||
|
///
|
||||||
|
/// Never touches the checked-out refs or the worktree.
|
||||||
|
pub fn fetch_repo_refs<U: AsRef<str>>(repo_path: &Path, urls: &[U], refspec: &str) -> Result<()> {
|
||||||
|
let repo = gix::open(repo_path)?;
|
||||||
|
let refspec = gix::refspec::parse(
|
||||||
|
gix::bstr::BStr::new(refspec),
|
||||||
|
gix::refspec::parse::Operation::Fetch,
|
||||||
|
)
|
||||||
|
.context("invalid fetch refspec")?
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
|
try_each_url(urls, "fetch", |url| {
|
||||||
|
let url = transport_url(url);
|
||||||
|
let options = gix::remote::ref_map::Options {
|
||||||
|
extra_refspecs: vec![refspec.clone()],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
repo.remote_at(url.as_str())
|
||||||
|
.with_context(|| format!("fetch from {url} failed"))?
|
||||||
|
.connect(gix::remote::Direction::Fetch)
|
||||||
|
.with_context(|| format!("fetch from {url} failed"))?
|
||||||
|
.prepare_fetch(Discard, options)
|
||||||
|
.with_context(|| format!("fetch from {url} failed"))?
|
||||||
|
.receive(Discard, &IS_INTERRUPTED)
|
||||||
|
.with_context(|| format!("fetch from {url} failed"))?;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The URL of the `origin` remote of the repository at `workdir`.
|
||||||
|
///
|
||||||
|
/// `None` when it has no `origin` yet.
|
||||||
|
pub fn origin_url(workdir: &Path) -> Result<Option<String>> {
|
||||||
|
let Ok(repo) = gix::open(workdir) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(remote) = repo.find_remote("origin") else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(remote
|
||||||
|
.url(gix::remote::Direction::Fetch)
|
||||||
|
.map(|url| url.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `git -C dir args`, disabling the terminal prompt and capturing stderr.
|
||||||
|
///
|
||||||
|
/// `what` names the command in the spawn error.
|
||||||
|
pub(crate) fn git_output(dir: &Path, args: &[&str], what: &str) -> Result<std::process::Output> {
|
||||||
|
Command::new("git")
|
||||||
|
.arg("-C")
|
||||||
|
.arg(dir)
|
||||||
|
.args(args)
|
||||||
|
.env("GIT_TERMINAL_PROMPT", "0")
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.output()
|
||||||
|
.with_context(|| format!("failed to spawn `{what}`"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,488 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
|
||||||
|
use crate::history::open_with_cache;
|
||||||
|
use crate::worktree::{force_checkout, worktree_dirty};
|
||||||
|
|
||||||
|
/// The merge base of two revisions in the repository at `repo_path`,
|
||||||
|
/// revisions may be branch names, remote-tracking refs or commit ids.
|
||||||
|
///
|
||||||
|
/// `Ok(None)` when the revisions share no common ancestor.
|
||||||
|
///
|
||||||
|
/// Unresolvable revisions are errors.
|
||||||
|
pub fn merge_base(repo_path: &Path, a: &str, b: &str) -> Result<Option<String>> {
|
||||||
|
let repo = open_with_cache(repo_path)?;
|
||||||
|
let a = repo.rev_parse_single(a.as_bytes())?;
|
||||||
|
let b = repo.rev_parse_single(b.as_bytes())?;
|
||||||
|
match repo.merge_base(a, b) {
|
||||||
|
Ok(id) => Ok(Some(id.to_string())),
|
||||||
|
// No common ancestor, a valid outcome for a proposal.
|
||||||
|
Err(gix::repository::merge_base::Error::NotFound { .. }) => Ok(None),
|
||||||
|
Err(e) => Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The commit HEAD points to in the repository at `repo_path`.
|
||||||
|
///
|
||||||
|
/// `None` when the repository has no commits yet, an unborn HEAD.
|
||||||
|
pub fn head_commit_id(repo_path: &Path) -> Result<Option<String>> {
|
||||||
|
let Ok(repo) = gix::open(repo_path) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
match repo.head_id() {
|
||||||
|
Ok(id) => Ok(Some(id.to_string())),
|
||||||
|
Err(_) => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The commits in `base..HEAD` of the repository at `repo_path`, oldest first.
|
||||||
|
/// This is the order `git am` creates them.
|
||||||
|
///
|
||||||
|
/// `HEAD` alone when `base` is `None`.
|
||||||
|
pub fn commits_since(repo_path: &Path, base: Option<&str>) -> Result<Vec<String>> {
|
||||||
|
let repo = match gix::open(repo_path) {
|
||||||
|
Ok(repo) => repo,
|
||||||
|
Err(_) if base.is_none() => return Ok(Vec::new()),
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let head = match repo.head_id() {
|
||||||
|
Ok(head) => head,
|
||||||
|
Err(_) if base.is_none() => return Ok(Vec::new()),
|
||||||
|
Err(e) => return Err(e).context("repository has no commits"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(base) = base else {
|
||||||
|
// `HEAD` alone when no base is given.
|
||||||
|
return Ok(vec![head.to_string()]);
|
||||||
|
};
|
||||||
|
|
||||||
|
let base = repo.rev_parse_single(base.as_bytes())?;
|
||||||
|
let mut commits = Vec::new();
|
||||||
|
|
||||||
|
for info in repo
|
||||||
|
.rev_walk([head])
|
||||||
|
.sorting(gix::revision::walk::Sorting::ByCommitTime(
|
||||||
|
gix::traverse::commit::simple::CommitTimeOrder::NewestFirst,
|
||||||
|
))
|
||||||
|
.with_hidden([base])
|
||||||
|
.all()?
|
||||||
|
{
|
||||||
|
commits.push(info?.id().to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Oldest first, like `git rev-list --reverse`, the order `git am` creates them.
|
||||||
|
commits.reverse();
|
||||||
|
|
||||||
|
Ok(commits)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The identity written to reflogs and commits created by this crate itself.
|
||||||
|
///
|
||||||
|
/// Like `git -c user.name=… -c user.email=…` per invocation: the repository works
|
||||||
|
/// without a global git identity, and `gix` runs no hooks and never signs.
|
||||||
|
pub(crate) fn repository_signature() -> (gix::actor::Signature, gix::date::parse::TimeBuf) {
|
||||||
|
let seconds = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|duration| duration.as_secs() as i64)
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let signature = gix::actor::Signature {
|
||||||
|
name: gix::bstr::BString::from("Signed"),
|
||||||
|
email: gix::bstr::BString::from("signed@localhost"),
|
||||||
|
time: gix::date::Time { seconds, offset: 0 },
|
||||||
|
};
|
||||||
|
|
||||||
|
(signature, gix::date::parse::TimeBuf::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a repository at `path` with an initial `main` branch.
|
||||||
|
/// Write a `README.md` from `name` and `description`, then create the initial commit.
|
||||||
|
///
|
||||||
|
/// Returns the initial commit id.
|
||||||
|
pub fn init_repository(path: &Path, name: &str, description: &str) -> Result<String> {
|
||||||
|
use gix::refs::transaction::{Change, LogChange, PreviousValue, RefEdit, RefLog};
|
||||||
|
|
||||||
|
std::fs::create_dir_all(path)
|
||||||
|
.with_context(|| format!("failed to create {}", path.display()))?;
|
||||||
|
|
||||||
|
let repo = gix::init(path)?;
|
||||||
|
|
||||||
|
let (signature, mut time_buf) = repository_signature();
|
||||||
|
let signature = signature.to_ref(&mut time_buf);
|
||||||
|
|
||||||
|
// The initial branch is `main`, regardless of `init.defaultBranch` in
|
||||||
|
// the user's git configuration: point the unborn HEAD there.
|
||||||
|
let head = gix::refs::FullName::try_from("HEAD")
|
||||||
|
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?;
|
||||||
|
|
||||||
|
repo.edit_references_as(
|
||||||
|
[RefEdit {
|
||||||
|
change: Change::Update {
|
||||||
|
log: LogChange {
|
||||||
|
mode: RefLog::AndReference,
|
||||||
|
force_create_reflog: false,
|
||||||
|
message: "checkout: moving to main".into(),
|
||||||
|
},
|
||||||
|
expected: PreviousValue::Any,
|
||||||
|
new: gix::refs::Target::Symbolic(
|
||||||
|
gix::refs::FullName::try_from("refs/heads/main")
|
||||||
|
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
name: head,
|
||||||
|
deref: false,
|
||||||
|
}],
|
||||||
|
Some(signature),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let readme = if description.trim().is_empty() {
|
||||||
|
format!("# {name}\n")
|
||||||
|
} else {
|
||||||
|
format!("# {name}\n\n{description}\n")
|
||||||
|
};
|
||||||
|
|
||||||
|
std::fs::write(path.join("README.md"), &readme).context("failed to write README.md")?;
|
||||||
|
|
||||||
|
let blob = repo.write_object(gix::objs::Blob {
|
||||||
|
data: readme.into_bytes(),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let tree = repo.write_object(gix::objs::Tree {
|
||||||
|
entries: vec![gix::objs::tree::Entry {
|
||||||
|
mode: gix::objs::tree::EntryKind::Blob.into(),
|
||||||
|
filename: gix::bstr::BString::from("README.md"),
|
||||||
|
oid: blob.into(),
|
||||||
|
}],
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let commit = repo.commit_as(
|
||||||
|
signature,
|
||||||
|
signature,
|
||||||
|
"HEAD",
|
||||||
|
"Initial commit",
|
||||||
|
tree,
|
||||||
|
Vec::<gix::ObjectId>::new(),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Populate the index so the fresh repository is clean,
|
||||||
|
// as `git add` and`git commit` would leave it.
|
||||||
|
let mut index = repo.index_from_tree(&tree)?;
|
||||||
|
index.write(gix::index::write::Options::default())?;
|
||||||
|
|
||||||
|
let commit = commit.to_string();
|
||||||
|
if commit.len() != 40 {
|
||||||
|
bail!("unexpected initial commit id: {commit}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(commit)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The earliest unique commit of the repository at `repo_path`.
|
||||||
|
/// Used as the NIP-34 announcement's `euc` marker.
|
||||||
|
///
|
||||||
|
/// `None` for a repository without commits.
|
||||||
|
pub fn root_commit(repo_path: &Path) -> Result<Option<String>> {
|
||||||
|
let Ok(repo) = gix::open(repo_path) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(head) = repo.head_id() else {
|
||||||
|
// An unborn HEAD with no commits yet has no root commit.
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
for info in repo
|
||||||
|
.rev_walk([head])
|
||||||
|
.sorting(gix::revision::walk::Sorting::ByCommitTime(
|
||||||
|
gix::traverse::commit::simple::CommitTimeOrder::NewestFirst,
|
||||||
|
))
|
||||||
|
.all()?
|
||||||
|
{
|
||||||
|
let info = info?;
|
||||||
|
if info.parent_ids().next().is_none() {
|
||||||
|
let id = info.id().to_string();
|
||||||
|
return Ok((id.len() == 40).then_some(id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full ref names under `prefix`, sorted lexicographically, like `git for-each-ref`.
|
||||||
|
/// `prefix` is a ref namespace like `refs/fork/<owner>/<id>`.
|
||||||
|
///
|
||||||
|
/// Returns an empty list when nothing matches.
|
||||||
|
pub fn refs_with_prefix(repo_path: &Path, prefix: &str) -> Result<Vec<String>> {
|
||||||
|
let pattern = prefix.trim_end_matches('/');
|
||||||
|
let repo = gix::open(repo_path)?;
|
||||||
|
let mut names = Vec::new();
|
||||||
|
|
||||||
|
for reference in repo.references()?.all()? {
|
||||||
|
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||||
|
let name = String::from_utf8_lossy(reference.name().as_bstr()).into_owned();
|
||||||
|
|
||||||
|
// Match the pattern itself and everything beneath it, like `git for-each-ref`.
|
||||||
|
let under_pattern = name
|
||||||
|
.strip_prefix(pattern)
|
||||||
|
.is_some_and(|rest| rest.is_empty() || rest.starts_with('/'));
|
||||||
|
|
||||||
|
if under_pattern {
|
||||||
|
names.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort lexicographically, like `git for-each-ref`.
|
||||||
|
names.sort();
|
||||||
|
|
||||||
|
Ok(names)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete every ref under `prefix` of the repository at `repo_path`.
|
||||||
|
/// `prefix` is a ref namespace like `refs/fork/<owner>/<id>`.
|
||||||
|
pub fn delete_refs_with_prefix(repo_path: &Path, prefix: &str) -> Result<()> {
|
||||||
|
use gix::refs::transaction::{Change, PreviousValue, RefEdit, RefLog};
|
||||||
|
|
||||||
|
let refs = refs_with_prefix(repo_path, prefix)?;
|
||||||
|
if refs.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let repo = gix::open(repo_path)?;
|
||||||
|
let edits: Vec<RefEdit> = refs
|
||||||
|
.iter()
|
||||||
|
.map(|name| {
|
||||||
|
let full = gix::refs::FullName::try_from(name.as_str())
|
||||||
|
.map_err(|e| anyhow::anyhow!("invalid ref name {name}: {e}"))?;
|
||||||
|
Ok(RefEdit {
|
||||||
|
change: Change::Delete {
|
||||||
|
expected: PreviousValue::Any,
|
||||||
|
log: RefLog::AndReference,
|
||||||
|
},
|
||||||
|
name: full,
|
||||||
|
deref: false,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>>>()?;
|
||||||
|
|
||||||
|
// Delete all refs with the given prefix.
|
||||||
|
repo.edit_references(edits)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Short name of the branch HEAD points to at `workdir`,
|
||||||
|
/// `None` when detached or unreadable, like `git branch --show-current`.
|
||||||
|
pub fn worktree_current_branch(workdir: &Path) -> Option<String> {
|
||||||
|
let repo = gix::open(workdir).ok()?;
|
||||||
|
let head = repo.head().ok()?;
|
||||||
|
let name = head.referent_name()?;
|
||||||
|
Some(String::from_utf8_lossy(name.shorten()).into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the reference `name` exists in the repository at `workdir`.
|
||||||
|
pub fn worktree_ref_exists(workdir: &Path, name: &str) -> bool {
|
||||||
|
let Ok(repo) = gix::open(workdir) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
repo.find_reference(name).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fast-forward local branches that trail their remote-tracking counterpart.
|
||||||
|
///
|
||||||
|
/// Returns whether any branch moved.
|
||||||
|
pub fn fast_forward_branches(workdir: &Path) -> Result<bool> {
|
||||||
|
let repo = gix::open(workdir)?;
|
||||||
|
let current = worktree_current_branch(workdir);
|
||||||
|
let heads = refs_with_prefix(workdir, "refs/heads")?;
|
||||||
|
|
||||||
|
let (signature, mut time_buf) = repository_signature();
|
||||||
|
let signature = signature.to_ref(&mut time_buf);
|
||||||
|
|
||||||
|
let mut moved = false;
|
||||||
|
|
||||||
|
for head in heads {
|
||||||
|
let Some(branch) = head.strip_prefix("refs/heads/") else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let remote = format!("refs/remotes/origin/{branch}");
|
||||||
|
// No remote-tracking counterpart means the remote lacks this branch.
|
||||||
|
let Ok(mut remote_reference) = repo.find_reference(&remote) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(mut local_reference) = repo.find_reference(&head) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(remote_oid) = remote_reference.peel_to_id() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(local_oid) = local_reference.peel_to_id() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let remote_oid = remote_oid.detach();
|
||||||
|
let local_oid = local_oid.detach();
|
||||||
|
|
||||||
|
if local_oid == remote_oid {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only fast-forward.
|
||||||
|
// Local-only commits or diverged history must never be rewritten by a refresh.
|
||||||
|
let Ok(base) = repo.merge_base(local_oid, remote_oid) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
if base != local_oid {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let full = gix::refs::FullName::try_from(head.as_str())
|
||||||
|
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?;
|
||||||
|
|
||||||
|
let edit = |new: gix::refs::Target| {
|
||||||
|
use gix::refs::transaction::{Change, LogChange, PreviousValue, RefEdit, RefLog};
|
||||||
|
RefEdit {
|
||||||
|
change: Change::Update {
|
||||||
|
log: LogChange {
|
||||||
|
mode: RefLog::AndReference,
|
||||||
|
force_create_reflog: false,
|
||||||
|
message: format!("merge {remote}: Fast-forward").into(),
|
||||||
|
},
|
||||||
|
expected: PreviousValue::ExistingMustMatch(gix::refs::Target::Object(
|
||||||
|
local_oid,
|
||||||
|
)),
|
||||||
|
new,
|
||||||
|
},
|
||||||
|
name: full.clone(),
|
||||||
|
deref: false,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if current.as_deref() == Some(branch) {
|
||||||
|
// Merge so the checked-out worktree follows the branch.
|
||||||
|
// Only proceed on a clean worktree, like `git merge --ff-only`.
|
||||||
|
if worktree_dirty(workdir) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let tree = repo.find_object(remote_oid)?.peel_to_tree()?.id;
|
||||||
|
|
||||||
|
// Check out the remote tree, discarding local changes.
|
||||||
|
force_checkout(&repo, &tree)?;
|
||||||
|
|
||||||
|
// Update the branch reference to point to the remote tree.
|
||||||
|
repo.edit_references_as(
|
||||||
|
[edit(gix::refs::Target::Object(remote_oid))],
|
||||||
|
Some(signature),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
moved = true;
|
||||||
|
} else {
|
||||||
|
// Update the branch reference to point to the remote tree.
|
||||||
|
repo.edit_references_as(
|
||||||
|
[edit(gix::refs::Target::Object(remote_oid))],
|
||||||
|
Some(signature),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
moved = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(moved)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Short names of local branches, `refs/heads/*`, of `repo`, sorted alphabetically.
|
||||||
|
pub fn repo_branches(repo: &gix::Repository) -> Result<Vec<String>> {
|
||||||
|
let mut names = Vec::new();
|
||||||
|
for reference in repo.references()?.local_branches()? {
|
||||||
|
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||||
|
names.push(String::from_utf8_lossy(reference.name().shorten()).into_owned());
|
||||||
|
}
|
||||||
|
names.sort();
|
||||||
|
Ok(names)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Short names of tags, `refs/tags/*`, of `repo`, sorted alphabetically.
|
||||||
|
pub fn repo_tags(repo: &gix::Repository) -> Result<Vec<String>> {
|
||||||
|
let mut names = Vec::new();
|
||||||
|
for reference in repo.references()?.tags()? {
|
||||||
|
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||||
|
names.push(String::from_utf8_lossy(reference.name().shorten()).into_owned());
|
||||||
|
}
|
||||||
|
names.sort();
|
||||||
|
Ok(names)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Short names of local branches, `refs/heads/*`, sorted alphabetically.
|
||||||
|
pub fn worktree_branches(workdir: &Path) -> Result<Vec<String>> {
|
||||||
|
repo_branches(&gix::open(workdir)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Short name of the branch HEAD points to, or `None` when detached.
|
||||||
|
///
|
||||||
|
/// Detached after checking out a tag or a commit directly.
|
||||||
|
pub fn current_branch(repo: &gix::Repository) -> Result<Option<String>> {
|
||||||
|
let head = repo.head()?;
|
||||||
|
let Some(name) = head.referent_name() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
Ok(Some(String::from_utf8_lossy(name.shorten()).into_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Branch, tag and HEAD refs of a repository.
|
||||||
|
///
|
||||||
|
/// Ready for a NIP-34 kind-30618 repository state announcement.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct RepoRefState {
|
||||||
|
/// `(full refname, commit id)` pairs for heads and tags, sorted.
|
||||||
|
pub refs: Vec<(String, String)>,
|
||||||
|
/// Short branch name HEAD points to, or `None` when detached.
|
||||||
|
pub head: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collect the refs of `repo`.
|
||||||
|
///
|
||||||
|
/// Local branches and tags become `(refname, commit-id)` pairs.
|
||||||
|
/// Also reports the branch HEAD points to.
|
||||||
|
pub fn repo_ref_state(repo: &gix::Repository) -> Result<RepoRefState> {
|
||||||
|
let mut refs = Vec::new();
|
||||||
|
|
||||||
|
for reference in repo.references()?.local_branches()? {
|
||||||
|
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||||
|
refs.push((
|
||||||
|
String::from_utf8_lossy(reference.name().as_bstr()).into_owned(),
|
||||||
|
reference.id().to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
for reference in repo.references()?.tags()? {
|
||||||
|
let reference = reference.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||||
|
refs.push((
|
||||||
|
String::from_utf8_lossy(reference.name().as_bstr()).into_owned(),
|
||||||
|
reference.id().to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
refs.sort();
|
||||||
|
|
||||||
|
let head = match repo.head() {
|
||||||
|
Ok(head) => head
|
||||||
|
.referent_name()
|
||||||
|
.filter(|name| name.as_bstr().starts_with(b"refs/heads/"))
|
||||||
|
.map(|name| String::from_utf8_lossy(name.shorten()).into_owned()),
|
||||||
|
Err(_) => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(RepoRefState { refs, head })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`repo_ref_state`] for the repository at `workdir`.
|
||||||
|
pub fn worktree_ref_state(workdir: &Path) -> Result<RepoRefState> {
|
||||||
|
repo_ref_state(&gix::open(workdir)?)
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use ignore::WalkBuilder;
|
||||||
|
|
||||||
|
/// Maximum directory nesting depth when scanning for local repositories.
|
||||||
|
///
|
||||||
|
/// Pathological trees can't stall the scan.
|
||||||
|
const SCAN_MAX_DEPTH: usize = 12;
|
||||||
|
|
||||||
|
/// Walk `root` recursively and collect the paths of git repositories below it,
|
||||||
|
/// honouring `.gitignore` (and `.ignore`) files.
|
||||||
|
pub fn find_git_repos(root: &Path) -> Vec<PathBuf> {
|
||||||
|
if !root.is_dir() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let walker = WalkBuilder::new(root)
|
||||||
|
.max_depth(Some(SCAN_MAX_DEPTH))
|
||||||
|
// Honour `.gitignore` even when the scan root is not itself a repository.
|
||||||
|
.require_git(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
let mut repos: Vec<PathBuf> = walker
|
||||||
|
.flatten()
|
||||||
|
.filter(|entry| entry.file_type().is_some_and(|kind| kind.is_dir()))
|
||||||
|
.map(ignore::DirEntry::into_path)
|
||||||
|
.filter(|dir| dir.join(".git").exists())
|
||||||
|
.filter_map(|dir| dir.canonicalize().ok())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
repos.sort();
|
||||||
|
repos.dedup();
|
||||||
|
|
||||||
|
// A repository nested inside another, like a submodule worktree, is not reported.
|
||||||
|
let mut roots: Vec<PathBuf> = Vec::with_capacity(repos.len());
|
||||||
|
for repo in repos {
|
||||||
|
if !roots.iter().any(|kept| repo.starts_with(kept)) {
|
||||||
|
roots.push(repo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
roots
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,354 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use gix::progress::Discard;
|
||||||
|
|
||||||
|
use crate::history::{FileCommit, head_commit};
|
||||||
|
use crate::repo::{current_branch, repository_signature};
|
||||||
|
|
||||||
|
/// Whether the worktree of `workdir` has uncommitted changes.
|
||||||
|
///
|
||||||
|
/// Best-effort: any read failure is reported as clean.
|
||||||
|
pub fn worktree_dirty(workdir: &Path) -> bool {
|
||||||
|
let Ok(repo) = gix::open(workdir) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Changes to tracked files, staged or not; untracked files are excluded.
|
||||||
|
match repo.is_dirty() {
|
||||||
|
Ok(true) => return true,
|
||||||
|
Ok(false) => {}
|
||||||
|
Err(_) => return false,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Untracked files surface as `DirectoryContents` items of the index-vs-worktree walk,
|
||||||
|
// tracked files only appear there when modified.
|
||||||
|
let Ok(platform) = repo.status(Discard) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(mut changes) = platform.into_index_worktree_iter(Vec::<gix::bstr::BString>::new())
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
for change in changes.by_ref() {
|
||||||
|
match change {
|
||||||
|
Ok(gix::status::index_worktree::Item::DirectoryContents { .. }) => return true,
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(_) => return false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commits in `base..branch` of the checkout at `workdir`.
|
||||||
|
///
|
||||||
|
/// Best-effort: 0 when the range cannot be computed.
|
||||||
|
pub fn worktree_commits_ahead(workdir: &Path, base: &str, branch: &str) -> u32 {
|
||||||
|
let Ok(repo) = gix::open(workdir) else {
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
let (Some(base), Some(branch)) = (resolve_commit(&repo, base), resolve_commit(&repo, branch))
|
||||||
|
else {
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(walk) = repo.rev_walk([branch]).with_hidden([base]).all() else {
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
walk.filter_map(Result::ok).count().min(u32::MAX as usize) as u32
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve `rev` to a commit id, accepting full refs,
|
||||||
|
/// symbolic refs and the bare branch names callers pass, like git's DWIM.
|
||||||
|
fn resolve_commit<'a>(repo: &'a gix::Repository, rev: &str) -> Option<gix::Id<'a>> {
|
||||||
|
if let Ok(id) = repo.rev_parse_single(rev.as_bytes()) {
|
||||||
|
return Some(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Branch names arrive bare, like git resolving `main`.
|
||||||
|
if rev.contains('/') {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
repo.rev_parse_single(format!("refs/heads/{rev}").as_bytes())
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Relative paths of all entries in the worktree, files and directories.
|
||||||
|
///
|
||||||
|
/// The `.git` directory is skipped.
|
||||||
|
pub fn worktree_entries(repo: &gix::Repository) -> Result<Vec<PathBuf>> {
|
||||||
|
let workdir = repo.workdir().context("repository has no worktree")?;
|
||||||
|
|
||||||
|
let mut entries: Vec<(PathBuf, bool)> = Vec::new();
|
||||||
|
collect_entries(workdir, workdir, &mut entries)?;
|
||||||
|
|
||||||
|
entries.sort_by(|(a, a_is_dir), (b, b_is_dir)| {
|
||||||
|
b_is_dir
|
||||||
|
.cmp(a_is_dir)
|
||||||
|
.then_with(|| a.as_os_str().cmp(b.as_os_str()))
|
||||||
|
});
|
||||||
|
Ok(entries.into_iter().map(|(path, _)| path).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read a file from the worktree.
|
||||||
|
///
|
||||||
|
/// Returns `Ok(None)` if the path is missing or not a regular file.
|
||||||
|
pub fn worktree_read(repo: &gix::Repository, rel: &Path) -> Result<Option<Vec<u8>>> {
|
||||||
|
let workdir = repo.workdir().context("repository has no worktree")?;
|
||||||
|
let path = workdir.join(rel);
|
||||||
|
|
||||||
|
match std::fs::read(&path) {
|
||||||
|
Ok(bytes) => Ok(Some(bytes)),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::IsADirectory => Ok(None),
|
||||||
|
Err(e) => Err(e).with_context(|| format!("failed to read {}", path.display())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find the README file in the repository root.
|
||||||
|
///
|
||||||
|
/// Falls back to any other file whose name starts with `readme`.
|
||||||
|
pub fn find_readme(repo: &gix::Repository) -> Result<Option<PathBuf>> {
|
||||||
|
let Some(workdir) = repo.workdir() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut candidates: Vec<PathBuf> = Vec::new();
|
||||||
|
for entry in std::fs::read_dir(workdir)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let name = entry.file_name();
|
||||||
|
let Some(name) = name.to_str() else { continue };
|
||||||
|
if name.to_ascii_lowercase().starts_with("readme") {
|
||||||
|
candidates.push(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
candidates.sort_by_key(|path| {
|
||||||
|
let ext = path
|
||||||
|
.extension()
|
||||||
|
.map(|e| e.to_string_lossy().to_ascii_lowercase());
|
||||||
|
match ext.as_deref() {
|
||||||
|
Some("md") => 0,
|
||||||
|
Some("markdown") => 1,
|
||||||
|
Some("mdown") => 2,
|
||||||
|
Some("mkdn") => 3,
|
||||||
|
Some(_) => 5,
|
||||||
|
None => 4,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(candidates
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.and_then(|path| path.strip_prefix(workdir).ok().map(Path::to_path_buf)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything the browser needs to refresh after a branch or tag switch.
|
||||||
|
pub struct WorktreeSnapshot {
|
||||||
|
/// Relative paths of all worktree entries, directories first.
|
||||||
|
pub entries: Vec<PathBuf>,
|
||||||
|
/// README path relative to the worktree, if any.
|
||||||
|
pub readme_path: Option<PathBuf>,
|
||||||
|
/// Contents of the README, if any.
|
||||||
|
pub readme: Option<Vec<u8>>,
|
||||||
|
/// Branch HEAD points to, `None` when detached, for example on a tag.
|
||||||
|
pub current_branch: Option<String>,
|
||||||
|
/// Commit HEAD points to, if any, see [`head_commit`].
|
||||||
|
pub head_commit: Option<FileCommit>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshot the worktree after a branch or tag switch.
|
||||||
|
///
|
||||||
|
/// Collects entries, the README, the branch HEAD points to and its commit.
|
||||||
|
pub fn worktree_snapshot(workdir: &Path) -> Result<WorktreeSnapshot> {
|
||||||
|
let repo = gix::open(workdir)?;
|
||||||
|
let readme_path = find_readme(&repo)?;
|
||||||
|
let readme = match &readme_path {
|
||||||
|
Some(path) => worktree_read(&repo, path)?,
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
Ok(WorktreeSnapshot {
|
||||||
|
entries: worktree_entries(&repo)?,
|
||||||
|
readme_path,
|
||||||
|
readme,
|
||||||
|
current_branch: current_branch(&repo)?,
|
||||||
|
head_commit: head_commit(&repo)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check out `tree` into the worktree of `repo`
|
||||||
|
pub(crate) fn force_checkout(repo: &gix::Repository, tree: &gix::hash::oid) -> Result<()> {
|
||||||
|
let workdir = repo
|
||||||
|
.workdir()
|
||||||
|
.context("repository has no worktree")?
|
||||||
|
.to_path_buf();
|
||||||
|
|
||||||
|
let mut index = repo.index_from_tree(tree)?;
|
||||||
|
|
||||||
|
// Files the previous index tracked but `tree` no longer contains are removed,
|
||||||
|
// like git deleting files that vanish between branches.
|
||||||
|
if let Ok(previous) = repo.index_or_empty() {
|
||||||
|
let keep: HashSet<PathBuf> = index
|
||||||
|
.entries()
|
||||||
|
.iter()
|
||||||
|
.map(|entry| PathBuf::from(String::from_utf8_lossy(entry.path(&index)).into_owned()))
|
||||||
|
.collect();
|
||||||
|
for entry in previous.entries() {
|
||||||
|
let rel = entry.path(&previous);
|
||||||
|
let rel = PathBuf::from(String::from_utf8_lossy(rel).into_owned());
|
||||||
|
|
||||||
|
if keep.contains(&rel) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let path = workdir.join(&rel);
|
||||||
|
|
||||||
|
match std::fs::remove_file(&path) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||||
|
Err(error) => {
|
||||||
|
return Err(error)
|
||||||
|
.with_context(|| format!("failed to remove {}", path.display()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut options =
|
||||||
|
repo.checkout_options(gix_worktree::stack::state::attributes::Source::IdMapping)?;
|
||||||
|
options.overwrite_existing = true;
|
||||||
|
|
||||||
|
let objects = repo.objects.clone().into_arc()?;
|
||||||
|
let files = gix::progress::Discard;
|
||||||
|
let bytes = gix::progress::Discard;
|
||||||
|
|
||||||
|
// Check out the index into the worktree.
|
||||||
|
gix_worktree_state::checkout(
|
||||||
|
&mut index,
|
||||||
|
workdir,
|
||||||
|
objects,
|
||||||
|
&files,
|
||||||
|
&bytes,
|
||||||
|
&gix::interrupt::IS_INTERRUPTED,
|
||||||
|
options,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Write the index to disk.
|
||||||
|
index.write(gix::index::write::Options::default())?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Point `HEAD` at `target` and record the switch in the reflog.
|
||||||
|
fn move_head(
|
||||||
|
repo: &gix::Repository,
|
||||||
|
signature: gix::actor::SignatureRef<'_>,
|
||||||
|
target: gix::refs::Target,
|
||||||
|
message: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
use gix::refs::transaction::{Change, LogChange, PreviousValue, RefEdit, RefLog};
|
||||||
|
|
||||||
|
let head = gix::refs::FullName::try_from("HEAD")
|
||||||
|
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?;
|
||||||
|
|
||||||
|
// Update the reference, creating a reflog entry.
|
||||||
|
repo.edit_references_as(
|
||||||
|
[RefEdit {
|
||||||
|
change: Change::Update {
|
||||||
|
log: LogChange {
|
||||||
|
mode: RefLog::AndReference,
|
||||||
|
force_create_reflog: false,
|
||||||
|
message: message.into(),
|
||||||
|
},
|
||||||
|
expected: PreviousValue::Any,
|
||||||
|
new: target,
|
||||||
|
},
|
||||||
|
name: head,
|
||||||
|
deref: false,
|
||||||
|
}],
|
||||||
|
Some(signature),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check out the local branch `name`, HEAD stays attached to it.
|
||||||
|
pub fn worktree_checkout_branch(workdir: &Path, name: &str) -> Result<()> {
|
||||||
|
let repo = gix::open(workdir)?;
|
||||||
|
let full = format!("refs/heads/{name}");
|
||||||
|
|
||||||
|
let branch = gix::refs::FullName::try_from(full.as_str())
|
||||||
|
.map_err(|e| anyhow::anyhow!("invalid ref name: {e}"))?;
|
||||||
|
|
||||||
|
let mut reference = repo.find_reference(&full)?;
|
||||||
|
let tree = reference.peel_to_tree()?.id;
|
||||||
|
|
||||||
|
let (signature, mut time_buf) = repository_signature();
|
||||||
|
let signature = signature.to_ref(&mut time_buf);
|
||||||
|
|
||||||
|
// Move HEAD to the branch, creating a reflog entry.
|
||||||
|
move_head(
|
||||||
|
&repo,
|
||||||
|
signature,
|
||||||
|
gix::refs::Target::Symbolic(branch),
|
||||||
|
&format!("checkout: moving to {name}"),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Check out the branch's tree, replacing index + worktree.
|
||||||
|
force_checkout(&repo, &tree)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check out the tag `name`, HEAD becomes detached at the tagged commit.
|
||||||
|
pub fn worktree_checkout_tag(workdir: &Path, name: &str) -> Result<()> {
|
||||||
|
let repo = gix::open(workdir)?;
|
||||||
|
let full = format!("refs/tags/{name}");
|
||||||
|
|
||||||
|
let mut reference = repo.find_reference(&full)?;
|
||||||
|
|
||||||
|
let commit = reference.peel_to_id()?;
|
||||||
|
let tree = reference.peel_to_tree()?.id;
|
||||||
|
|
||||||
|
let (signature, mut time_buf) = repository_signature();
|
||||||
|
let signature = signature.to_ref(&mut time_buf);
|
||||||
|
|
||||||
|
// Move HEAD to the tag, creating a reflog entry.
|
||||||
|
move_head(
|
||||||
|
&repo,
|
||||||
|
signature,
|
||||||
|
gix::refs::Target::Object(commit.detach()),
|
||||||
|
&format!("checkout: moving to {name}"),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Check out the tag's tree, replacing index + worktree.
|
||||||
|
force_checkout(&repo, &tree)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_entries(root: &Path, dir: &Path, out: &mut Vec<(PathBuf, bool)>) -> Result<()> {
|
||||||
|
for entry in std::fs::read_dir(dir)? {
|
||||||
|
let entry = entry?;
|
||||||
|
if entry.file_name() == ".git" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let is_dir = entry.file_type()?.is_dir();
|
||||||
|
let path = entry.path();
|
||||||
|
let rel = path.strip_prefix(root)?.to_path_buf();
|
||||||
|
out.push((rel, is_dir));
|
||||||
|
|
||||||
|
if is_dir {
|
||||||
|
collect_entries(root, &path, out)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
+293
-390
File diff suppressed because it is too large
Load Diff
@@ -3,16 +3,15 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task};
|
use gpui::{App, AppContext, Context, Entity, Global, Subscription};
|
||||||
use nostr::prelude::*;
|
use nostr::prelude::*;
|
||||||
use settings::{CheckoutRecord, SettingsStore};
|
use settings::{CheckoutRecord, SettingsStore};
|
||||||
use signed_core::{Announcement, RepoAddr};
|
use signed_core::{Announcement, RepoAddr};
|
||||||
|
|
||||||
use crate::backend::{Backend, BackendEvent};
|
use crate::backend::{Backend, BackendEvent};
|
||||||
use crate::git_store::GitStore;
|
use crate::git_store::GitStore;
|
||||||
use crate::local_repos::LocalReposStore;
|
|
||||||
use crate::refresh::{RefreshGate, RefreshRequest};
|
use crate::refresh::{RefreshGate, RefreshRequest};
|
||||||
use crate::repo_list::RepoListStore;
|
use crate::repos::{LocalReposStore, RepoListStore};
|
||||||
|
|
||||||
/// Delay between a refresh request and the actual re-computation.
|
/// Delay between a refresh request and the actual re-computation.
|
||||||
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
||||||
@@ -105,7 +104,6 @@ pub struct CheckoutsStore {
|
|||||||
/// The local pass runs a full pass again once this is older than the
|
/// The local pass runs a full pass again once this is older than the
|
||||||
/// reconciliation cadence, so remote moves still land.
|
/// reconciliation cadence, so remote moves still land.
|
||||||
last_full_sync: Option<Instant>,
|
last_full_sync: Option<Instant>,
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
|
||||||
_subscriptions: Vec<Subscription>,
|
_subscriptions: Vec<Subscription>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,7 +153,16 @@ impl CheckoutsStore {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut store = Self {
|
if !cfg!(target_arch = "wasm32") {
|
||||||
|
let weak = cx.entity().downgrade();
|
||||||
|
cx.defer(move |cx| {
|
||||||
|
if let Err(error) = weak.update(cx, |this, cx| this.refresh(cx)) {
|
||||||
|
log::warn!("checkouts store dropped before initial refresh could run: {error}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Self {
|
||||||
by_repo: HashMap::new(),
|
by_repo: HashMap::new(),
|
||||||
statuses: HashMap::new(),
|
statuses: HashMap::new(),
|
||||||
status_requested: HashSet::new(),
|
status_requested: HashSet::new(),
|
||||||
@@ -165,23 +172,8 @@ impl CheckoutsStore {
|
|||||||
refresh: RefreshGate::default(),
|
refresh: RefreshGate::default(),
|
||||||
local_pending: false,
|
local_pending: false,
|
||||||
last_full_sync: None,
|
last_full_sync: None,
|
||||||
tasks: Vec::new(),
|
|
||||||
_subscriptions: subscriptions,
|
_subscriptions: subscriptions,
|
||||||
};
|
|
||||||
|
|
||||||
if !cfg!(target_arch = "wasm32") {
|
|
||||||
store.refresh(cx);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
store
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Track a spawned task, pruning finished tasks first.
|
|
||||||
///
|
|
||||||
/// Keeps the store's task list bounded by the number of in-flight tasks.
|
|
||||||
fn push_task(&mut self, task: Task<Result<(), Error>>) {
|
|
||||||
self.tasks.retain(|task| !task.is_ready());
|
|
||||||
self.tasks.push(task);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remember a successful local-checkout use.
|
/// Remember a successful local-checkout use.
|
||||||
@@ -302,12 +294,11 @@ impl CheckoutsStore {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let task = cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
|
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
|
||||||
this.update(cx, |this, cx| this.run_refresh(cx))
|
this.update(cx, |this, cx| this.run_refresh(cx))
|
||||||
});
|
})
|
||||||
|
.detach();
|
||||||
self.push_task(task);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One full resolve and apply cycle, the debounced entry point.
|
/// One full resolve and apply cycle, the debounced entry point.
|
||||||
@@ -388,7 +379,7 @@ impl CheckoutsStore {
|
|||||||
Ok::<_, Error>((associations, statuses, push_statuses))
|
Ok::<_, Error>((associations, statuses, push_statuses))
|
||||||
});
|
});
|
||||||
|
|
||||||
self.push_task(cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
let (associations, statuses, push_statuses) = match work.await {
|
let (associations, statuses, push_statuses) = match work.await {
|
||||||
Ok(results) => results,
|
Ok(results) => results,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
@@ -435,7 +426,8 @@ impl CheckoutsStore {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
})
|
||||||
|
.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Schedule the fast local status pass, unless one is already pending.
|
/// Schedule the fast local status pass, unless one is already pending.
|
||||||
@@ -449,15 +441,14 @@ impl CheckoutsStore {
|
|||||||
}
|
}
|
||||||
self.local_pending = true;
|
self.local_pending = true;
|
||||||
|
|
||||||
let task = cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
cx.background_executor().timer(LOCAL_POLL).await;
|
cx.background_executor().timer(LOCAL_POLL).await;
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.local_pending = false;
|
this.local_pending = false;
|
||||||
this.local_tick(cx);
|
this.local_tick(cx);
|
||||||
})
|
})
|
||||||
});
|
})
|
||||||
|
.detach();
|
||||||
self.push_task(task);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The fast local status pass.
|
/// The fast local status pass.
|
||||||
@@ -525,7 +516,7 @@ impl CheckoutsStore {
|
|||||||
Ok::<_, Error>((statuses, push_statuses))
|
Ok::<_, Error>((statuses, push_statuses))
|
||||||
});
|
});
|
||||||
|
|
||||||
self.push_task(cx.spawn(async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let Ok((statuses, push_statuses)) = work.await else {
|
let Ok((statuses, push_statuses)) = work.await else {
|
||||||
// Git reads are best-effort, keep the last results.
|
// Git reads are best-effort, keep the last results.
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -550,7 +541,8 @@ impl CheckoutsStore {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
});
|
||||||
|
task.detach();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
mod backend;
|
mod backend;
|
||||||
mod checkouts;
|
mod checkouts;
|
||||||
mod git_store;
|
mod git_store;
|
||||||
mod local_repos;
|
|
||||||
mod profile;
|
mod profile;
|
||||||
mod refresh;
|
mod refresh;
|
||||||
mod repo;
|
mod repo;
|
||||||
mod repo_list;
|
mod repos;
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
@@ -13,11 +12,10 @@ pub use backend::{Backend, BackendEvent, user_grasp_list_servers};
|
|||||||
pub use checkouts::{CheckoutStatus, CheckoutsStore, pr_proposes_checkout};
|
pub use checkouts::{CheckoutStatus, CheckoutsStore, pr_proposes_checkout};
|
||||||
pub use git_store::GitStore;
|
pub use git_store::GitStore;
|
||||||
use gpui::{App, AppContext, Entity};
|
use gpui::{App, AppContext, Entity};
|
||||||
pub use local_repos::LocalReposStore;
|
|
||||||
pub use nostr_sdk::prelude::Timestamp;
|
pub use nostr_sdk::prelude::Timestamp;
|
||||||
pub use profile::{Profile, ProfileStore};
|
pub use profile::{Profile, ProfileStore};
|
||||||
pub use repo::RepoStore;
|
pub use repo::RepoStore;
|
||||||
pub use repo_list::{RepoActivityCounts, RepoListStore};
|
pub use repos::{LocalReposStore, RepoActivityCounts, RepoListStore};
|
||||||
use signed_nostr::new_backend;
|
use signed_nostr::new_backend;
|
||||||
|
|
||||||
/// Initialize the backend and stores, and install them as globals.
|
/// Initialize the backend and stores, and install them as globals.
|
||||||
|
|||||||
@@ -1,104 +0,0 @@
|
|||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use anyhow::Error;
|
|
||||||
use gpui::{App, AppContext, Context, Entity, Global, Task};
|
|
||||||
use signed_git::find_git_repos;
|
|
||||||
|
|
||||||
struct GlobalLocalReposStore(Entity<LocalReposStore>);
|
|
||||||
|
|
||||||
impl Global for GlobalLocalReposStore {}
|
|
||||||
|
|
||||||
/// Store of the git repositories discovered under a set of scan paths.
|
|
||||||
pub struct LocalReposStore {
|
|
||||||
/// The directories being scanned.
|
|
||||||
pub roots: Arc<Vec<PathBuf>>,
|
|
||||||
/// Git repositories discovered under [`Self::roots`], sorted by path.
|
|
||||||
pub repos: Arc<Vec<PathBuf>>,
|
|
||||||
/// A scan is currently running.
|
|
||||||
pub scanning: bool,
|
|
||||||
/// A scan was requested while one was already running.
|
|
||||||
scan_dirty: bool,
|
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LocalReposStore {
|
|
||||||
/// Retrieve the global local-repositories store.
|
|
||||||
pub fn global(cx: &App) -> Entity<Self> {
|
|
||||||
cx.global::<GlobalLocalReposStore>().0.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn set_global(entity: Entity<Self>, cx: &mut App) {
|
|
||||||
cx.set_global(GlobalLocalReposStore(entity));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a store scanning `roots` right away.
|
|
||||||
pub fn new(roots: Vec<PathBuf>, cx: &mut Context<Self>) -> Self {
|
|
||||||
let mut store = Self {
|
|
||||||
roots: Arc::new(roots),
|
|
||||||
repos: Arc::new(Vec::new()),
|
|
||||||
scanning: false,
|
|
||||||
scan_dirty: false,
|
|
||||||
tasks: Vec::new(),
|
|
||||||
};
|
|
||||||
store.rescan(cx);
|
|
||||||
store
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Forget a repository that has just been published to NIP-34.
|
|
||||||
pub fn remove(&mut self, path: &Path, cx: &mut Context<Self>) {
|
|
||||||
self.repos = Arc::new(
|
|
||||||
self.repos
|
|
||||||
.iter()
|
|
||||||
.filter(|repo| repo.as_path() != path)
|
|
||||||
.cloned()
|
|
||||||
.collect(),
|
|
||||||
);
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Re-run the scan.
|
|
||||||
pub fn rescan(&mut self, cx: &mut Context<Self>) {
|
|
||||||
if self.scanning {
|
|
||||||
self.scan_dirty = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if self.roots.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.scanning = true;
|
|
||||||
cx.notify();
|
|
||||||
|
|
||||||
let roots = self.roots.clone();
|
|
||||||
let work = cx.background_spawn(async move {
|
|
||||||
let mut repos = Vec::new();
|
|
||||||
for root in roots.iter() {
|
|
||||||
repos.extend(find_git_repos(root));
|
|
||||||
}
|
|
||||||
repos.sort();
|
|
||||||
repos.dedup();
|
|
||||||
repos
|
|
||||||
});
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
let repos = work.await;
|
|
||||||
let again = this.update(cx, |this, cx| {
|
|
||||||
this.repos = Arc::new(repos);
|
|
||||||
this.scanning = false;
|
|
||||||
cx.notify();
|
|
||||||
|
|
||||||
let dirty = this.scan_dirty;
|
|
||||||
this.scan_dirty = false;
|
|
||||||
dirty
|
|
||||||
})?;
|
|
||||||
|
|
||||||
// Scans requested while this one ran are coalesced into one follow-up scan.
|
|
||||||
if again {
|
|
||||||
this.update(cx, |this, cx| this.rescan(cx))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -75,7 +75,6 @@ pub struct ProfileStore {
|
|||||||
seen: RefCell<HashSet<PublicKey>>,
|
seen: RefCell<HashSet<PublicKey>>,
|
||||||
/// Sender for queuing fetch requests, batched by a background task.
|
/// Sender for queuing fetch requests, batched by a background task.
|
||||||
sender: Sender<PublicKey>,
|
sender: Sender<PublicKey>,
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
|
||||||
_subscription: Subscription,
|
_subscription: Subscription,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,9 +96,14 @@ impl ProfileStore {
|
|||||||
let backend = Backend::global(cx);
|
let backend = Backend::global(cx);
|
||||||
|
|
||||||
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| match event {
|
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| match event {
|
||||||
BackendEvent::NostrUpdate(update) if update.kind == Kind::Metadata => {
|
BackendEvent::NostrUpdate(updates) => {
|
||||||
|
for update in updates
|
||||||
|
.iter()
|
||||||
|
.filter(|update| update.kind == Kind::Metadata)
|
||||||
|
{
|
||||||
this.apply_author(update.author, cx);
|
this.apply_author(update.author, cx);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
BackendEvent::Published(event) if event.kind == Kind::Metadata => {
|
BackendEvent::Published(event) if event.kind == Kind::Metadata => {
|
||||||
let metadata = Metadata::from_json(&event.content).unwrap_or_default();
|
let metadata = Metadata::from_json(&event.content).unwrap_or_default();
|
||||||
this.profiles
|
this.profiles
|
||||||
@@ -114,30 +118,24 @@ impl ProfileStore {
|
|||||||
let (sender, receiver) = flume::unbounded::<PublicKey>();
|
let (sender, receiver) = flume::unbounded::<PublicKey>();
|
||||||
let entity = cx.entity().downgrade();
|
let entity = cx.entity().downgrade();
|
||||||
|
|
||||||
let mut tasks = Vec::new();
|
cx.spawn(async move |_this, cx| {
|
||||||
|
|
||||||
tasks.push(cx.spawn(async move |_this, cx| {
|
|
||||||
Self::handle_requests(entity, &client, &receiver, cx).await
|
Self::handle_requests(entity, &client, &receiver, cx).await
|
||||||
}));
|
})
|
||||||
|
.detach();
|
||||||
|
|
||||||
let mut store = Self {
|
let weak = cx.entity().downgrade();
|
||||||
|
cx.defer(move |cx| {
|
||||||
|
if let Err(error) = weak.update(cx, |this, cx| this.load(cx)) {
|
||||||
|
log::warn!("profile store dropped before initial load could run: {error}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Self {
|
||||||
profiles: HashMap::new(),
|
profiles: HashMap::new(),
|
||||||
seen: RefCell::new(HashSet::new()),
|
seen: RefCell::new(HashSet::new()),
|
||||||
sender,
|
sender,
|
||||||
tasks,
|
|
||||||
_subscription: subscription,
|
_subscription: subscription,
|
||||||
};
|
|
||||||
|
|
||||||
store.load(cx);
|
|
||||||
store
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Track a spawned task, pruning finished tasks first.
|
|
||||||
///
|
|
||||||
/// Keeps the store's task list bounded by the number of in-flight tasks.
|
|
||||||
fn push_task(&mut self, task: Task<Result<(), Error>>) {
|
|
||||||
self.tasks.retain(|task| !task.is_ready());
|
|
||||||
self.tasks.push(task);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a profile.
|
/// Get a profile.
|
||||||
@@ -181,7 +179,7 @@ impl ProfileStore {
|
|||||||
Ok::<_, Error>(profiles)
|
Ok::<_, Error>(profiles)
|
||||||
});
|
});
|
||||||
|
|
||||||
self.push_task(cx.spawn(async move |this, cx| {
|
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let profiles = work.await?;
|
let profiles = work.await?;
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
@@ -192,7 +190,8 @@ impl ProfileStore {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
});
|
||||||
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-read the latest metadata of an author from the local database.
|
/// Re-read the latest metadata of an author from the local database.
|
||||||
@@ -217,7 +216,7 @@ impl ProfileStore {
|
|||||||
Ok::<_, Error>(profile)
|
Ok::<_, Error>(profile)
|
||||||
});
|
});
|
||||||
|
|
||||||
self.push_task(cx.spawn(async move |this, cx| {
|
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let profile = work.await?;
|
let profile = work.await?;
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
@@ -228,7 +227,8 @@ impl ProfileStore {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
});
|
||||||
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Re-read the latest metadata of every requested author from the local database.
|
/// Re-read the latest metadata of every requested author from the local database.
|
||||||
@@ -273,7 +273,7 @@ impl ProfileStore {
|
|||||||
Ok::<_, Error>(profiles)
|
Ok::<_, Error>(profiles)
|
||||||
});
|
});
|
||||||
|
|
||||||
self.push_task(cx.spawn(async move |this, cx| {
|
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let profiles = work.await?;
|
let profiles = work.await?;
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
@@ -284,7 +284,8 @@ impl ProfileStore {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
});
|
||||||
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sync metadata for requested authors in batches, debounced to collect requests.
|
/// Sync metadata for requested authors in batches, debounced to collect requests.
|
||||||
@@ -337,7 +338,7 @@ impl ProfileStore {
|
|||||||
// Re-apply from the database afterwards.
|
// Re-apply from the database afterwards.
|
||||||
match sync_bootstrap_only(client, filter, SyncOptions::default()).await {
|
match sync_bootstrap_only(client, filter, SyncOptions::default()).await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
let _ = this.update(cx, |this, cx| this.apply_seen(cx));
|
this.update(cx, |this, cx| this.apply_seen(cx)).ok();
|
||||||
}
|
}
|
||||||
Err(e) => log::warn!("profile sync failed: {e}"),
|
Err(e) => log::warn!("profile sync failed: {e}"),
|
||||||
}
|
}
|
||||||
|
|||||||
+179
-60
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::Error;
|
use anyhow::{Error, bail};
|
||||||
use bitcoin_hashes::sha1::Hash as Sha1Hash;
|
use bitcoin_hashes::sha1::Hash as Sha1Hash;
|
||||||
use gpui::{App, AppContext, AsyncApp, Context, SharedString, Subscription, Task, WeakEntity};
|
use gpui::{App, AppContext, AsyncApp, Context, SharedString, Subscription, Task, WeakEntity};
|
||||||
use nostr::event::IntoEventBuilder;
|
use nostr::event::IntoEventBuilder;
|
||||||
@@ -14,12 +14,13 @@ use signed_core::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::backend::{
|
use crate::backend::{
|
||||||
Backend, BackendEvent, grasp_base_url, grasp06_prs_url, pr_clone_urls, user_grasp_list_servers,
|
Backend, BackendEvent, grasp_base_url, grasp06_prs_url, pr_clone_urls, require_relay_accepted,
|
||||||
|
user_grasp_list_servers,
|
||||||
};
|
};
|
||||||
use crate::checkouts::CheckoutsStore;
|
use crate::checkouts::CheckoutsStore;
|
||||||
use crate::git_store::GitStore;
|
use crate::git_store::GitStore;
|
||||||
use crate::refresh::{RefreshGate, RefreshRequest};
|
use crate::refresh::{RefreshGate, RefreshRequest};
|
||||||
use crate::repo_list::RepoListStore;
|
use crate::repos::RepoListStore;
|
||||||
|
|
||||||
/// Delay between a refresh request and the actual re-query.
|
/// Delay between a refresh request and the actual re-query.
|
||||||
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
||||||
@@ -81,7 +82,6 @@ pub struct RepoStore {
|
|||||||
root_fetches: HashSet<EventId>,
|
root_fetches: HashSet<EventId>,
|
||||||
/// Refresh coalescing, see [`RefreshGate`].
|
/// Refresh coalescing, see [`RefreshGate`].
|
||||||
refresh: RefreshGate,
|
refresh: RefreshGate,
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
|
||||||
_subscription: Subscription,
|
_subscription: Subscription,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,7 +91,7 @@ impl RepoStore {
|
|||||||
|
|
||||||
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
|
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
|
||||||
let relevant = match event {
|
let relevant = match event {
|
||||||
BackendEvent::NostrUpdate(update) => {
|
BackendEvent::NostrUpdate(updates) => updates.iter().any(|update| {
|
||||||
// Deletions may target any event of this repository.
|
// Deletions may target any event of this repository.
|
||||||
let deletion =
|
let deletion =
|
||||||
update.kind == Kind::EventDeletion || update.kind == Kind::RequestToVanish;
|
update.kind == Kind::EventDeletion || update.kind == Kind::RequestToVanish;
|
||||||
@@ -107,7 +107,7 @@ impl RepoStore {
|
|||||||
let status = RepoStatus::from_kind(update.kind).is_some();
|
let status = RepoStatus::from_kind(update.kind).is_some();
|
||||||
|
|
||||||
deletion || coordinate || (author && kind) || comment || status
|
deletion || coordinate || (author && kind) || comment || status
|
||||||
}
|
}),
|
||||||
BackendEvent::Published(event) => {
|
BackendEvent::Published(event) => {
|
||||||
let kind = event.kind == Kind::GitRepoAnnouncement;
|
let kind = event.kind == Kind::GitRepoAnnouncement;
|
||||||
let author = event.pubkey == this.addr.public_key;
|
let author = event.pubkey == this.addr.public_key;
|
||||||
@@ -127,7 +127,20 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut store = Self {
|
let weak = cx.entity().downgrade();
|
||||||
|
cx.defer(move |cx| {
|
||||||
|
let result = weak.update(cx, |this, cx| {
|
||||||
|
this.subscribe_remote(cx);
|
||||||
|
this.connect_announced_relays(&announced_relays, cx);
|
||||||
|
this.refresh(cx);
|
||||||
|
});
|
||||||
|
|
||||||
|
if let Err(error) = result {
|
||||||
|
log::warn!("repo store dropped before bootstrap could run: {error}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Self {
|
||||||
addr,
|
addr,
|
||||||
announcement: None,
|
announcement: None,
|
||||||
head: None,
|
head: None,
|
||||||
@@ -148,16 +161,7 @@ impl RepoStore {
|
|||||||
root_fetches: HashSet::new(),
|
root_fetches: HashSet::new(),
|
||||||
refresh: RefreshGate::default(),
|
refresh: RefreshGate::default(),
|
||||||
_subscription: subscription,
|
_subscription: subscription,
|
||||||
tasks: Vec::new(),
|
}
|
||||||
};
|
|
||||||
|
|
||||||
store.subscribe_remote(cx);
|
|
||||||
// The announcement we opened the repo from may already list its relays.
|
|
||||||
// Connect to them right away.
|
|
||||||
// Do not wait for the bootstrap fetch to return the same event.
|
|
||||||
store.connect_announced_relays(&announced_relays, cx);
|
|
||||||
store.refresh(cx);
|
|
||||||
store
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the repository's address.
|
/// Returns the repository's address.
|
||||||
@@ -229,14 +233,12 @@ impl RepoStore {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let task = cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
|
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
|
||||||
|
|
||||||
this.update(cx, |this, cx| this.run_refresh(cx))
|
this.update(cx, |this, cx| this.run_refresh(cx))
|
||||||
});
|
})
|
||||||
|
.detach();
|
||||||
self.tasks.retain(|task| !task.is_ready());
|
|
||||||
self.tasks.push(task);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_refresh(&mut self, cx: &mut Context<Self>) {
|
fn run_refresh(&mut self, cx: &mut Context<Self>) {
|
||||||
@@ -372,9 +374,7 @@ impl RepoStore {
|
|||||||
))
|
))
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.retain(|task| !task.is_ready());
|
cx.spawn(async move |this, cx| {
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
let (
|
let (
|
||||||
announcement,
|
announcement,
|
||||||
state,
|
state,
|
||||||
@@ -466,7 +466,8 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
})
|
||||||
|
.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve the status of a root event, an issue, patch or PR, per NIP-34.
|
/// Resolve the status of a root event, an issue, patch or PR, per NIP-34.
|
||||||
@@ -514,7 +515,7 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
.into_event_builder();
|
.into_event_builder();
|
||||||
|
|
||||||
self.send(builder, cx);
|
self.publish(builder, cx);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Comments on a root event, an issue or PR, oldest first.
|
/// Comments on a root event, an issue or PR, oldest first.
|
||||||
@@ -545,7 +546,7 @@ impl RepoStore {
|
|||||||
.and_then(|a| a.relays.first())
|
.and_then(|a| a.relays.first())
|
||||||
.cloned();
|
.cloned();
|
||||||
|
|
||||||
self.send(
|
self.publish(
|
||||||
comment_builder(root, parent, relay_hint.as_ref(), &self.addr, content),
|
comment_builder(root, parent, relay_hint.as_ref(), &self.addr, content),
|
||||||
cx,
|
cx,
|
||||||
);
|
);
|
||||||
@@ -638,7 +639,7 @@ impl RepoStore {
|
|||||||
.collect()
|
.collect()
|
||||||
};
|
};
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
// The PR references the root patch event.
|
// The PR references the root patch event.
|
||||||
// Viewers can then find the patch without carrying it inline.
|
// Viewers can then find the patch without carrying it inline.
|
||||||
let root_patch = match publish_patch_series(
|
let root_patch = match publish_patch_series(
|
||||||
@@ -798,12 +799,15 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let publish_task = this.update(cx, |_this, cx| {
|
let client = this.update(cx, |_this, cx| Backend::global(cx).read(cx).client())?;
|
||||||
let backend = Backend::global(cx);
|
|
||||||
backend.update(cx, |backend, cx| backend.publish_event(event, cx))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let pr_event = match publish_task.await {
|
let publish_result: Result<Event, Error> = async {
|
||||||
|
let output = client.send_event(&event).broadcast().await?;
|
||||||
|
require_relay_accepted(output, event)
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let pr_event = match publish_result {
|
||||||
Ok(event) => event,
|
Ok(event) => event,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return this.update(cx, |this, cx| {
|
return this.update(cx, |this, cx| {
|
||||||
@@ -813,6 +817,11 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
this.update(cx, |_this, cx| {
|
||||||
|
Backend::global(cx)
|
||||||
|
.update(cx, |backend, cx| backend.announce_published(pr_event.clone(), cx))
|
||||||
|
})?;
|
||||||
|
|
||||||
// A draft PR carries a kind-1633 status event, NIP-34.
|
// A draft PR carries a kind-1633 status event, NIP-34.
|
||||||
// Publish it right after the PR event so viewers never show it open.
|
// Publish it right after the PR event so viewers never show it open.
|
||||||
if draft {
|
if draft {
|
||||||
@@ -822,7 +831,61 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
})
|
||||||
|
.detach();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate the patch between `merge_base` and `compare_ref` in `repo_path`,
|
||||||
|
/// then open a pull request from it.
|
||||||
|
///
|
||||||
|
/// Fails descriptively when there are no commits to propose or the patch
|
||||||
|
/// could not be generated; otherwise publishes exactly like
|
||||||
|
/// [`Self::open_pull_request`].
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn open_pull_request_from_refs(
|
||||||
|
&mut self,
|
||||||
|
repo_path: PathBuf,
|
||||||
|
merge_base: String,
|
||||||
|
compare_ref: String,
|
||||||
|
subject: Option<String>,
|
||||||
|
description: String,
|
||||||
|
branch_name: Option<String>,
|
||||||
|
draft: bool,
|
||||||
|
cx: &mut Context<Self>,
|
||||||
|
) -> Task<Result<(), Error>> {
|
||||||
|
cx.spawn(async move |this, cx| {
|
||||||
|
// Regenerate the series at submit time.
|
||||||
|
// The published patch covers the current tip of the compare branch.
|
||||||
|
let patch = cx
|
||||||
|
.background_spawn({
|
||||||
|
let repo_path = repo_path.clone();
|
||||||
|
let merge_base = merge_base.clone();
|
||||||
|
let compare_ref = compare_ref.clone();
|
||||||
|
async move {
|
||||||
|
signed_git::format_patch_between(&repo_path, &merge_base, &compare_ref)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let patch = match patch {
|
||||||
|
Ok(patch) if !patch.is_empty() => patch,
|
||||||
|
Ok(_) => bail!("No commits between the branches to propose"),
|
||||||
|
Err(error) => bail!("Failed to generate the patch: {error}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.update(cx, |this, cx| {
|
||||||
|
this.open_pull_request(
|
||||||
|
subject,
|
||||||
|
description,
|
||||||
|
branch_name,
|
||||||
|
patch,
|
||||||
|
draft,
|
||||||
|
Some(merge_base),
|
||||||
|
Some(repo_path),
|
||||||
|
cx,
|
||||||
|
);
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update a pull request.
|
/// Update a pull request.
|
||||||
@@ -894,7 +957,7 @@ impl RepoStore {
|
|||||||
.map(|a| a.clone.clone())
|
.map(|a| a.clone.clone())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
if let Err(e) = publish_patch_series(
|
if let Err(e) = publish_patch_series(
|
||||||
&this,
|
&this,
|
||||||
cx,
|
cx,
|
||||||
@@ -913,7 +976,7 @@ impl RepoStore {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let update_task = this.update(cx, |this, cx| {
|
let builder = this.update(cx, |this, _cx| {
|
||||||
let builder = GitPullRequestUpdate {
|
let builder = GitPullRequestUpdate {
|
||||||
repository: this.addr.clone(),
|
repository: this.addr.clone(),
|
||||||
pull_request_event: root.id,
|
pull_request_event: root.id,
|
||||||
@@ -926,24 +989,44 @@ impl RepoStore {
|
|||||||
|
|
||||||
// The `r` EUC tag lets clients subscribe to all PR updates.
|
// The `r` EUC tag lets clients subscribe to all PR updates.
|
||||||
// The SDK builder omits it.
|
// The SDK builder omits it.
|
||||||
let builder = match euc.as_deref() {
|
match euc.as_deref() {
|
||||||
Some(euc) => builder.tag(Tag::parse(["r", euc]).expect("valid r tag")),
|
Some(euc) => builder.tag(Tag::parse(["r", euc]).expect("valid r tag")),
|
||||||
None => builder,
|
None => builder,
|
||||||
};
|
}
|
||||||
|
|
||||||
let backend = Backend::global(cx);
|
|
||||||
backend.update(cx, |backend, cx| backend.send(builder, cx))
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
if let Err(e) = update_task.await {
|
let (client, signer) = this.update(cx, |_this, cx| {
|
||||||
|
let backend = Backend::global(cx);
|
||||||
|
let backend = backend.read(cx);
|
||||||
|
(backend.client(), backend.signer())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let publish_result: Result<Event, Error> = async {
|
||||||
|
let event = builder.finalize_async(&signer).await?;
|
||||||
|
let output = client.send_event(&event).broadcast().await?;
|
||||||
|
require_relay_accepted(output, event)
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match publish_result {
|
||||||
|
Ok(event) => {
|
||||||
|
this.update(cx, |_this, cx| {
|
||||||
|
Backend::global(cx).update(cx, |backend, cx| {
|
||||||
|
backend.announce_published(event.clone(), cx)
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
return this.update(cx, |this, cx| {
|
return this.update(cx, |this, cx| {
|
||||||
this.last_error = Some(e.to_string());
|
this.last_error = Some(e.to_string());
|
||||||
cx.notify();
|
cx.notify();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
})
|
||||||
|
.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the status of a root event.
|
/// Set the status of a root event.
|
||||||
@@ -982,7 +1065,7 @@ impl RepoStore {
|
|||||||
Tag::coordinate(self.addr.clone(), None),
|
Tag::coordinate(self.addr.clone(), None),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
self.send(builder, cx);
|
self.publish(builder, cx);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Merge a pull request.
|
/// Merge a pull request.
|
||||||
@@ -1002,10 +1085,10 @@ impl RepoStore {
|
|||||||
let cache = GitStore::global(cx).cache().clone();
|
let cache = GitStore::global(cx).cache().clone();
|
||||||
let addr = self.addr.clone();
|
let addr = self.addr.clone();
|
||||||
|
|
||||||
let clone_urls: Vec<String> = self
|
let clone_urls: Vec<Url> = self
|
||||||
.announcement
|
.announcement
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|a| a.clone.iter().map(ToString::to_string).collect())
|
.map(|a| a.clone.clone())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
let patch = pull_request_patch(root, self.patches.iter());
|
let patch = pull_request_patch(root, self.patches.iter());
|
||||||
@@ -1040,7 +1123,7 @@ impl RepoStore {
|
|||||||
Ok::<_, Error>(applied)
|
Ok::<_, Error>(applied)
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
match apply.await {
|
match apply.await {
|
||||||
Ok(applied) => {
|
Ok(applied) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
@@ -1062,7 +1145,8 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
});
|
||||||
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The latest announcement of this repository,
|
/// The latest announcement of this repository,
|
||||||
@@ -1224,7 +1308,7 @@ impl RepoStore {
|
|||||||
return self.action_error("Repository announcement is not loaded yet", cx);
|
return self.action_error("Repository announcement is not loaded yet", cx);
|
||||||
};
|
};
|
||||||
|
|
||||||
let clone_urls: Vec<String> = announcement.clone.iter().map(ToString::to_string).collect();
|
let clone_urls = announcement.clone.clone();
|
||||||
let addr = self.addr.clone();
|
let addr = self.addr.clone();
|
||||||
|
|
||||||
self.cloning = true;
|
self.cloning = true;
|
||||||
@@ -1328,24 +1412,50 @@ impl RepoStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.send(EventBuilder::new(Kind::GitStatusApplied, "").tags(tags), cx);
|
self.publish(EventBuilder::new(Kind::GitStatusApplied, "").tags(tags), cx);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send(&mut self, builder: EventBuilder, cx: &mut Context<Self>) {
|
/// Sign `builder`, broadcast it and track the outcome in [`Self::last_error`].
|
||||||
|
///
|
||||||
|
/// Every one-shot repository event (issue, comment, status) goes through
|
||||||
|
/// this. Multi-step flows (opening or updating a pull request, a patch
|
||||||
|
/// series) call the SDK directly instead, since their error handling and
|
||||||
|
/// post-conditions differ per step.
|
||||||
|
fn publish(&mut self, builder: EventBuilder, cx: &mut Context<Self>) {
|
||||||
self.last_error = None;
|
self.last_error = None;
|
||||||
|
|
||||||
let backend = Backend::global(cx);
|
let backend = Backend::global(cx);
|
||||||
let task = backend.update(cx, |backend, cx| backend.send(builder, cx));
|
let (client, signer) = {
|
||||||
|
let backend = backend.read(cx);
|
||||||
|
(backend.client(), backend.signer())
|
||||||
|
};
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
if let Err(e) = task.await {
|
let publish_result: Result<Event, Error> = async {
|
||||||
|
let event = builder.finalize_async(&signer).await?;
|
||||||
|
let output = client.send_event(&event).broadcast().await?;
|
||||||
|
require_relay_accepted(output, event)
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match publish_result {
|
||||||
|
Ok(event) => {
|
||||||
|
this.update(cx, |_this, cx| {
|
||||||
|
Backend::global(cx)
|
||||||
|
.update(cx, |backend, cx| backend.announce_published(event, cx))
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.last_error = Some(e.to_string());
|
this.last_error = Some(e.to_string());
|
||||||
cx.notify();
|
cx.notify();
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
});
|
||||||
|
task.detach();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1426,6 +1536,12 @@ async fn publish_patch_series(
|
|||||||
first_marker: &str,
|
first_marker: &str,
|
||||||
reply_to: Option<EventId>,
|
reply_to: Option<EventId>,
|
||||||
) -> Result<Event, Error> {
|
) -> Result<Event, Error> {
|
||||||
|
let (client, signer) = this.update(cx, |_this, cx| {
|
||||||
|
let backend = Backend::global(cx);
|
||||||
|
let backend = backend.read(cx);
|
||||||
|
(backend.client(), backend.signer())
|
||||||
|
})?;
|
||||||
|
|
||||||
let mut root: Option<Event> = None;
|
let mut root: Option<Event> = None;
|
||||||
let mut previous = reply_to;
|
let mut previous = reply_to;
|
||||||
|
|
||||||
@@ -1466,11 +1582,14 @@ async fn publish_patch_series(
|
|||||||
|
|
||||||
let builder = EventBuilder::new(Kind::GitPatch, part.clone()).tags(tags);
|
let builder = EventBuilder::new(Kind::GitPatch, part.clone()).tags(tags);
|
||||||
|
|
||||||
let task = this.update(cx, |_this, cx| {
|
let event = builder.finalize_async(&signer).await?;
|
||||||
let backend = Backend::global(cx);
|
let output = client.send_event(&event).broadcast().await?;
|
||||||
backend.update(cx, |backend, cx| backend.send(builder, cx))
|
let event = require_relay_accepted(output, event)?;
|
||||||
|
this.update(cx, |_this, cx| {
|
||||||
|
Backend::global(cx).update(cx, |backend, cx| {
|
||||||
|
backend.announce_published(event.clone(), cx)
|
||||||
|
})
|
||||||
})?;
|
})?;
|
||||||
let event = task.await?;
|
|
||||||
|
|
||||||
if root.is_none() {
|
if root.is_none() {
|
||||||
root = Some(event.clone());
|
root = Some(event.clone());
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -6,10 +7,116 @@ use anyhow::Error;
|
|||||||
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task};
|
use gpui::{App, AppContext, Context, Entity, Global, Subscription, Task};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use signed_core::{Announcement, Deletions, RepoAddr, filters, repo_addr};
|
use signed_core::{Announcement, Deletions, RepoAddr, filters, repo_addr};
|
||||||
|
use signed_git::find_git_repos;
|
||||||
|
|
||||||
use crate::backend::{Backend, BackendEvent};
|
use crate::backend::{Backend, BackendEvent};
|
||||||
use crate::refresh::{RefreshGate, RefreshRequest};
|
use crate::refresh::{RefreshGate, RefreshRequest};
|
||||||
|
|
||||||
|
struct GlobalLocalReposStore(Entity<LocalReposStore>);
|
||||||
|
|
||||||
|
impl Global for GlobalLocalReposStore {}
|
||||||
|
|
||||||
|
/// Store of the git repositories discovered under a set of scan paths.
|
||||||
|
pub struct LocalReposStore {
|
||||||
|
/// The directories being scanned.
|
||||||
|
pub roots: Arc<Vec<PathBuf>>,
|
||||||
|
/// Git repositories discovered under [`Self::roots`], sorted by path.
|
||||||
|
pub repos: Arc<Vec<PathBuf>>,
|
||||||
|
/// A scan is currently running.
|
||||||
|
pub scanning: bool,
|
||||||
|
/// A scan was requested while one was already running.
|
||||||
|
scan_dirty: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LocalReposStore {
|
||||||
|
/// Retrieve the global local-repositories store.
|
||||||
|
pub fn global(cx: &App) -> Entity<Self> {
|
||||||
|
cx.global::<GlobalLocalReposStore>().0.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_global(entity: Entity<Self>, cx: &mut App) {
|
||||||
|
cx.set_global(GlobalLocalReposStore(entity));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a store scanning `roots` right away.
|
||||||
|
pub fn new(roots: Vec<PathBuf>, cx: &mut Context<Self>) -> Self {
|
||||||
|
let weak = cx.entity().downgrade();
|
||||||
|
cx.defer(move |cx| {
|
||||||
|
if let Err(error) = weak.update(cx, |this, cx| this.rescan(cx)) {
|
||||||
|
log::warn!("local repos store dropped before initial scan could run: {error}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Self {
|
||||||
|
roots: Arc::new(roots),
|
||||||
|
repos: Arc::new(Vec::new()),
|
||||||
|
scanning: false,
|
||||||
|
scan_dirty: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forget a repository that has just been published to NIP-34.
|
||||||
|
pub fn remove(&mut self, path: &Path, cx: &mut Context<Self>) {
|
||||||
|
self.repos = Arc::new(
|
||||||
|
self.repos
|
||||||
|
.iter()
|
||||||
|
.filter(|repo| repo.as_path() != path)
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
|
);
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-run the scan.
|
||||||
|
pub fn rescan(&mut self, cx: &mut Context<Self>) {
|
||||||
|
if self.scanning {
|
||||||
|
self.scan_dirty = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.roots.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.scanning = true;
|
||||||
|
cx.notify();
|
||||||
|
|
||||||
|
let roots = self.roots.clone();
|
||||||
|
|
||||||
|
let work = cx.background_spawn(async move {
|
||||||
|
let mut repos = Vec::new();
|
||||||
|
for root in roots.iter() {
|
||||||
|
repos.extend(find_git_repos(root));
|
||||||
|
}
|
||||||
|
repos.sort();
|
||||||
|
repos.dedup();
|
||||||
|
repos
|
||||||
|
});
|
||||||
|
|
||||||
|
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
|
let repos = work.await;
|
||||||
|
let again = this.update(cx, |this, cx| {
|
||||||
|
this.repos = Arc::new(repos);
|
||||||
|
this.scanning = false;
|
||||||
|
cx.notify();
|
||||||
|
|
||||||
|
let dirty = this.scan_dirty;
|
||||||
|
this.scan_dirty = false;
|
||||||
|
dirty
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Scans requested while this one ran are coalesced into one follow-up scan.
|
||||||
|
if again {
|
||||||
|
this.update(cx, |this, cx| this.rescan(cx))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
|
||||||
|
task.detach();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Delay between a refresh request and the actual re-query.
|
/// Delay between a refresh request and the actual re-query.
|
||||||
///
|
///
|
||||||
/// Bursts of events, e.g. sync progress ticks, collapse into one query.
|
/// Bursts of events, e.g. sync progress ticks, collapse into one query.
|
||||||
@@ -55,7 +162,6 @@ pub struct RepoListStore {
|
|||||||
pub counts: Arc<HashMap<RepoAddr, RepoActivityCounts>>,
|
pub counts: Arc<HashMap<RepoAddr, RepoActivityCounts>>,
|
||||||
/// Refresh coalescing, see [`RefreshGate`].
|
/// Refresh coalescing, see [`RefreshGate`].
|
||||||
refresh: RefreshGate,
|
refresh: RefreshGate,
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
|
||||||
_subscription: Subscription,
|
_subscription: Subscription,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,7 +181,7 @@ impl RepoListStore {
|
|||||||
|
|
||||||
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
|
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
|
||||||
let relevant = match event {
|
let relevant = match event {
|
||||||
BackendEvent::NostrUpdate(update) => {
|
BackendEvent::NostrUpdate(updates) => updates.iter().any(|update| {
|
||||||
// Deletions may target anything we list, always refresh.
|
// Deletions may target anything we list, always refresh.
|
||||||
if update.kind == Kind::EventDeletion || update.kind == Kind::RequestToVanish {
|
if update.kind == Kind::EventDeletion || update.kind == Kind::RequestToVanish {
|
||||||
true
|
true
|
||||||
@@ -88,7 +194,7 @@ impl RepoListStore {
|
|||||||
let is_repo_state = update.kind == Kind::RepoState;
|
let is_repo_state = update.kind == Kind::RepoState;
|
||||||
is_announcement || is_repo_state
|
is_announcement || is_repo_state
|
||||||
}
|
}
|
||||||
}
|
}),
|
||||||
BackendEvent::Published(event) => {
|
BackendEvent::Published(event) => {
|
||||||
let announcement = event.kind == Kind::GitRepoAnnouncement;
|
let announcement = event.kind == Kind::GitRepoAnnouncement;
|
||||||
|
|
||||||
@@ -99,7 +205,10 @@ impl RepoListStore {
|
|||||||
|
|
||||||
announcement || deletion
|
announcement || deletion
|
||||||
}
|
}
|
||||||
BackendEvent::Synced | BackendEvent::SyncProgress { .. } => true,
|
// Only a completed sync refreshes the list.
|
||||||
|
// Progress ticks would re-scan the whole database several times
|
||||||
|
// per sync to reveal entries incrementally.
|
||||||
|
BackendEvent::Synced => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -108,20 +217,26 @@ impl RepoListStore {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut store = Self {
|
let weak = cx.entity().downgrade();
|
||||||
|
cx.defer(move |cx| {
|
||||||
|
let result = weak.update(cx, |this, cx| {
|
||||||
|
this.subscribe_remote(cx);
|
||||||
|
// Query the local database right away.
|
||||||
|
// The list never waits for the relay syncs started above to finish.
|
||||||
|
this.refresh_initial(cx);
|
||||||
|
});
|
||||||
|
if let Err(error) = result {
|
||||||
|
log::warn!("repo list store dropped before bootstrap could run: {error}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Self {
|
||||||
announcements: Arc::new(Vec::new()),
|
announcements: Arc::new(Vec::new()),
|
||||||
last_activity: Arc::new(HashMap::new()),
|
last_activity: Arc::new(HashMap::new()),
|
||||||
counts: Arc::new(HashMap::new()),
|
counts: Arc::new(HashMap::new()),
|
||||||
refresh: RefreshGate::default(),
|
refresh: RefreshGate::default(),
|
||||||
_subscription: subscription,
|
_subscription: subscription,
|
||||||
tasks: Vec::new(),
|
}
|
||||||
};
|
|
||||||
|
|
||||||
store.subscribe_remote(cx);
|
|
||||||
// Query the local database right away.
|
|
||||||
// The list never waits for the relay syncs started above to finish.
|
|
||||||
store.refresh_initial(cx);
|
|
||||||
store
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The announcements of `user`, newest first.
|
/// The announcements of `user`, newest first.
|
||||||
@@ -133,14 +248,6 @@ impl RepoListStore {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Track a spawned task, pruning finished tasks first.
|
|
||||||
///
|
|
||||||
/// Keeps the store's task list bounded by the number of in-flight tasks.
|
|
||||||
fn push_task(&mut self, task: Task<Result<(), Error>>) {
|
|
||||||
self.tasks.retain(|task| !task.is_ready());
|
|
||||||
self.tasks.push(task);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Negentropy-sync announcements with the bootstrap relays.
|
/// Negentropy-sync announcements with the bootstrap relays.
|
||||||
fn subscribe_remote(&mut self, cx: &mut Context<Self>) {
|
fn subscribe_remote(&mut self, cx: &mut Context<Self>) {
|
||||||
let backend = Backend::global(cx);
|
let backend = Backend::global(cx);
|
||||||
@@ -171,13 +278,11 @@ impl RepoListStore {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let task = cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
|
cx.background_executor().timer(REFRESH_DEBOUNCE).await;
|
||||||
|
|
||||||
this.update(cx, |this, cx| this.run_refresh(cx))
|
this.update(cx, |this, cx| this.run_refresh(cx))
|
||||||
});
|
})
|
||||||
|
.detach();
|
||||||
self.push_task(task);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One query and apply cycle, the debounced entry point.
|
/// One query and apply cycle, the debounced entry point.
|
||||||
@@ -294,7 +399,7 @@ impl RepoListStore {
|
|||||||
Ok::<_, Error>((announcements, last_activity, counts))
|
Ok::<_, Error>((announcements, last_activity, counts))
|
||||||
});
|
});
|
||||||
|
|
||||||
self.push_task(cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
let (announcements, last_activity, counts) = match work.await {
|
let (announcements, last_activity, counts) = match work.await {
|
||||||
Ok(results) => results,
|
Ok(results) => results,
|
||||||
// Database errors are transient, keep the last list.
|
// Database errors are transient, keep the last list.
|
||||||
@@ -321,6 +426,7 @@ impl RepoListStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
})
|
||||||
|
.detach();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -325,8 +325,6 @@ pub struct CommitDiffView {
|
|||||||
error: Option<SharedString>,
|
error: Option<SharedString>,
|
||||||
/// Changed-files explorer and per-file diff, also used by the new PR panel's compare view.
|
/// Changed-files explorer and per-file diff, also used by the new PR panel's compare view.
|
||||||
pane: Entity<DiffPane>,
|
pane: Entity<DiffPane>,
|
||||||
/// In-flight tasks, pruned on every push.
|
|
||||||
tasks: Vec<gpui::Task<Result<(), anyhow::Error>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommitDiffView {
|
impl CommitDiffView {
|
||||||
@@ -358,7 +356,6 @@ impl CommitDiffView {
|
|||||||
loading: true,
|
loading: true,
|
||||||
error: None,
|
error: None,
|
||||||
pane,
|
pane,
|
||||||
tasks: Vec::new(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -371,7 +368,8 @@ impl CommitDiffView {
|
|||||||
let worktree = self.worktree.clone();
|
let worktree = self.worktree.clone();
|
||||||
let id = self.commit.id.clone();
|
let id = self.commit.id.clone();
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), anyhow::Error>> =
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
let commit = cx
|
let commit = cx
|
||||||
.background_spawn({
|
.background_spawn({
|
||||||
let worktree = worktree.clone();
|
let worktree = worktree.clone();
|
||||||
@@ -406,7 +404,7 @@ impl CommitDiffView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Header with the commit id, summary, author/time and overall change stats.
|
/// Header with the commit id, summary, author/time and overall change stats.
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ use gix::Repository;
|
|||||||
use gpui::prelude::*;
|
use gpui::prelude::*;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
Action, Anchor, AnyElement, App, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
Action, Anchor, AnyElement, App, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
||||||
Focusable, PathPromptOptions, Pixels, Render, SharedString, Size, Subscription, Task,
|
Focusable, PathPromptOptions, Pixels, Render, SharedString, Size, Subscription, WeakEntity,
|
||||||
WeakEntity, Window, div, px, relative, size, transparent_white,
|
Window, div, px, relative, size, transparent_white,
|
||||||
};
|
};
|
||||||
use gpui_base::{Button as BaseButton, Disableable, Popover};
|
use gpui_base::{Button as BaseButton, Disableable, Popover};
|
||||||
use gpui_component::alert::Alert;
|
use gpui_component::alert::Alert;
|
||||||
@@ -24,7 +24,7 @@ use gpui_component::{
|
|||||||
ActiveTheme, Colorize, Icon, IconName, Sizable, StyledExt, ThemeStyled,
|
ActiveTheme, Colorize, Icon, IconName, Sizable, StyledExt, ThemeStyled,
|
||||||
VirtualListScrollHandle, h_flex, v_flex,
|
VirtualListScrollHandle, h_flex, v_flex,
|
||||||
};
|
};
|
||||||
use nostr::prelude::{RelayUrl, ToBech32};
|
use nostr::prelude::{RelayUrl, ToBech32, Url};
|
||||||
use signed_core::{Announcement, RepoAddr, RepoStatus, filters};
|
use signed_core::{Announcement, RepoAddr, RepoStatus, filters};
|
||||||
use signed_git::{CommitList, FileCommit};
|
use signed_git::{CommitList, FileCommit};
|
||||||
use signed_state::{
|
use signed_state::{
|
||||||
@@ -175,9 +175,6 @@ pub struct RepoDetailView {
|
|||||||
/// Bumped on every branch/tag switch.
|
/// Bumped on every branch/tag switch.
|
||||||
/// In-flight loads with an older generation are discarded when they complete.
|
/// In-flight loads with an older generation are discarded when they complete.
|
||||||
ref_generation: u64,
|
ref_generation: u64,
|
||||||
/// In-flight tasks, finished tasks are pruned on every push.
|
|
||||||
/// The vec stays bounded by the number of concurrent loads.
|
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
|
||||||
/// Subscriptions keeping the selectors' confirm events alive.
|
/// Subscriptions keeping the selectors' confirm events alive.
|
||||||
_subscriptions: Vec<Subscription>,
|
_subscriptions: Vec<Subscription>,
|
||||||
/// `(path, branch)` ready-suggestions dismissed by the user, per panel.
|
/// `(path, branch)` ready-suggestions dismissed by the user, per panel.
|
||||||
@@ -346,7 +343,6 @@ impl RepoDetailView {
|
|||||||
push_statuses: Vec::new(),
|
push_statuses: Vec::new(),
|
||||||
pending_upstream: None,
|
pending_upstream: None,
|
||||||
focus_handle: cx.focus_handle(),
|
focus_handle: cx.focus_handle(),
|
||||||
tasks: Vec::new(),
|
|
||||||
_subscriptions: subscriptions,
|
_subscriptions: subscriptions,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -363,7 +359,7 @@ impl RepoDetailView {
|
|||||||
// Local repositories live on disk at their scan path.
|
// Local repositories live on disk at their scan path.
|
||||||
// No clone step or network refresh applies here.
|
// No clone step or network refresh applies here.
|
||||||
if let Some(local_path) = self.local_path.clone() {
|
if let Some(local_path) = self.local_path.clone() {
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
let data = cx
|
let data = cx
|
||||||
.background_spawn(async move {
|
.background_spawn(async move {
|
||||||
let repo = gix::open(&local_path)?;
|
let repo = gix::open(&local_path)?;
|
||||||
@@ -383,7 +379,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -394,7 +390,7 @@ impl RepoDetailView {
|
|||||||
|
|
||||||
let cache = GitStore::global(cx).cache().clone();
|
let cache = GitStore::global(cx).cache().clone();
|
||||||
let addr = initial.addr();
|
let addr = initial.addr();
|
||||||
let clone_urls: Vec<String> = initial.clone.iter().map(ToString::to_string).collect();
|
let clone_urls: Vec<Url> = initial.clone.clone();
|
||||||
|
|
||||||
// Captured before the loads start.
|
// Captured before the loads start.
|
||||||
// A branch/tag switch bumps the generation, discarding the refresh below.
|
// A branch/tag switch bumps the generation, discarding the refresh below.
|
||||||
@@ -411,7 +407,7 @@ impl RepoDetailView {
|
|||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
let disk = disk.await;
|
let disk = disk.await;
|
||||||
let had_clone = matches!(&disk, Ok(Some(_)));
|
let had_clone = matches!(&disk, Ok(Some(_)));
|
||||||
|
|
||||||
@@ -531,7 +527,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply the loaded repository data.
|
/// Apply the loaded repository data.
|
||||||
@@ -619,7 +615,7 @@ impl RepoDetailView {
|
|||||||
prompt: Some("Clone".into()),
|
prompt: Some("Clone".into()),
|
||||||
});
|
});
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
// `Ok(Ok(Some(paths)))` means the user picked a folder.
|
// `Ok(Ok(Some(paths)))` means the user picked a folder.
|
||||||
// A cancel or picker failure resolves to anything else.
|
// A cancel or picker failure resolves to anything else.
|
||||||
let picked = match prompt.await {
|
let picked = match prompt.await {
|
||||||
@@ -649,7 +645,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Preview the file at `path`, relative to the worktree root.
|
/// Preview the file at `path`, relative to the worktree root.
|
||||||
@@ -703,7 +699,7 @@ impl RepoDetailView {
|
|||||||
self.load_commit(&path, cx);
|
self.load_commit(&path, cx);
|
||||||
let generation = self.ref_generation;
|
let generation = self.ref_generation;
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
let path_for_read = path.clone();
|
let path_for_read = path.clone();
|
||||||
let content = cx
|
let content = cx
|
||||||
.background_spawn(async move {
|
.background_spawn(async move {
|
||||||
@@ -772,7 +768,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Queue `path` for the per-file commit query.
|
/// Queue `path` for the per-file commit query.
|
||||||
@@ -804,7 +800,7 @@ impl RepoDetailView {
|
|||||||
let paths = std::mem::take(&mut self.pending_commits);
|
let paths = std::mem::take(&mut self.pending_commits);
|
||||||
let generation = self.ref_generation;
|
let generation = self.ref_generation;
|
||||||
|
|
||||||
let task = cx.spawn(async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let rels: Vec<PathBuf> = paths.iter().map(PathBuf::from).collect();
|
let rels: Vec<PathBuf> = paths.iter().map(PathBuf::from).collect();
|
||||||
let result = cx
|
let result = cx
|
||||||
.background_spawn(
|
.background_spawn(
|
||||||
@@ -834,7 +830,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Walk all commits reachable from HEAD on a background task.
|
/// Walk all commits reachable from HEAD on a background task.
|
||||||
@@ -852,7 +848,7 @@ impl RepoDetailView {
|
|||||||
self.loading_all_commits = true;
|
self.loading_all_commits = true;
|
||||||
let generation = self.ref_generation;
|
let generation = self.ref_generation;
|
||||||
|
|
||||||
let task = cx.spawn(async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let result = cx
|
let result = cx
|
||||||
.background_spawn(async move { signed_git::worktree_all_commits(&worktree) })
|
.background_spawn(async move { signed_git::worktree_all_commits(&worktree) })
|
||||||
.await;
|
.await;
|
||||||
@@ -876,7 +872,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Open a new panel showing the diff of `commit_id`.
|
/// Open a new panel showing the diff of `commit_id`.
|
||||||
@@ -909,8 +905,9 @@ impl RepoDetailView {
|
|||||||
self.error = None;
|
self.error = None;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
|
|
||||||
self.tasks
|
store
|
||||||
.push(store.update(cx, |store, cx| store.push_repository(cx)));
|
.update(cx, |store, cx| store.push_repository(cx))
|
||||||
|
.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Push the unpushed commits of the local checkout at `path`.
|
/// Push the unpushed commits of the local checkout at `path`.
|
||||||
@@ -931,7 +928,7 @@ impl RepoDetailView {
|
|||||||
self.error = None;
|
self.error = None;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
// The store owns the push, its busy flag and error reporting.
|
// The store owns the push, its busy flag and error reporting.
|
||||||
let push = this.update_in(cx, |_this, _window, cx| {
|
let push = this.update_in(cx, |_this, _window, cx| {
|
||||||
store.update(cx, |store, cx| store.push_checkout(path.clone(), cx))
|
store.update(cx, |store, cx| store.push_checkout(path.clone(), cx))
|
||||||
@@ -948,7 +945,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Delete the repository from nostr, announcement, state and activity.
|
/// Delete the repository from nostr, announcement, state and activity.
|
||||||
@@ -956,8 +953,9 @@ impl RepoDetailView {
|
|||||||
let Some(store) = self.store.clone() else {
|
let Some(store) = self.store.clone() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
self.tasks
|
store
|
||||||
.push(store.update(cx, |store, cx| store.delete_repository(cx)));
|
.update(cx, |store, cx| store.delete_repository(cx))
|
||||||
|
.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Open the issues list panel in the dock area.
|
/// Open the issues list panel in the dock area.
|
||||||
@@ -1025,7 +1023,7 @@ impl RepoDetailView {
|
|||||||
});
|
});
|
||||||
self.pending_upstream = Some(addr);
|
self.pending_upstream = Some(addr);
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
for _ in 0..60 {
|
for _ in 0..60 {
|
||||||
cx.background_executor()
|
cx.background_executor()
|
||||||
.timer(Duration::from_millis(250))
|
.timer(Duration::from_millis(250))
|
||||||
@@ -1060,7 +1058,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check out `name`, a branch or tag picked in the header.
|
/// Check out `name`, a branch or tag picked in the header.
|
||||||
@@ -1101,7 +1099,7 @@ impl RepoDetailView {
|
|||||||
cx.notify();
|
cx.notify();
|
||||||
|
|
||||||
let checkout_name = name.clone();
|
let checkout_name = name.clone();
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
let result = cx
|
let result = cx
|
||||||
.background_spawn(async move {
|
.background_spawn(async move {
|
||||||
match kind {
|
match kind {
|
||||||
@@ -1131,7 +1129,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Restore a selector to `previous`, or clear it after a failed switch.
|
/// Restore a selector to `previous`, or clear it after a failed switch.
|
||||||
@@ -1157,7 +1155,7 @@ impl RepoDetailView {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let task = cx.spawn(async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let result = cx
|
let result = cx
|
||||||
.background_spawn(async move {
|
.background_spawn(async move {
|
||||||
let snapshot = signed_git::worktree_snapshot(&worktree)?;
|
let snapshot = signed_git::worktree_snapshot(&worktree)?;
|
||||||
@@ -1218,7 +1216,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Refresh the file explorer, previews and commit list after the mirror
|
/// Refresh the file explorer, previews and commit list after the mirror
|
||||||
@@ -1233,7 +1231,7 @@ impl RepoDetailView {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let task = cx.spawn(async move |this, cx| {
|
let task: gpui::Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
||||||
let result = cx
|
let result = cx
|
||||||
.background_spawn(async move {
|
.background_spawn(async move {
|
||||||
let snapshot = signed_git::worktree_snapshot(&worktree)?;
|
let snapshot = signed_git::worktree_snapshot(&worktree)?;
|
||||||
@@ -1314,7 +1312,7 @@ impl RepoDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drop the cached preview, editor and commit state of `path`.
|
/// Drop the cached preview, editor and commit state of `path`.
|
||||||
|
|||||||
@@ -6,8 +6,7 @@ use dock::{BasePanel, DockArea, Panel, PanelEvent, add_center_panel, panel_handl
|
|||||||
use gpui::prelude::*;
|
use gpui::prelude::*;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, PathPromptOptions,
|
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, PathPromptOptions,
|
||||||
Pixels, Render, SharedString, Size, Subscription, Task, WeakEntity, Window, div, px, relative,
|
Pixels, Render, SharedString, Size, Subscription, WeakEntity, Window, div, px, relative, size,
|
||||||
size,
|
|
||||||
};
|
};
|
||||||
use gpui_base::{Button as BaseButton, StyledExt};
|
use gpui_base::{Button as BaseButton, StyledExt};
|
||||||
use gpui_component::button::{Button, ButtonVariants};
|
use gpui_component::button::{Button, ButtonVariants};
|
||||||
@@ -22,10 +21,10 @@ use gpui_component::{
|
|||||||
v_virtual_list,
|
v_virtual_list,
|
||||||
};
|
};
|
||||||
use nostr::prelude::*;
|
use nostr::prelude::*;
|
||||||
use signed_core::{Announcement, RepoAddr};
|
use signed_core::{Announcement, RepoAddr, fork_candidates};
|
||||||
use signed_git::{
|
use signed_git::{
|
||||||
delete_refs_with_prefix, fetch_repo_refs, format_patch_between, merge_base, refs_with_prefix,
|
delete_refs_with_prefix, fetch_repo_refs, fork_namespace, merge_base, refs_with_prefix,
|
||||||
sanitize_path_component, worktree_commit_range_commits, worktree_commit_range_diff,
|
worktree_commit_range_commits, worktree_commit_range_diff,
|
||||||
};
|
};
|
||||||
use signed_state::{Backend, CheckoutsStore, GitStore, RepoListStore, RepoStore};
|
use signed_state::{Backend, CheckoutsStore, GitStore, RepoListStore, RepoStore};
|
||||||
use signed_ui::{CountBadge, placeholder};
|
use signed_ui::{CountBadge, placeholder};
|
||||||
@@ -79,7 +78,6 @@ pub struct NewPullRequestView {
|
|||||||
scroll_handle: VirtualListScrollHandle,
|
scroll_handle: VirtualListScrollHandle,
|
||||||
item_sizes: Rc<Vec<Size<Pixels>>>,
|
item_sizes: Rc<Vec<Size<Pixels>>>,
|
||||||
_subscriptions: Vec<Subscription>,
|
_subscriptions: Vec<Subscription>,
|
||||||
tasks: Vec<Task<Result<(), anyhow::Error>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A fork-backed compare.
|
/// A fork-backed compare.
|
||||||
@@ -104,36 +102,6 @@ impl ForkCompare {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The refs namespace of a fork's import in the target mirror.
|
|
||||||
fn fork_namespace(announcement: &Announcement) -> String {
|
|
||||||
format!(
|
|
||||||
"{}/{}",
|
|
||||||
announcement.owner.to_hex(),
|
|
||||||
sanitize_path_component(&announcement.id)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The announced forks of `base` a New PR compare can be built from.
|
|
||||||
fn fork_candidates<'a>(
|
|
||||||
announcements: &'a [Announcement],
|
|
||||||
base: &RepoAddr,
|
|
||||||
base_euc: Option<&str>,
|
|
||||||
user: Option<PublicKey>,
|
|
||||||
) -> Vec<&'a Announcement> {
|
|
||||||
let (mut own, mut others) = (Vec::new(), Vec::new());
|
|
||||||
for announcement in announcements {
|
|
||||||
if announcement.clone.is_empty() || !announcement.is_fork_of(base, base_euc) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if Some(announcement.owner) == user {
|
|
||||||
own.push(announcement);
|
|
||||||
} else {
|
|
||||||
others.push(announcement);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
own.into_iter().chain(others).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The display name of an announcement.
|
/// The display name of an announcement.
|
||||||
///
|
///
|
||||||
/// Its human-readable name, falling back to the repository id.
|
/// Its human-readable name, falling back to the repository id.
|
||||||
@@ -363,7 +331,6 @@ impl NewPullRequestView {
|
|||||||
scroll_handle: VirtualListScrollHandle::new(),
|
scroll_handle: VirtualListScrollHandle::new(),
|
||||||
item_sizes: Rc::new(Vec::new()),
|
item_sizes: Rc::new(Vec::new()),
|
||||||
_subscriptions: subscriptions,
|
_subscriptions: subscriptions,
|
||||||
tasks: Vec::new(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Prefill with the store's freshest associated checkout, no folder dialog.
|
// Prefill with the store's freshest associated checkout, no folder dialog.
|
||||||
@@ -426,7 +393,8 @@ impl NewPullRequestView {
|
|||||||
prompt: Some("Choose local checkout".into()),
|
prompt: Some("Choose local checkout".into()),
|
||||||
});
|
});
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), anyhow::Error>> =
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
// `Ok(Ok(Some(paths)))` means the user picked a folder.
|
// `Ok(Ok(Some(paths)))` means the user picked a folder.
|
||||||
// A cancel or picker failure resolves to anything else.
|
// A cancel or picker failure resolves to anything else.
|
||||||
let picked = match prompt.await {
|
let picked = match prompt.await {
|
||||||
@@ -444,7 +412,7 @@ impl NewPullRequestView {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply `path` as the local checkout, no picker.
|
/// Apply `path` as the local checkout, no picker.
|
||||||
@@ -453,7 +421,8 @@ impl NewPullRequestView {
|
|||||||
fn apply_folder_path(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
|
fn apply_folder_path(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let path = path.to_string_lossy().to_string();
|
let path = path.to_string_lossy().to_string();
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), anyhow::Error>> =
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
// Branches and the current branch are read off the UI thread.
|
// Branches and the current branch are read off the UI thread.
|
||||||
let info = cx
|
let info = cx
|
||||||
.background_spawn({
|
.background_spawn({
|
||||||
@@ -474,7 +443,7 @@ impl NewPullRequestView {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply a picked checkout, filling the selectors and loading the compare.
|
/// Apply a picked checkout, filling the selectors and loading the compare.
|
||||||
@@ -592,14 +561,14 @@ impl NewPullRequestView {
|
|||||||
let cache = GitStore::global(cx).cache().clone();
|
let cache = GitStore::global(cx).cache().clone();
|
||||||
let mirror_path = cache.repo_path(&base);
|
let mirror_path = cache.repo_path(&base);
|
||||||
let namespace = fork_namespace(&announcement);
|
let namespace = fork_namespace(&announcement);
|
||||||
let clone_urls: Vec<String> = announcement.clone.iter().map(ToString::to_string).collect();
|
let clone_urls = announcement.clone.clone();
|
||||||
|
|
||||||
let base_clone_urls: Vec<String> = self
|
let base_clone_urls: Vec<Url> = self
|
||||||
.store
|
.store
|
||||||
.read(cx)
|
.read(cx)
|
||||||
.announcement
|
.announcement
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|a| a.clone.iter().map(ToString::to_string).collect())
|
.map(|a| a.clone.clone())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
// Keep the current compare and base when the fork is already applied.
|
// Keep the current compare and base when the fork is already applied.
|
||||||
@@ -615,7 +584,8 @@ impl NewPullRequestView {
|
|||||||
self.error = None;
|
self.error = None;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), anyhow::Error>> =
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
// The fork and base must share history for a merge-base to exist.
|
// The fork and base must share history for a merge-base to exist.
|
||||||
// The target's mirror is the object store both sides land in.
|
// The target's mirror is the object store both sides land in.
|
||||||
// `ensure_clone` fetches `origin` when the mirror already exists.
|
// `ensure_clone` fetches `origin` when the mirror already exists.
|
||||||
@@ -696,7 +666,7 @@ impl NewPullRequestView {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply an imported fork, filling the selectors and loading the compare.
|
/// Apply an imported fork, filling the selectors and loading the compare.
|
||||||
@@ -834,7 +804,8 @@ impl NewPullRequestView {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), anyhow::Error>> =
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
let result = cx
|
let result = cx
|
||||||
.background_spawn({
|
.background_spawn({
|
||||||
let repo_path = repo_path.clone();
|
let repo_path = repo_path.clone();
|
||||||
@@ -875,7 +846,8 @@ impl NewPullRequestView {
|
|||||||
Ok((merge_base, commits, diff)) => {
|
Ok((merge_base, commits, diff)) => {
|
||||||
this.merge_base = Some(merge_base);
|
this.merge_base = Some(merge_base);
|
||||||
let count = commits.len();
|
let count = commits.len();
|
||||||
this.item_sizes = Rc::new(vec![size(px(0.), px(COMMIT_ROW_HEIGHT)); count]);
|
this.item_sizes =
|
||||||
|
Rc::new(vec![size(px(0.), px(COMMIT_ROW_HEIGHT)); count]);
|
||||||
this.commits = Some(commits);
|
this.commits = Some(commits);
|
||||||
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
|
this.pane.update(cx, |pane, cx| pane.set_diff(diff, cx));
|
||||||
}
|
}
|
||||||
@@ -893,7 +865,7 @@ impl NewPullRequestView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Publish the pull request.
|
/// Publish the pull request.
|
||||||
@@ -927,56 +899,35 @@ impl NewPullRequestView {
|
|||||||
self.error = None;
|
self.error = None;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), anyhow::Error>> =
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
// Regenerate the series at submit time.
|
// Regenerate the series at submit time.
|
||||||
// The published patch covers the current tip of the compare branch.
|
// The published patch covers the current tip of the compare branch.
|
||||||
let patch = cx
|
let publish = store.update(cx, |store, cx| {
|
||||||
.background_spawn({
|
store.open_pull_request_from_refs(
|
||||||
let repo_path = repo_path.clone();
|
repo_path,
|
||||||
let merge_base = merge_base.clone();
|
merge_base,
|
||||||
let compare_ref = compare_ref.clone();
|
compare_ref,
|
||||||
async move {
|
|
||||||
format_patch_between(Path::new(&repo_path), &merge_base, &compare_ref)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let patch = match patch {
|
|
||||||
Ok(patch) if !patch.is_empty() => patch,
|
|
||||||
Ok(_) => {
|
|
||||||
this.update_in(cx, |this, _window, cx| {
|
|
||||||
this.submitting = false;
|
|
||||||
this.error = Some("No commits between the branches to propose".into());
|
|
||||||
cx.notify();
|
|
||||||
})?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
this.update_in(cx, |this, _window, cx| {
|
|
||||||
this.submitting = false;
|
|
||||||
this.error = Some(format!("Failed to generate the patch: {error}").into());
|
|
||||||
cx.notify();
|
|
||||||
})?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
this.update_in(cx, |this, window, cx| {
|
|
||||||
this.submitting = false;
|
|
||||||
|
|
||||||
store.update(cx, |store, cx| {
|
|
||||||
store.open_pull_request(
|
|
||||||
(!subject.is_empty()).then_some(subject),
|
(!subject.is_empty()).then_some(subject),
|
||||||
description,
|
description,
|
||||||
Some(branch_name),
|
Some(branch_name),
|
||||||
patch,
|
|
||||||
false,
|
false,
|
||||||
Some(merge_base),
|
|
||||||
Some(repo_path),
|
|
||||||
cx,
|
cx,
|
||||||
);
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if let Err(error) = publish.await {
|
||||||
|
this.update_in(cx, |this, _window, cx| {
|
||||||
|
this.submitting = false;
|
||||||
|
this.error = Some(error.to_string().into());
|
||||||
|
cx.notify();
|
||||||
|
})?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
this.update_in(cx, |this, window, cx| {
|
||||||
|
this.submitting = false;
|
||||||
|
|
||||||
// Close the panel once the publish is underway.
|
// Close the panel once the publish is underway.
|
||||||
cx.defer_in(window, {
|
cx.defer_in(window, {
|
||||||
let dock_area = dock_area.clone();
|
let dock_area = dock_area.clone();
|
||||||
@@ -996,7 +947,7 @@ impl NewPullRequestView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(task);
|
task.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Open the diff of `commit_id`, from the Commits tab, in a new panel.
|
/// Open the diff of `commit_id`, from the Commits tab, in a new panel.
|
||||||
@@ -1459,140 +1410,3 @@ impl Render for NewPullRequestView {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use nostr::prelude::*;
|
|
||||||
use signed_core::repo_addr;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
const OWNER_KEYS: [&str; 3] = [
|
|
||||||
"0000000000000000000000000000000000000000000000000000000000000001",
|
|
||||||
"0000000000000000000000000000000000000000000000000000000000000002",
|
|
||||||
"0000000000000000000000000000000000000000000000000000000000000003",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Build a signed kind-30617 event for `owner` with the given tags.
|
|
||||||
fn announcement_event(owner: &str, tags: &[&[&str]]) -> Event {
|
|
||||||
let keys = Keys::new(SecretKey::from_hex(owner).expect("valid secret key"));
|
|
||||||
let tags: Vec<Tag> = tags
|
|
||||||
.iter()
|
|
||||||
.map(|t| Tag::parse(t.to_vec()).expect("valid tag"))
|
|
||||||
.collect();
|
|
||||||
EventBuilder::new(Kind::GitRepoAnnouncement, "")
|
|
||||||
.tags(tags)
|
|
||||||
.finalize(&keys)
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn announcements(owner_ix: usize, tags: &[&[&str]]) -> Vec<Announcement> {
|
|
||||||
vec![
|
|
||||||
Announcement::from_event(&announcement_event(OWNER_KEYS[owner_ix], tags))
|
|
||||||
.expect("parses"),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn fork_candidates_orders_own_forks_first() {
|
|
||||||
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
|
||||||
let clone = "https://grasp.example/npub1x/my-fork.git";
|
|
||||||
|
|
||||||
let base_addr = repo_addr(
|
|
||||||
PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey"),
|
|
||||||
"upstream",
|
|
||||||
);
|
|
||||||
// Newest first, as RepoListStore keeps them.
|
|
||||||
// Unrelated repo, the user's fork with the shared EUC, another fork with a `u` tag.
|
|
||||||
let all = vec![
|
|
||||||
announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "other-project"],
|
|
||||||
&["r", "bb231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
announcements(
|
|
||||||
1,
|
|
||||||
&[&["d", "my-fork"], &["r", euc, "euc"], &["clone", clone]],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "their-fork"],
|
|
||||||
&["u", &base_addr.to_string()],
|
|
||||||
&["clone", clone],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
];
|
|
||||||
|
|
||||||
let user = PublicKey::from_hex(OWNER_KEYS[1]).expect("pubkey");
|
|
||||||
let forks = fork_candidates(&all, &base_addr, Some(euc), Some(user));
|
|
||||||
|
|
||||||
// The user's fork comes first, then the other author's.
|
|
||||||
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
|
|
||||||
assert_eq!(ids, vec!["my-fork", "their-fork"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn fork_candidates_excludes_base_unrelated_and_unfetchable() {
|
|
||||||
let euc = "aa231c4c6a5777dc89b42207b499891a344add5c";
|
|
||||||
let base_owner = PublicKey::from_hex(OWNER_KEYS[0]).expect("pubkey");
|
|
||||||
let base_addr = repo_addr(base_owner, "upstream");
|
|
||||||
|
|
||||||
let mut all = vec![
|
|
||||||
announcements(0, &[&["d", "upstream"], &["r", euc, "euc"]])
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
announcements(1, &[&["d", "no-clone-fork"], &["r", euc, "euc"]])
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "other"],
|
|
||||||
&["r", "cc231c4c6a5777dc89b42207b499891a344add5c", "euc"],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "mirror"],
|
|
||||||
&["r", euc, "euc"],
|
|
||||||
&["clone", "https://grasp.example/x/mirror.git"],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
];
|
|
||||||
|
|
||||||
let forks = fork_candidates(&all, &base_addr, Some(euc), Some(base_owner));
|
|
||||||
assert_eq!(forks.len(), 1);
|
|
||||||
assert_eq!(forks[0].id, "mirror");
|
|
||||||
|
|
||||||
// Without a base EUC only `u`-tag forks match.
|
|
||||||
all.push(
|
|
||||||
announcements(
|
|
||||||
2,
|
|
||||||
&[
|
|
||||||
&["d", "u-fork"],
|
|
||||||
&["u", &base_addr.to_string()],
|
|
||||||
&["clone", "https://grasp.example/x/u-fork.git"],
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.pop()
|
|
||||||
.unwrap(),
|
|
||||||
);
|
|
||||||
let forks = fork_candidates(&all, &base_addr, None, Some(base_owner));
|
|
||||||
let ids: Vec<&str> = forks.iter().map(|a| a.id.as_str()).collect();
|
|
||||||
assert_eq!(ids, vec!["u-fork"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
|
|||||||
use gpui::prelude::*;
|
use gpui::prelude::*;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
|
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
|
||||||
SharedString, Size, Task, WeakEntity, Window, div, px, relative, size,
|
SharedString, Size, WeakEntity, Window, div, px, relative, size,
|
||||||
};
|
};
|
||||||
use gpui_component::button::{Button, ButtonVariants};
|
use gpui_component::button::{Button, ButtonVariants};
|
||||||
use gpui_component::clipboard::Clipboard;
|
use gpui_component::clipboard::Clipboard;
|
||||||
@@ -20,8 +20,11 @@ use gpui_component::{
|
|||||||
ActiveTheme, Sizable, StyledExt, VirtualListScrollHandle, WindowExt, h_flex, v_flex,
|
ActiveTheme, Sizable, StyledExt, VirtualListScrollHandle, WindowExt, h_flex, v_flex,
|
||||||
v_virtual_list,
|
v_virtual_list,
|
||||||
};
|
};
|
||||||
use nostr::prelude::{Event, EventId, Kind, Nip34Tag};
|
use nostr::prelude::{Event, EventId, Kind};
|
||||||
use signed_core::{activity_subject, pull_request_patch};
|
use signed_core::{
|
||||||
|
activity_subject, branch_name_of, clone_urls_of, current_commit_of, latest_update,
|
||||||
|
merge_base_of, pull_request_patch,
|
||||||
|
};
|
||||||
use signed_git::{FileCommit, patch_commits, patch_diffs};
|
use signed_git::{FileCommit, patch_commits, patch_diffs};
|
||||||
use signed_state::{Backend, GitStore, ProfileStore, RepoStore};
|
use signed_state::{Backend, GitStore, ProfileStore, RepoStore};
|
||||||
use signed_ui::{CountBadge, UserAvatar, placeholder, status_badge};
|
use signed_ui::{CountBadge, UserAvatar, placeholder, status_badge};
|
||||||
@@ -66,8 +69,6 @@ pub struct PullRequestDetailView {
|
|||||||
commit_item_sizes: Rc<Vec<Size<Pixels>>>,
|
commit_item_sizes: Rc<Vec<Size<Pixels>>>,
|
||||||
/// Virtual list state of the commits tab.
|
/// Virtual list state of the commits tab.
|
||||||
commit_scroll_handle: VirtualListScrollHandle,
|
commit_scroll_handle: VirtualListScrollHandle,
|
||||||
/// In-flight tasks, finished tasks are pruned on every push.
|
|
||||||
tasks: Vec<Task<Result<(), anyhow::Error>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PullRequestDetailView {
|
impl PullRequestDetailView {
|
||||||
@@ -106,7 +107,6 @@ impl PullRequestDetailView {
|
|||||||
pane,
|
pane,
|
||||||
commit_item_sizes: Rc::new(Vec::new()),
|
commit_item_sizes: Rc::new(Vec::new()),
|
||||||
commit_scroll_handle: VirtualListScrollHandle::new(),
|
commit_scroll_handle: VirtualListScrollHandle::new(),
|
||||||
tasks: Vec::new(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,12 +142,8 @@ impl PullRequestDetailView {
|
|||||||
.and_then(merge_base_of)
|
.and_then(merge_base_of)
|
||||||
.or_else(|| merge_base_of(root));
|
.or_else(|| merge_base_of(root));
|
||||||
|
|
||||||
let clone_urls = clone_urls_of(root).or_else(|| {
|
let clone_urls = clone_urls_of(root)
|
||||||
store
|
.or_else(|| store.announcement.as_ref().map(|a| a.clone.clone()));
|
||||||
.announcement
|
|
||||||
.as_ref()
|
|
||||||
.map(|a| a.clone.iter().map(ToString::to_string).collect())
|
|
||||||
});
|
|
||||||
|
|
||||||
(
|
(
|
||||||
root.content.clone(),
|
root.content.clone(),
|
||||||
@@ -162,7 +158,8 @@ impl PullRequestDetailView {
|
|||||||
|
|
||||||
self.description = description.into();
|
self.description = description.into();
|
||||||
|
|
||||||
let task = cx.spawn_in(window, async move |this, cx| {
|
let task: gpui::Task<Result<(), anyhow::Error>> =
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
let nostr_diff = cx
|
let nostr_diff = cx
|
||||||
.background_spawn({
|
.background_spawn({
|
||||||
let patch = patch.clone();
|
let patch = patch.clone();
|
||||||
@@ -202,8 +199,8 @@ impl PullRequestDetailView {
|
|||||||
.ok_or_else(|| anyhow::anyhow!("repository has no worktree"))?
|
.ok_or_else(|| anyhow::anyhow!("repository has no worktree"))?
|
||||||
.to_path_buf();
|
.to_path_buf();
|
||||||
|
|
||||||
let tip =
|
let tip = tip
|
||||||
tip.ok_or_else(|| anyhow::anyhow!("pull request has no tip commit"))?;
|
.ok_or_else(|| anyhow::anyhow!("pull request has no tip commit"))?;
|
||||||
|
|
||||||
let base = match base {
|
let base = match base {
|
||||||
Some(base) => base,
|
Some(base) => base,
|
||||||
@@ -217,7 +214,8 @@ impl PullRequestDetailView {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let diff = signed_git::worktree_commit_range_diff(&workdir, &base, &tip)?;
|
let diff =
|
||||||
|
signed_git::worktree_commit_range_diff(&workdir, &base, &tip)?;
|
||||||
let commits =
|
let commits =
|
||||||
signed_git::worktree_commit_range_commits(&workdir, &base, &tip)?;
|
signed_git::worktree_commit_range_commits(&workdir, &base, &tip)?;
|
||||||
|
|
||||||
@@ -237,7 +235,8 @@ impl PullRequestDetailView {
|
|||||||
this.loading = false;
|
this.loading = false;
|
||||||
this.worktree = worktree;
|
this.worktree = worktree;
|
||||||
this.current_commit = current_commit.map(SharedString::from);
|
this.current_commit = current_commit.map(SharedString::from);
|
||||||
this.commit_item_sizes = Rc::new(vec![size(px(0.), px(ROW_HEIGHT)); commits.len()]);
|
this.commit_item_sizes =
|
||||||
|
Rc::new(vec![size(px(0.), px(ROW_HEIGHT)); commits.len()]);
|
||||||
this.commits = commits;
|
this.commits = commits;
|
||||||
|
|
||||||
match diff {
|
match diff {
|
||||||
@@ -255,8 +254,7 @@ impl PullRequestDetailView {
|
|||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.retain(|task| !task.is_ready());
|
task.detach();
|
||||||
self.tasks.push(task);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Open the diff of `commit_id` in the bottom dock of the area.
|
/// Open the diff of `commit_id` in the bottom dock of the area.
|
||||||
@@ -706,66 +704,6 @@ fn open_update_pull_request_dialog(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The `c` tag of a PR event, the commit the proposal points at.
|
/// The `c` tag of a PR event, the commit the proposal points at.
|
||||||
fn current_commit_of(root: &Event) -> Option<String> {
|
|
||||||
root.tags
|
|
||||||
.iter()
|
|
||||||
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
|
|
||||||
Ok(Nip34Tag::CurrentCommit(commit)) => Some(commit.to_string()),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `merge-base` tag of a PR event, as hex.
|
|
||||||
///
|
|
||||||
/// The most recent common ancestor with the target branch.
|
|
||||||
fn merge_base_of(event: &Event) -> Option<String> {
|
|
||||||
event
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
|
|
||||||
Ok(Nip34Tag::MergeBase(commit)) => Some(commit.to_string()),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `clone` tag of a PR event.
|
|
||||||
///
|
|
||||||
/// URLs where the proposed branch can be fetched, or `None` if the PR has none.
|
|
||||||
fn clone_urls_of(event: &Event) -> Option<Vec<String>> {
|
|
||||||
event
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
|
|
||||||
Ok(Nip34Tag::Clone(urls)) => Some(urls.iter().map(ToString::to_string).collect()),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `branch-name` tag of a PR event, if any.
|
|
||||||
fn branch_name_of(event: &Event) -> Option<String> {
|
|
||||||
event
|
|
||||||
.tags
|
|
||||||
.iter()
|
|
||||||
.find_map(|tag| match Nip34Tag::parse(tag.as_slice()) {
|
|
||||||
Ok(Nip34Tag::BranchName(name)) => Some(name),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The latest PR update, kind 1619, revising `root`.
|
|
||||||
fn latest_update<'a>(events: impl Iterator<Item = &'a Event>, root: &Event) -> Option<&'a Event> {
|
|
||||||
let root_hex = root.id.to_hex();
|
|
||||||
events
|
|
||||||
.filter(|e| e.kind == Kind::GitPullRequestUpdate)
|
|
||||||
.filter(|e| e.pubkey == root.pubkey)
|
|
||||||
.filter(|e| {
|
|
||||||
e.tags
|
|
||||||
.iter()
|
|
||||||
.any(|t| t.kind() == "E" && t.content() == Some(root_hex.as_str()))
|
|
||||||
})
|
|
||||||
.max_by_key(|e| e.created_at)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One-line commit metadata for the commits list.
|
/// One-line commit metadata for the commits list.
|
||||||
///
|
///
|
||||||
/// Author and relative time, whichever is available.
|
/// Author and relative time, whichever is available.
|
||||||
@@ -826,104 +764,9 @@ impl Render for PullRequestDetailView {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use nostr::prelude::{Tag, *};
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
const COMMIT_HEX: &str = "1111111111111111111111111111111111111111";
|
const COMMIT_HEX: &str = "1111111111111111111111111111111111111111";
|
||||||
const OTHER_ROOT_HEX: &str = "2222222222222222222222222222222222222222";
|
|
||||||
|
|
||||||
fn keys() -> Keys {
|
|
||||||
Keys::new(
|
|
||||||
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000001")
|
|
||||||
.expect("valid secret key"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build a signed event with a controlled `created_at`.
|
|
||||||
fn signed(kind: Kind, tags: Vec<Tag>, created_at: u64) -> Event {
|
|
||||||
EventBuilder::new(kind, "")
|
|
||||||
.tags(tags)
|
|
||||||
.custom_created_at(Timestamp::from(created_at))
|
|
||||||
.finalize(&keys())
|
|
||||||
.expect("signed event")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pr_root() -> Event {
|
|
||||||
signed(
|
|
||||||
Kind::GitPullRequest,
|
|
||||||
vec![
|
|
||||||
Tag::parse(["c", COMMIT_HEX]).expect("valid tag"),
|
|
||||||
Tag::parse(["branch-name", "feature/x"]).expect("valid tag"),
|
|
||||||
],
|
|
||||||
100,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn reads_current_commit_and_branch_name() {
|
|
||||||
let pr = pr_root();
|
|
||||||
assert_eq!(current_commit_of(&pr).as_deref(), Some(COMMIT_HEX));
|
|
||||||
assert_eq!(branch_name_of(&pr).as_deref(), Some("feature/x"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn returns_none_without_pr_tags() {
|
|
||||||
let pr = signed(Kind::GitPullRequest, vec![], 100);
|
|
||||||
assert_eq!(current_commit_of(&pr), None);
|
|
||||||
assert_eq!(branch_name_of(&pr), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn latest_update_picks_newest_revision_of_the_root() {
|
|
||||||
let root = pr_root();
|
|
||||||
let root_hex = root.id.to_hex();
|
|
||||||
|
|
||||||
let revision = |created_at: u64| {
|
|
||||||
signed(
|
|
||||||
Kind::GitPullRequestUpdate,
|
|
||||||
vec![Tag::parse(["E", &root_hex]).expect("valid tag")],
|
|
||||||
created_at,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
// An update revising a different PR must be ignored even though it is newer.
|
|
||||||
let unrelated = signed(
|
|
||||||
Kind::GitPullRequestUpdate,
|
|
||||||
vec![Tag::parse(["E", OTHER_ROOT_HEX]).expect("valid tag")],
|
|
||||||
999,
|
|
||||||
);
|
|
||||||
|
|
||||||
let events = [unrelated, revision(200), root.clone(), revision(300)];
|
|
||||||
let latest = latest_update(events.iter(), &root).expect("an update");
|
|
||||||
|
|
||||||
assert_eq!(latest.created_at.as_secs(), 300);
|
|
||||||
assert_eq!(latest.kind, Kind::GitPullRequestUpdate);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn latest_update_ignores_other_authors() {
|
|
||||||
let root = pr_root();
|
|
||||||
let root_hex = root.id.to_hex();
|
|
||||||
let other = Keys::new(
|
|
||||||
SecretKey::from_hex("0000000000000000000000000000000000000000000000000000000000000002")
|
|
||||||
.expect("valid secret key"),
|
|
||||||
);
|
|
||||||
let stranger = EventBuilder::new(Kind::GitPullRequestUpdate, "")
|
|
||||||
.tags([Tag::parse(["E", &root_hex]).expect("valid tag")])
|
|
||||||
.custom_created_at(Timestamp::from(999))
|
|
||||||
.finalize(&other)
|
|
||||||
.expect("signed event");
|
|
||||||
|
|
||||||
// The tip of a PR is only mutable by its author.
|
|
||||||
// A newer update from anyone else must not win.
|
|
||||||
assert!(latest_update([&stranger, &root].into_iter(), &root).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn latest_update_ignores_roots_without_revisions() {
|
|
||||||
let root = pr_root();
|
|
||||||
assert!(latest_update([&root].into_iter(), &root).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn commit_meta_combines_author_and_time() {
|
fn commit_meta_combines_author_and_time() {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user