Compare commits
4
Commits
feat/inbox
...
db3eaff4b9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db3eaff4b9 | ||
|
|
c054f61593 | ||
|
|
6f1256757f | ||
|
|
aaa7aa7ec8 |
@@ -13,6 +13,6 @@ pub use annotations::{COVER_NOTE_KIND, cover_note, labels_and_subject, subject_o
|
||||
pub use clone_url::{CloneTarget, parse_clone_url};
|
||||
pub use comments::{CommentThread, comment_threads};
|
||||
pub use deletions::Deletions;
|
||||
pub use model::{Announcement, activity_subject, pull_request_patch};
|
||||
pub use model::{Announcement, activity_subject, pull_request_patch, pull_request_patches};
|
||||
pub use state::{build_state, parse_state};
|
||||
pub use status::{RepoStatus, references_root, resolve_status};
|
||||
|
||||
@@ -3,6 +3,8 @@ use std::collections::HashSet;
|
||||
use gpui::SharedString;
|
||||
use nostr::prelude::*;
|
||||
|
||||
use crate::RepoAddr;
|
||||
|
||||
/// Parsed NIP-34 repository announcement (plain data, ready for the UI).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Announcement {
|
||||
@@ -28,11 +30,53 @@ pub struct Announcement {
|
||||
pub maintainers: Vec<PublicKey>,
|
||||
/// Value of a `u` tag, if any: this repository is a subordinate fork of
|
||||
/// the referenced upstream (NIP-34).
|
||||
pub upstream: Option<String>,
|
||||
pub upstream: Option<Upstream>,
|
||||
/// Hashtags labelling the repository (`t` tags).
|
||||
pub hashtags: Vec<String>,
|
||||
}
|
||||
|
||||
/// The `u` tag of a fork announcement (NIP-34): the repository this one is a
|
||||
/// subordinate fork of. The first value is the upstream coordinate
|
||||
/// (`30617:<pubkey>:<id>`) or a git URL; the second is an optional relay hint
|
||||
/// for the upstream.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Upstream {
|
||||
/// Raw first value of the `u` tag (coordinate or git URL).
|
||||
pub raw: String,
|
||||
/// The upstream `30617:<pubkey>:<id>` coordinate, when the `u` tag
|
||||
/// references a NIP-34 repository; `None` for the git-URL form.
|
||||
pub addr: Option<RepoAddr>,
|
||||
/// Relay hint for the upstream, if the `u` tag carries one.
|
||||
pub relay_hint: Option<RelayUrl>,
|
||||
}
|
||||
|
||||
impl Upstream {
|
||||
/// Parse the `u` tag values. The first is the upstream coordinate or a
|
||||
/// git URL (the coordinate form may append `|git-url`; the coordinate is
|
||||
/// the part before the first `|`), the second an optional relay hint.
|
||||
fn parse(raw: &str, relay_hint: Option<&str>) -> Self {
|
||||
let coordinate = raw.split('|').next().unwrap_or(raw);
|
||||
let addr = coordinate
|
||||
.parse::<Coordinate>()
|
||||
.ok()
|
||||
.filter(|c| c.kind == Kind::GitRepoAnnouncement);
|
||||
Self {
|
||||
raw: raw.to_owned(),
|
||||
addr,
|
||||
relay_hint: relay_hint.and_then(|hint| RelayUrl::parse(hint).ok()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text for display: the upstream coordinate when it is a NIP-34
|
||||
/// repository, otherwise the raw `u` value (git-URL form).
|
||||
pub fn display(&self) -> SharedString {
|
||||
match &self.addr {
|
||||
Some(addr) => SharedString::from(addr.to_string()),
|
||||
None => SharedString::from(self.raw.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Subject of a NIP-34 issue or pull request event: the `subject` tag,
|
||||
/// falling back to the first non-empty line of the content.
|
||||
pub fn activity_subject(event: &Event) -> SharedString {
|
||||
@@ -193,7 +237,7 @@ impl Announcement {
|
||||
let mut relays: Vec<RelayUrl> = Vec::new();
|
||||
let mut euc: Option<String> = None;
|
||||
let mut maintainers: Vec<PublicKey> = Vec::new();
|
||||
let mut upstream: Option<String> = None;
|
||||
let mut upstream: Option<Upstream> = None;
|
||||
|
||||
for tag in event.tags.iter() {
|
||||
match Nip34Tag::parse(tag.as_slice()) {
|
||||
@@ -208,9 +252,13 @@ impl Announcement {
|
||||
}
|
||||
|
||||
// The `u` tag is not modelled by the SDK's `Nip34Tag`; parse it
|
||||
// manually (first value wins).
|
||||
// manually (first wins).
|
||||
if upstream.is_none() && tag.kind() == "u" {
|
||||
upstream = tag.content().map(str::to_owned);
|
||||
let values = tag.as_slice();
|
||||
let raw = values.get(1).map(String::as_str).unwrap_or_default();
|
||||
if !raw.is_empty() {
|
||||
upstream = Some(Upstream::parse(raw, values.get(2).map(String::as_str)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -391,14 +439,55 @@ mod tests {
|
||||
fn parses_upstream_tag() {
|
||||
let event = announcement_event(&[
|
||||
&["d", "my-fork"],
|
||||
&["u", "30617:abc:upstream|https://example.com/upstream.git"],
|
||||
&[
|
||||
"u",
|
||||
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git",
|
||||
"wss://relay.example.com",
|
||||
],
|
||||
]);
|
||||
|
||||
let announcement = Announcement::from_event(&event).expect("parses");
|
||||
let upstream = announcement.upstream.expect("parses the u tag");
|
||||
|
||||
// The coordinate part resolves to a repository address; the raw
|
||||
// value keeps the `|git-url` suffix.
|
||||
assert_eq!(
|
||||
announcement.upstream.as_deref(),
|
||||
Some("30617:abc:upstream|https://example.com/upstream.git")
|
||||
upstream.addr,
|
||||
Some(crate::repo_addr(
|
||||
PublicKey::from_hex(MAINTAINER_HEX).expect("valid pubkey"),
|
||||
"upstream"
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
upstream.raw,
|
||||
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream|https://example.com/upstream.git"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream.relay_hint,
|
||||
Some(RelayUrl::parse("wss://relay.example.com").expect("valid relay"))
|
||||
);
|
||||
assert_eq!(
|
||||
upstream.display().to_string(),
|
||||
"30617:68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272:upstream"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_git_url_upstream() {
|
||||
// The `u` tag may reference a non-nostr upstream by git URL only;
|
||||
// there is no repository address to navigate to.
|
||||
let event = announcement_event(&[
|
||||
&["d", "my-fork"],
|
||||
&["u", "https://example.com/upstream.git"],
|
||||
]);
|
||||
|
||||
let announcement = Announcement::from_event(&event).expect("parses");
|
||||
let upstream = announcement.upstream.expect("parses the u tag");
|
||||
|
||||
assert_eq!(upstream.addr, None);
|
||||
assert_eq!(
|
||||
upstream.display().to_string(),
|
||||
"https://example.com/upstream.git"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -195,6 +195,185 @@ pub fn apply_patch(repo_path: &Path, patch: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The merge base of two revisions (branch names, remote-tracking refs or
|
||||
/// commit ids) in the repository at `repo_path`. `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 output = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo_path)
|
||||
.args(["merge-base", a, b])
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.context("failed to spawn `git merge-base`")?;
|
||||
|
||||
match output.status.code() {
|
||||
// Exit 1: no common ancestor (a valid outcome for a proposal).
|
||||
Some(1) => Ok(None),
|
||||
Some(0) => Ok(Some(
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_owned(),
|
||||
)),
|
||||
_ => bail!(
|
||||
"git merge-base failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `git format-patch` series of `base..tip` (mbox), 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)
|
||||
}
|
||||
|
||||
/// Whether `patch` (a `git format-patch` series) applies to the working
|
||||
/// tree of `repo_path`, without modifying anything
|
||||
/// (`git apply --check --3way`). Best-effort: useful to surface conflicts
|
||||
/// before a patch is published or applied.
|
||||
pub fn patch_applies(repo_path: &Path, patch: &str) -> Result<()> {
|
||||
let mut child = Command::new("git")
|
||||
.arg("apply")
|
||||
.args(["--check", "--3way", "--whitespace=nowarn", "-"])
|
||||
.current_dir(repo_path)
|
||||
.stdin(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.context("failed to spawn `git apply --check`")?;
|
||||
|
||||
child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.expect("stdin piped")
|
||||
.write_all(patch.as_bytes())?;
|
||||
|
||||
let output = child.wait_with_output()?;
|
||||
if !output.status.success() {
|
||||
bail!(
|
||||
"patch does not apply: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Push `commit` to `reference` (e.g. `refs/nostr/<event-id>`) on the git
|
||||
/// server at `url`, from the repository at `repo_path`. GRASP servers host
|
||||
/// the `refs/nostr` namespace so anyone can contribute a commit; nak pushes
|
||||
/// pull request tips there before publishing the PR event, and readers
|
||||
/// fetch the ref to get the commit behind a PR's `c` tag.
|
||||
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(())
|
||||
}
|
||||
|
||||
/// Split a `git format-patch` series into its individual patches (mbox
|
||||
/// messages). Each message begins with a `From <40-hex> ` boundary line;
|
||||
/// `>From` quoting inside bodies means no false positives. 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()
|
||||
}
|
||||
|
||||
/// The commit HEAD points to in the repository at `repo_path`, or `None`
|
||||
/// when the repository has no commits yet (unborn HEAD).
|
||||
pub fn head_commit_id(repo_path: &Path) -> Result<Option<String>> {
|
||||
let output = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo_path)
|
||||
.args(["rev-parse", "HEAD"])
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.context("failed to spawn `git rev-parse`")?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
/// The commits in `base..HEAD` of the repository at `repo_path`, oldest
|
||||
/// first (the order `git am` creates them); `HEAD` alone when `base` is
|
||||
/// `None`. An empty range yields an empty list.
|
||||
pub fn commits_since(repo_path: &Path, base: Option<&str>) -> Result<Vec<String>> {
|
||||
let output = match base {
|
||||
Some(base) => git_in(
|
||||
repo_path,
|
||||
&["rev-list", "--reverse", &format!("{base}..HEAD")],
|
||||
)?,
|
||||
// No `base` (unborn HEAD): there is nothing to walk yet.
|
||||
None => match git_in(repo_path, &["rev-parse", "HEAD"]) {
|
||||
Ok(head) => head,
|
||||
Err(_) => return Ok(Vec::new()),
|
||||
},
|
||||
};
|
||||
Ok(output
|
||||
.lines()
|
||||
.map(str::to_owned)
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn clone(url: &str, path: &Path) -> Result<gix::Repository> {
|
||||
// GRASP servers announce `grasp://<host>/<owner>/<repo>` clone URLs;
|
||||
// the transport is git smart HTTP, so rewrite the scheme for gix.
|
||||
@@ -1884,6 +2063,200 @@ mod tests {
|
||||
git_run(repo.workdir().expect("workdir"), &["commit", "-m", message]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_base_finds_the_fork_point_and_reports_unrelated_history() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("repo");
|
||||
let initial = init_repository(&path, "My Repo", "desc").expect("init");
|
||||
|
||||
// A feature branch and a mainline commit diverge from the initial
|
||||
// commit; it is their merge base.
|
||||
git_run(&path, &["checkout", "-b", "feature"]);
|
||||
std::fs::write(path.join("feature.txt"), "feature\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "feature commit");
|
||||
git_run(&path, &["checkout", "main"]);
|
||||
std::fs::write(path.join("main.txt"), "main\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "mainline commit");
|
||||
|
||||
assert_eq!(
|
||||
merge_base(&path, "feature", "main")
|
||||
.expect("merge base")
|
||||
.as_deref(),
|
||||
Some(initial.as_str())
|
||||
);
|
||||
|
||||
// An orphan branch shares no history with main: `Ok(None)`.
|
||||
git_run(&path, &["checkout", "--orphan", "orphan"]);
|
||||
std::fs::write(path.join("orphan.txt"), "orphan\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "orphan commit");
|
||||
assert_eq!(merge_base(&path, "orphan", "main").expect("ok"), None);
|
||||
|
||||
// An unresolvable revision is an error, not a missing ancestor.
|
||||
assert!(merge_base(&path, "orphan", "no-such-ref").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_patch_between_produces_the_series_and_rejects_empty_ranges() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("repo");
|
||||
let initial = init_repository(&path, "My Repo", "desc").expect("init");
|
||||
|
||||
git_run(&path, &["checkout", "-b", "feature"]);
|
||||
std::fs::write(path.join("feature.txt"), "feature\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "feature commit");
|
||||
|
||||
let patch = format_patch_between(&path, &initial, "feature").expect("patch");
|
||||
assert!(patch.contains("Subject: [PATCH] feature commit"));
|
||||
assert!(patch.contains("feature.txt"));
|
||||
|
||||
// An empty range has no commits to send.
|
||||
assert!(format_patch_between(&path, "feature", "feature").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patch_applies_checks_without_modifying_the_tree() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("repo");
|
||||
let initial = init_repository(&path, "My Repo", "desc").expect("init");
|
||||
|
||||
git_run(&path, &["checkout", "-b", "feature"]);
|
||||
std::fs::write(path.join("feature.txt"), "feature\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "feature commit");
|
||||
let patch = format_patch_between(&path, &initial, "feature").expect("patch");
|
||||
|
||||
// A clone of the initial state accepts the series...
|
||||
let clone = dir.path().join("clone");
|
||||
git_run(
|
||||
dir.path(),
|
||||
&[
|
||||
"clone",
|
||||
"-q",
|
||||
path.to_str().unwrap(),
|
||||
clone.to_str().unwrap(),
|
||||
],
|
||||
);
|
||||
git_run(&clone, &["checkout", "-q", &initial]);
|
||||
assert!(patch_applies(&clone, &patch).is_ok());
|
||||
// ...and the check must not have modified the working tree.
|
||||
assert!(!clone.join("feature.txt").exists());
|
||||
|
||||
// A conflicting file makes the same series fail the check.
|
||||
std::fs::write(clone.join("feature.txt"), "conflicting\n").expect("write");
|
||||
assert!(patch_applies(&clone, &patch).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_commit_ref_pushes_to_the_event_namespace() {
|
||||
// A bare "server" repository reachable via a `file://` URL, like a
|
||||
// grasp server's `{base}/{owner}/{repo-id}.git` layout.
|
||||
let server = tempfile::tempdir().unwrap();
|
||||
let server_repo = server.path().join("npub1test").join("my-repo.git");
|
||||
std::fs::create_dir_all(server_repo.parent().unwrap()).unwrap();
|
||||
let init_status = Command::new("git")
|
||||
.args(["init", "--bare", "-q"])
|
||||
.arg(&server_repo)
|
||||
.status()
|
||||
.expect("spawn git init --bare");
|
||||
assert!(init_status.success());
|
||||
|
||||
let (dir, repo) = fixture(&[("a.txt", b"one")]);
|
||||
commit_all(&repo, "initial");
|
||||
let dir = dir.path();
|
||||
let tip = git_in(dir, &["rev-parse", "HEAD"]).expect("tip");
|
||||
|
||||
let url = format!("file://{}/npub1test/my-repo.git", server.path().display());
|
||||
push_commit_ref(dir, &url, &tip, "refs/nostr/abcd1234").expect("push");
|
||||
|
||||
let refs = git_in(&server_repo, &["show-ref"]).expect("server refs");
|
||||
assert!(refs.contains("refs/nostr/abcd1234"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_patch_series_splits_real_multi_commit_mboxes() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("repo");
|
||||
let initial = init_repository(&path, "My Repo", "desc").expect("init");
|
||||
|
||||
git_run(&path, &["checkout", "-b", "feature"]);
|
||||
std::fs::write(path.join("one.txt"), "one\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "first commit");
|
||||
std::fs::write(path.join("two.txt"), "two\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "second commit");
|
||||
|
||||
let series = format_patch_between(&path, &initial, "feature").expect("series");
|
||||
let parts = split_patch_series(&series);
|
||||
|
||||
assert_eq!(parts.len(), 2);
|
||||
assert!(parts[0].contains("Subject: [PATCH 1/2] first commit"));
|
||||
assert!(parts[1].contains("Subject: [PATCH 2/2] second commit"));
|
||||
// Each part starts its own mbox message with its own commit id.
|
||||
let first = parts[0].lines().next().expect("first header");
|
||||
let second = parts[1].lines().next().expect("second header");
|
||||
assert!(first.starts_with("From ") && first.len() >= 45);
|
||||
assert_ne!(first, second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_patch_series_keeps_single_patches_whole() {
|
||||
let patch = "From abcdefabcdefabcdefabcdefabcdefabcdefab Mon Sep 17 00:00:00 2001\nFrom: A <a@b>\nSubject: [PATCH] fix\n\n---\n";
|
||||
let parts = split_patch_series(patch);
|
||||
assert_eq!(parts.len(), 1);
|
||||
assert_eq!(parts[0], patch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_commit_and_commits_since_track_applied_commits() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("repo");
|
||||
let initial = init_repository(&path, "My Repo", "desc").expect("init");
|
||||
|
||||
assert_eq!(
|
||||
head_commit_id(&path).expect("head").as_deref(),
|
||||
Some(initial.as_str())
|
||||
);
|
||||
// No commits yet: `HEAD` alone.
|
||||
assert_eq!(
|
||||
commits_since(&path, None).expect("commits"),
|
||||
vec![initial.clone()]
|
||||
);
|
||||
|
||||
std::fs::write(path.join("one.txt"), "one\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "first commit");
|
||||
let first = head_commit_id(&path).expect("head").expect("on a branch");
|
||||
|
||||
std::fs::write(path.join("two.txt"), "two\n").expect("write");
|
||||
commit_all(&gix::open(&path).expect("open"), "second commit");
|
||||
let second = head_commit_id(&path).expect("head").expect("on a branch");
|
||||
|
||||
// Oldest first, like the order `git am` creates them.
|
||||
assert_eq!(
|
||||
commits_since(&path, Some(&initial)).expect("commits"),
|
||||
vec![first.clone(), second.clone()]
|
||||
);
|
||||
assert_eq!(
|
||||
commits_since(&path, Some(&first)).expect("commits"),
|
||||
vec![second]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_commit_reports_unborn_repositories() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("repo");
|
||||
let status = Command::new("git")
|
||||
.args(["init", "-q"])
|
||||
.arg(&path)
|
||||
.status()
|
||||
.expect("spawn git init");
|
||||
assert!(status.success());
|
||||
|
||||
assert_eq!(head_commit_id(&path).expect("head"), None);
|
||||
assert_eq!(
|
||||
commits_since(&path, None).expect("commits"),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_repository_creates_main_branch_and_readme() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
|
||||
@@ -1302,6 +1302,55 @@ impl Backend {
|
||||
})
|
||||
}
|
||||
|
||||
/// Broadcast and locally store an already-signed event, like
|
||||
/// [`Self::send`] without the signing step. Callers that signed early
|
||||
/// (e.g. to learn the event id before pushing a commit to the grasp
|
||||
/// servers) publish through this.
|
||||
pub fn publish_event(
|
||||
&mut self,
|
||||
event: Event,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<Event, Error>> {
|
||||
let client = self.client.clone();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
let work = cx.background_spawn(async move {
|
||||
let output = client.send_event(&event).await?;
|
||||
|
||||
if output.success.is_empty() && !output.failed.is_empty() {
|
||||
let reasons = output
|
||||
.failed
|
||||
.values()
|
||||
.cloned()
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ");
|
||||
return Err(anyhow!("event not accepted by any relay: {reasons}"));
|
||||
}
|
||||
|
||||
Ok(event.clone())
|
||||
});
|
||||
|
||||
let result = work.await;
|
||||
|
||||
match &result {
|
||||
Ok(event) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::Published(Box::new(event.clone())));
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::error(e.to_string()));
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
/// Publish a NIP-34 repository announcement (kind 30617) with the
|
||||
/// current signer. The returned task yields the published event, so
|
||||
/// callers can show inline progress/errors.
|
||||
@@ -1414,7 +1463,12 @@ async fn connect_repo_relays_only(
|
||||
let relays = &relays;
|
||||
let sync_opts = sync_opts.clone();
|
||||
async move {
|
||||
if let Err(e) = client.sync(filter).with(relays.iter()).opts(sync_opts).await {
|
||||
if let Err(e) = client
|
||||
.sync(filter)
|
||||
.with(relays.iter())
|
||||
.opts(sync_opts)
|
||||
.await
|
||||
{
|
||||
log::warn!("repo relay negentropy sync failed: {e}");
|
||||
}
|
||||
}
|
||||
@@ -1469,7 +1523,7 @@ fn with_master_key(uri: &str, keys: &Keys) -> String {
|
||||
/// A `https://<host>` (or `http://<host>` for `ws://` grasp servers, like
|
||||
/// ngit) base URL for a grasp server. The repository then lives at
|
||||
/// `{base}/{npub}/{repo-id}.git`.
|
||||
fn grasp_base_url(relay: &RelayUrl) -> Option<String> {
|
||||
pub(crate) fn grasp_base_url(relay: &RelayUrl) -> Option<String> {
|
||||
// `domain()` drops the port; parse the full URL to keep it (local dev
|
||||
// grasp servers commonly run on a custom port).
|
||||
let parsed = Url::parse(relay.as_str()).ok()?;
|
||||
|
||||
@@ -163,7 +163,8 @@ impl ProfileStore {
|
||||
|
||||
/// Load recently seen profiles from the local database.
|
||||
fn load(&mut self, cx: &mut Context<Self>) {
|
||||
let client = Backend::global(cx).read(cx).client();
|
||||
let backend = Backend::global(cx);
|
||||
let client = backend.read(cx).client();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
let filter = Filter::new().kind(Kind::Metadata).limit(200);
|
||||
@@ -197,7 +198,8 @@ impl ProfileStore {
|
||||
|
||||
/// Re-read the latest metadata of an author from the local database.
|
||||
fn apply_author(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
||||
let client = Backend::global(cx).read(cx).client();
|
||||
let backend = Backend::global(cx);
|
||||
let client = backend.read(cx).client();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
let filter = Filter::new().kind(Kind::Metadata).author(public_key);
|
||||
@@ -238,7 +240,8 @@ impl ProfileStore {
|
||||
return;
|
||||
}
|
||||
|
||||
let client = Backend::global(cx).read(cx).client();
|
||||
let backend = Backend::global(cx);
|
||||
let client = backend.read(cx).client();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
let filter = Filter::new().kind(Kind::Metadata).authors(authors);
|
||||
|
||||
+461
-53
@@ -1,23 +1,30 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Error;
|
||||
use gpui::{AppContext, Context, Subscription, Task};
|
||||
use bitcoin_hashes::sha1::Hash as Sha1Hash;
|
||||
use gpui::{AppContext, AsyncApp, Context, Subscription, Task, WeakEntity};
|
||||
use nostr::event::IntoEventBuilder;
|
||||
use nostr_sdk::prelude::*;
|
||||
use signed_core::{
|
||||
Announcement, COVER_NOTE_KIND, Deletions, RepoAddr, RepoStatus, build_state, cover_note,
|
||||
filters, labels_and_subject, parse_state, pull_request_patch, subject_override,
|
||||
filters, labels_and_subject, parse_state, pull_request_patch, pull_request_patches,
|
||||
subject_override,
|
||||
};
|
||||
|
||||
use crate::backend::{Backend, BackendEvent};
|
||||
use crate::backend::{Backend, BackendEvent, grasp_base_url};
|
||||
use crate::git_store::GitStore;
|
||||
|
||||
/// Delay between a refresh request and the actual re-query, so bursts of
|
||||
/// events (e.g. per-event `NostrUpdate`s) collapse into one query.
|
||||
const REFRESH_DEBOUNCE: Duration = Duration::from_millis(300);
|
||||
|
||||
/// Maximum size of one patch event, following NIP-34's guidance that
|
||||
/// patches should be used when each event is under 60kb.
|
||||
const MAX_PATCH_EVENT_BYTES: usize = 60 * 1024;
|
||||
|
||||
/// Per-repository store: announcement, state, issues, patches, PRs,
|
||||
/// comments and their resolved statuses. Always derived from the local
|
||||
/// database.
|
||||
@@ -50,6 +57,9 @@ pub struct RepoStore {
|
||||
version: u64,
|
||||
/// Error of the last action initiated from this store, if any.
|
||||
pub last_error: Option<String>,
|
||||
/// Non-fatal warning of the last action (e.g. a PR published without
|
||||
/// its commit reaching a grasp server), if any.
|
||||
pub last_warning: Option<String>,
|
||||
/// Relays announced by this repository (NIP-34 `relays` tag) that we
|
||||
/// have already been asked to connect to and fetch from, to avoid
|
||||
/// re-subscribing on every refresh.
|
||||
@@ -128,6 +138,7 @@ impl RepoStore {
|
||||
labels: Vec::new(),
|
||||
version: 0,
|
||||
last_error: None,
|
||||
last_warning: None,
|
||||
repo_relays: HashSet::new(),
|
||||
root_fetches: HashSet::new(),
|
||||
refreshing: false,
|
||||
@@ -235,7 +246,8 @@ impl RepoStore {
|
||||
fn run_refresh(&mut self, cx: &mut Context<Self>) {
|
||||
self.refreshing = true;
|
||||
|
||||
let client = Backend::global(cx).read(cx).client();
|
||||
let backend = Backend::global(cx);
|
||||
let client = backend.read(cx).client();
|
||||
let addr = self.addr.clone();
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
@@ -617,23 +629,60 @@ impl RepoStore {
|
||||
/// (kind 1617) carrying the `git format-patch` output, which the PR
|
||||
/// references via an `e` tag (NIP-34).
|
||||
///
|
||||
/// The patch is published first so the PR can reference its id. The
|
||||
/// proposed commit is parsed from the patch's `From <commit>` header;
|
||||
/// without one publishing is refused, because the PR's `c` tag must
|
||||
/// carry a real commit id for other NIP-34 clients to verify and apply
|
||||
/// the proposal. The `clone` tag carries the announced mirror URLs; the
|
||||
/// linked patch is the source of truth until the commit is pushed there.
|
||||
/// The patch series is published first (one kind-1617 event per commit,
|
||||
/// chained with NIP-10 `e` replies, each under [`MAX_PATCH_EVENT_BYTES`])
|
||||
/// so the PR can reference the root patch's id. The proposed commit is
|
||||
/// parsed from the series' last `From <commit>` header (the tip); without
|
||||
/// one publishing is refused, because the PR's `c` tag must carry a real
|
||||
/// commit id for other NIP-34 clients to verify and apply the proposal.
|
||||
/// The `clone` tag carries the announced mirror URLs, and when
|
||||
/// `push_from` is set the tip is pushed to those servers under
|
||||
/// `refs/nostr/<event-id>` (best-effort) before the PR is published, so
|
||||
/// the commit is actually downloadable there; the linked patch stays the
|
||||
/// source of truth either way.
|
||||
///
|
||||
/// `branch_name` lands in the PR's `branch-name` tag (NIP-34); `draft`
|
||||
/// publishes a kind-1633 status right after the PR event. `merge_base`
|
||||
/// is the hex commit the proposed branch forked from, computed from a
|
||||
/// local checkout when the patch was generated there.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn open_pull_request(
|
||||
&mut self,
|
||||
subject: Option<String>,
|
||||
description: String,
|
||||
branch_name: Option<String>,
|
||||
patch: String,
|
||||
draft: bool,
|
||||
merge_base: Option<String>,
|
||||
push_from: Option<PathBuf>,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
self.last_error = None;
|
||||
self.last_warning = None;
|
||||
|
||||
let Some(current_commit) =
|
||||
patch_current_commit(&patch).and_then(|hex| hex.parse::<bitcoin_hashes::Sha1>().ok())
|
||||
let series: Vec<String> = signed_git::split_patch_series(&patch)
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if let Some(oversized) = series
|
||||
.iter()
|
||||
.find(|part| part.len() > MAX_PATCH_EVENT_BYTES)
|
||||
{
|
||||
self.last_error = Some(format!(
|
||||
"patch too large ({} bytes; NIP-34 suggests keeping each patch under {} bytes)",
|
||||
oversized.len(),
|
||||
MAX_PATCH_EVENT_BYTES
|
||||
));
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
|
||||
// The tip of the series is its last commit; `git format-patch`
|
||||
// orders patches oldest first.
|
||||
let Some(current_commit) = series
|
||||
.last()
|
||||
.and_then(|part| patch_current_commit(part))
|
||||
.and_then(|hex| hex.parse::<Sha1Hash>().ok())
|
||||
else {
|
||||
self.last_error = Some(
|
||||
"Patch must be `git format-patch` output with a `From <commit-id>` header".into(),
|
||||
@@ -642,35 +691,41 @@ impl RepoStore {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(root_marker) = Tag::parse(["t", "root"]) else {
|
||||
let backend = Backend::global(cx);
|
||||
if backend.read(cx).current_user().is_none() {
|
||||
self.last_error = Some("Sign in to open a pull request".into());
|
||||
cx.notify();
|
||||
return;
|
||||
};
|
||||
let commit_hex = current_commit.to_string();
|
||||
let mut patch_tags = vec![
|
||||
Tag::coordinate(self.addr.clone(), None),
|
||||
Tag::public_key(self.addr.public_key),
|
||||
root_marker,
|
||||
];
|
||||
// NIP-34: the `r` EUC tag lets clients subscribe to all patches of
|
||||
// this repository; `commit`/`r` tags reference the proposed commit.
|
||||
if let Some(euc) = self.announcement.as_ref().and_then(|a| a.euc.clone())
|
||||
&& let Ok(tag) = Tag::parse(["r", &euc])
|
||||
{
|
||||
patch_tags.push(tag);
|
||||
}
|
||||
if let Ok(tag) = Tag::parse(["commit", &commit_hex]) {
|
||||
patch_tags.push(tag);
|
||||
}
|
||||
if let Ok(tag) = Tag::parse(["r", &commit_hex]) {
|
||||
patch_tags.push(tag);
|
||||
}
|
||||
let patch_builder = EventBuilder::new(Kind::GitPatch, patch).tags(patch_tags);
|
||||
let signer = backend.read(cx).signer();
|
||||
|
||||
let patch_task =
|
||||
Backend::global(cx).update(cx, |backend, cx| backend.send(patch_builder, cx));
|
||||
let addr = self.addr.clone();
|
||||
let owner = self.addr.public_key;
|
||||
let euc = self.announcement.as_ref().and_then(|a| a.euc.clone());
|
||||
let (push_owner, push_repo_id, push_relays) = self
|
||||
.announcement
|
||||
.as_ref()
|
||||
.map(|a| {
|
||||
let owner = a.owner.to_bech32().unwrap_or_else(|_| a.owner.to_hex());
|
||||
(owner, a.id.clone(), a.relays.clone())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
let patch_event = match patch_task.await {
|
||||
// The PR references the root patch event so viewers can find
|
||||
// the patch without carrying it inline.
|
||||
let root_patch = match publish_patch_series(
|
||||
&this,
|
||||
cx,
|
||||
&addr,
|
||||
owner,
|
||||
euc.as_deref(),
|
||||
&series,
|
||||
"root",
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(event) => event,
|
||||
Err(e) => {
|
||||
return this.update(cx, |this, cx| {
|
||||
@@ -680,33 +735,226 @@ impl RepoStore {
|
||||
}
|
||||
};
|
||||
|
||||
// The PR references the patch event so viewers can find the
|
||||
// patch without carrying it inline.
|
||||
let pr_task = this.update(cx, |this, cx| {
|
||||
let builder = this.update(cx, |this, _cx| {
|
||||
let builder = GitPullRequest {
|
||||
repository: this.addr.clone(),
|
||||
content: description,
|
||||
subject,
|
||||
labels: Vec::new(),
|
||||
branch_name: None,
|
||||
branch_name,
|
||||
// NIP-34: PRs carry at least one clone URL where the
|
||||
// tip commit can be downloaded; use the repository's
|
||||
// announced mirrors until a push backend exists.
|
||||
// tip commit can be downloaded; the announced mirrors
|
||||
// are also the servers the tip is pushed to below.
|
||||
clone: this
|
||||
.announcement
|
||||
.as_ref()
|
||||
.map(|a| a.clone.clone())
|
||||
.unwrap_or_default(),
|
||||
current_commit,
|
||||
root_patch_event: Some(patch_event.id),
|
||||
root_patch_event: Some(root_patch.id),
|
||||
merge_base: merge_base
|
||||
.and_then(|hex| hex.parse::<bitcoin_hashes::Sha1>().ok()),
|
||||
}
|
||||
.into_event_builder();
|
||||
|
||||
// NIP-34: the `r` EUC tag lets clients subscribe to all
|
||||
// PRs of this repository; the SDK builder omits it.
|
||||
match this.announcement.as_ref().and_then(|a| a.euc.clone()) {
|
||||
Some(euc) => builder.tag(Tag::parse(["r", &euc]).expect("valid r tag")),
|
||||
None => builder,
|
||||
}
|
||||
})?;
|
||||
|
||||
// Sign before publishing so the tip can be pushed to the grasp
|
||||
// servers under `refs/nostr/<event-id>` (nak's convention):
|
||||
// readers fetch that ref to get the commit behind the `c` tag.
|
||||
let event = cx
|
||||
.background_spawn({
|
||||
let signer = signer.clone();
|
||||
async move { builder.finalize_async(&signer).await }
|
||||
})
|
||||
.await?;
|
||||
|
||||
if let Some(path) = push_from.as_ref() {
|
||||
let tip = current_commit.to_string();
|
||||
let reference = format!("refs/nostr/{}", event.id.to_hex());
|
||||
let (pushed, failures) = cx
|
||||
.background_spawn({
|
||||
let path = path.clone();
|
||||
let tip = tip.clone();
|
||||
let reference = reference.clone();
|
||||
let owner = push_owner.clone();
|
||||
let repo_id = push_repo_id.clone();
|
||||
let relays = push_relays.clone();
|
||||
async move {
|
||||
let mut failures = Vec::new();
|
||||
let mut pushed = 0;
|
||||
for relay in &relays {
|
||||
let Some(base) = grasp_base_url(relay) else {
|
||||
continue;
|
||||
};
|
||||
let url = format!("{base}/{owner}/{repo_id}.git");
|
||||
match signed_git::push_commit_ref(&path, &url, &tip, &reference) {
|
||||
Ok(()) => pushed += 1,
|
||||
Err(e) => failures.push(format!("{relay}: {e}")),
|
||||
}
|
||||
}
|
||||
(pushed, failures)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if pushed == 0 {
|
||||
this.update(cx, |this, cx| {
|
||||
this.last_warning = Some(format!(
|
||||
"Pull request published, but the commit could not be pushed to any grasp server ({}); the patch is still the source of truth",
|
||||
failures.join("; ")
|
||||
));
|
||||
cx.notify();
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
let publish_task = this.update(cx, |_this, cx| {
|
||||
let backend = Backend::global(cx);
|
||||
backend.update(cx, |backend, cx| backend.publish_event(event, cx))
|
||||
})?;
|
||||
let pr_event = match publish_task.await {
|
||||
Ok(event) => event,
|
||||
Err(e) => {
|
||||
return this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// NIP-34: a draft PR carries a kind-1633 status event; publish
|
||||
// it right after the PR event so viewers never show it open.
|
||||
if draft {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_status(&pr_event, RepoStatus::Draft, cx);
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// Update a pull request: publish revision patch events chained to the
|
||||
/// original root patch (`t root-revision` and a NIP-10 `e` reply on the
|
||||
/// first, per NIP-34), then a kind-1619 PR update event carrying the
|
||||
/// new tip.
|
||||
///
|
||||
/// Only the PR author may update it; other authors must open a new PR.
|
||||
pub fn update_pull_request(&mut self, root: &Event, patch: String, cx: &mut Context<Self>) {
|
||||
self.last_error = None;
|
||||
self.last_warning = None;
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
|
||||
let Some(user) = backend.read(cx).current_user() else {
|
||||
self.last_error = Some("Sign in to update the pull request".into());
|
||||
cx.notify();
|
||||
return;
|
||||
};
|
||||
|
||||
if user != root.pubkey {
|
||||
self.last_error = Some("Only the pull request author can update it".into());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
|
||||
let series: Vec<String> = signed_git::split_patch_series(&patch)
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if let Some(oversized) = series
|
||||
.iter()
|
||||
.find(|part| part.len() > MAX_PATCH_EVENT_BYTES)
|
||||
{
|
||||
self.last_error = Some(format!(
|
||||
"patch too large ({} bytes; NIP-34 suggests keeping each patch under {} bytes)",
|
||||
oversized.len(),
|
||||
MAX_PATCH_EVENT_BYTES
|
||||
));
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
|
||||
// The new tip of the PR is the last commit of the series.
|
||||
let Some(current_commit) = series
|
||||
.last()
|
||||
.and_then(|part| patch_current_commit(part))
|
||||
.and_then(|hex| hex.parse::<Sha1Hash>().ok())
|
||||
else {
|
||||
self.last_error = Some(
|
||||
"Patch must be `git format-patch` output with a `From <commit-id>` header".into(),
|
||||
);
|
||||
cx.notify();
|
||||
return;
|
||||
};
|
||||
|
||||
// NIP-34: the first patch of a revision replies to the original
|
||||
// root patch (the PR's `e` tag; fall back to the oldest patch of
|
||||
// the linked set for PRs without one).
|
||||
let root_patch_id = root.tags.event_ids().next().or_else(|| {
|
||||
pull_request_patches(root, self.patches.iter())
|
||||
.first()
|
||||
.map(|p| p.id)
|
||||
});
|
||||
|
||||
let addr = self.addr.clone();
|
||||
let owner = self.addr.public_key;
|
||||
let euc = self.announcement.as_ref().and_then(|a| a.euc.clone());
|
||||
let root = root.clone();
|
||||
let clone: Vec<Url> = self
|
||||
.announcement
|
||||
.as_ref()
|
||||
.map(|a| a.clone.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
if let Err(e) = publish_patch_series(
|
||||
&this,
|
||||
cx,
|
||||
&addr,
|
||||
owner,
|
||||
euc.as_deref(),
|
||||
&series,
|
||||
"root-revision",
|
||||
root_patch_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
|
||||
let update_task = this.update(cx, |this, cx| {
|
||||
let builder = GitPullRequestUpdate {
|
||||
repository: this.addr.clone(),
|
||||
pull_request_event: root.id,
|
||||
pull_request_author: root.pubkey,
|
||||
current_commit,
|
||||
clone: clone.clone(),
|
||||
merge_base: None,
|
||||
}
|
||||
.into_event_builder();
|
||||
|
||||
Backend::global(cx).update(cx, |backend, cx| backend.send(builder, cx))
|
||||
// NIP-34: the `r` EUC tag lets clients subscribe to all PR
|
||||
// updates of this repository; the SDK builder omits it.
|
||||
let builder = match euc.as_deref() {
|
||||
Some(euc) => builder.tag(Tag::parse(["r", euc]).expect("valid r tag")),
|
||||
None => builder,
|
||||
};
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
backend.update(cx, |backend, cx| backend.send(builder, cx))
|
||||
})?;
|
||||
|
||||
if let Err(e) = pr_task.await {
|
||||
if let Err(e) = update_task.await {
|
||||
return this.update(cx, |this, cx| {
|
||||
this.last_error = Some(e.to_string());
|
||||
cx.notify();
|
||||
@@ -729,7 +977,8 @@ impl RepoStore {
|
||||
.map(Announcement::effective_maintainers)
|
||||
.unwrap_or_default();
|
||||
|
||||
let Some(user) = Backend::global(cx).read(cx).current_user() else {
|
||||
let backend = Backend::global(cx);
|
||||
let Some(user) = backend.read(cx).current_user() else {
|
||||
self.last_error = Some("Sign in to change the status".into());
|
||||
cx.notify();
|
||||
return;
|
||||
@@ -761,7 +1010,8 @@ impl RepoStore {
|
||||
pub fn publish_state(&mut self, cx: &mut Context<Self>) {
|
||||
self.last_error = None;
|
||||
|
||||
let Some(user) = Backend::global(cx).read(cx).current_user() else {
|
||||
let backend = Backend::global(cx);
|
||||
let Some(user) = backend.read(cx).current_user() else {
|
||||
self.last_error = Some("Sign in to publish repository state".into());
|
||||
cx.notify();
|
||||
return;
|
||||
@@ -808,7 +1058,10 @@ impl RepoStore {
|
||||
|
||||
/// Merge a pull request: apply its patch (the content of the linked
|
||||
/// root patch event) to the local clone of this repository, then publish
|
||||
/// the merged status.
|
||||
/// a kind-1631 (Applied) status event with merge provenance: the commits
|
||||
/// `git am` created (`applied-as-commits` + `r` tags) and the applied
|
||||
/// patch events (`q` tags, plus `e` reply tags for every patch beyond
|
||||
/// the root, per NIP-34).
|
||||
///
|
||||
/// Only the repository author may merge. The clone is created on demand
|
||||
/// from the announcement's clone URLs when needed. Patch application
|
||||
@@ -816,6 +1069,7 @@ impl RepoStore {
|
||||
/// no longer applies) surface in [`Self::last_error`].
|
||||
pub fn merge_pull_request(&mut self, root: &Event, cx: &mut Context<Self>) {
|
||||
self.last_error = None;
|
||||
self.last_warning = None;
|
||||
|
||||
let is_author = Backend::global(cx)
|
||||
.read(cx)
|
||||
@@ -834,21 +1088,46 @@ impl RepoStore {
|
||||
.map(|a| a.clone.iter().map(ToString::to_string).collect())
|
||||
.unwrap_or_default();
|
||||
let patch = pull_request_patch(root, self.patches.iter());
|
||||
// The applied patch events, for the status tags below.
|
||||
let patches: Vec<Event> = pull_request_patches(root, self.patches.iter())
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.collect();
|
||||
let relay_hint = self
|
||||
.announcement
|
||||
.as_ref()
|
||||
.and_then(|a| a.relays.first())
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default();
|
||||
let euc = self.announcement.as_ref().and_then(|a| a.euc.clone());
|
||||
let root = root.clone();
|
||||
|
||||
let apply = cx.background_spawn(async move {
|
||||
let repo = cache.ensure_clone(&addr, &clone_urls)?;
|
||||
let workdir = repo
|
||||
.workdir()
|
||||
.ok_or_else(|| anyhow::anyhow!("repository has no worktree"))?;
|
||||
signed_git::apply_patch(workdir, &patch)
|
||||
.ok_or_else(|| anyhow::anyhow!("repository has no worktree"))?
|
||||
.to_path_buf();
|
||||
// The commits created by the apply: everything between the
|
||||
// previous HEAD and the new one, oldest first.
|
||||
let previous = signed_git::head_commit_id(&workdir)?;
|
||||
signed_git::apply_patch(&workdir, &patch)?;
|
||||
let applied = signed_git::commits_since(&workdir, previous.as_deref())?;
|
||||
Ok::<_, Error>(applied)
|
||||
});
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
match apply.await {
|
||||
Ok(()) => {
|
||||
Ok(applied) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_status(&root, RepoStatus::Applied, cx);
|
||||
this.publish_applied_status(
|
||||
&root,
|
||||
&patches,
|
||||
&applied,
|
||||
&relay_hint,
|
||||
euc.as_deref(),
|
||||
cx,
|
||||
);
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -862,6 +1141,62 @@ impl RepoStore {
|
||||
}));
|
||||
}
|
||||
|
||||
/// Publish a kind-1631 (Applied) status event for `root` after a merge:
|
||||
/// `applied-as-commits` + `r` tags for the commits `git am` created,
|
||||
/// `q` tags for the applied patch events, and `e` reply tags for every
|
||||
/// patch of the series beyond the root (NIP-34).
|
||||
fn publish_applied_status(
|
||||
&mut self,
|
||||
root: &Event,
|
||||
patches: &[Event],
|
||||
applied: &[String],
|
||||
relay_hint: &str,
|
||||
euc: Option<&str>,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let mut tags = vec![
|
||||
Tag::parse(["e", &root.id.to_hex(), "", "root"]).expect("valid root tag"),
|
||||
Tag::public_key(self.addr.public_key),
|
||||
Tag::public_key(root.pubkey),
|
||||
Tag::coordinate(self.addr.clone(), None),
|
||||
];
|
||||
if let Some(euc) = euc
|
||||
&& let Ok(tag) = Tag::parse(["r", euc])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
// The applied patch events: a `q` tag per event, plus an `e` reply
|
||||
// for every event beyond the root (chain parts and revisions), so
|
||||
// their statuses resolve to Applied too.
|
||||
for (ix, patch) in patches.iter().enumerate() {
|
||||
if let Ok(tag) =
|
||||
Tag::parse(["q", &patch.id.to_hex(), relay_hint, &patch.pubkey.to_hex()])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
if ix > 0
|
||||
&& let Ok(tag) = Tag::parse(["e", &patch.id.to_hex(), "", "reply"])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
}
|
||||
// The commits `git am` created on top of the previous HEAD.
|
||||
if !applied.is_empty() {
|
||||
let mut applied_tag = vec!["applied-as-commits".to_string()];
|
||||
applied_tag.extend(applied.iter().cloned());
|
||||
if let Ok(tag) = Tag::parse(applied_tag) {
|
||||
tags.push(tag);
|
||||
}
|
||||
for commit in applied {
|
||||
if let Ok(tag) = Tag::parse(["r", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.send(EventBuilder::new(Kind::GitStatusApplied, "").tags(tags), cx);
|
||||
}
|
||||
|
||||
fn send(&mut self, builder: EventBuilder, cx: &mut Context<Self>) {
|
||||
self.last_error = None;
|
||||
|
||||
@@ -924,7 +1259,8 @@ fn resolve_statuses(
|
||||
.chain(pull_requests)
|
||||
.map(|root| {
|
||||
let events = by_root.get(&root.id).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let status = signed_core::resolve_status(events.iter().copied(), &root.pubkey, maintainers);
|
||||
let status =
|
||||
signed_core::resolve_status(events.iter().copied(), &root.pubkey, maintainers);
|
||||
(root.id, status)
|
||||
})
|
||||
.collect()
|
||||
@@ -946,6 +1282,78 @@ fn patch_current_commit(patch: &str) -> Option<&str> {
|
||||
hex.split_whitespace().next().filter(|hex| hex.len() == 40)
|
||||
}
|
||||
|
||||
/// Publish a `git format-patch` series as chained kind-1617 events and
|
||||
/// return the root event (the one a PR references). The first part carries
|
||||
/// `first_marker` (`t root`, or `t root-revision` with an `e` reply to
|
||||
/// `reply_to` for revisions); every later part replies to the previous one
|
||||
/// (NIP-34). Every part gets the repository coordinate, the owner, its own
|
||||
/// `commit`/`r` tags, and the repository EUC when known.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn publish_patch_series(
|
||||
this: &WeakEntity<RepoStore>,
|
||||
cx: &mut AsyncApp,
|
||||
addr: &RepoAddr,
|
||||
owner: PublicKey,
|
||||
euc: Option<&str>,
|
||||
series: &[String],
|
||||
first_marker: &str,
|
||||
reply_to: Option<EventId>,
|
||||
) -> Result<Event, Error> {
|
||||
let mut root: Option<Event> = None;
|
||||
let mut previous = reply_to;
|
||||
|
||||
for (ix, part) in series.iter().enumerate() {
|
||||
let Some(commit) = patch_current_commit(part).filter(|hex| hex.len() == 40) else {
|
||||
return Err(anyhow::anyhow!(
|
||||
"patch {} of the series has no `From <commit-id>` header",
|
||||
ix + 1
|
||||
));
|
||||
};
|
||||
|
||||
let mut tags = vec![Tag::coordinate(addr.clone(), None), Tag::public_key(owner)];
|
||||
if ix == 0 {
|
||||
if let Ok(tag) = Tag::parse(["t", first_marker]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
if let Some(root_id) = reply_to
|
||||
&& let Ok(tag) = Tag::parse(["e", &root_id.to_hex(), "", "reply"])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
} else if let Some(previous) = previous
|
||||
&& let Ok(tag) = Tag::parse(["e", &previous.to_hex(), "", "reply"])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
if let Some(euc) = euc
|
||||
&& let Ok(tag) = Tag::parse(["r", euc])
|
||||
{
|
||||
tags.push(tag);
|
||||
}
|
||||
if let Ok(tag) = Tag::parse(["commit", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
if let Ok(tag) = Tag::parse(["r", commit]) {
|
||||
tags.push(tag);
|
||||
}
|
||||
|
||||
let builder = EventBuilder::new(Kind::GitPatch, part.clone()).tags(tags);
|
||||
|
||||
let task = this.update(cx, |_this, cx| {
|
||||
let backend = Backend::global(cx);
|
||||
backend.update(cx, |backend, cx| backend.send(builder, cx))
|
||||
})?;
|
||||
let event = task.await?;
|
||||
|
||||
if root.is_none() {
|
||||
root = Some(event.clone());
|
||||
}
|
||||
previous = Some(event.id);
|
||||
}
|
||||
|
||||
root.ok_or_else(|| anyhow::anyhow!("patch series is empty"))
|
||||
}
|
||||
|
||||
/// Build a NIP-22 kind-1111 comment: uppercase `E`/`K`/`P` tags scope the
|
||||
/// thread root, lowercase `e`/`k`/`p` the direct parent (or the root for a
|
||||
/// top-level comment). An `a` tag with the repository coordinate (not part
|
||||
|
||||
@@ -202,7 +202,8 @@ impl RepoListStore {
|
||||
fn run_refresh(&mut self, cx: &mut Context<Self>) {
|
||||
self.refreshing = true;
|
||||
|
||||
let client = Backend::global(cx).read(cx).client();
|
||||
let backend = Backend::global(cx);
|
||||
let client = backend.read(cx).client();
|
||||
let author = self.author;
|
||||
|
||||
let work = cx.background_spawn(async move {
|
||||
|
||||
@@ -3,5 +3,6 @@ mod repo_list;
|
||||
pub(crate) mod sidebar;
|
||||
|
||||
pub use repo_detail::RepoDetailView;
|
||||
pub(crate) use repo_detail::open_repo_panel;
|
||||
pub use repo_list::RepoListView;
|
||||
pub use sidebar::SidebarPanel;
|
||||
|
||||
@@ -60,6 +60,7 @@ fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
|
||||
cx,
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(euc) = &announcement.euc {
|
||||
rows.push(row(
|
||||
"Earliest Commit",
|
||||
@@ -67,13 +68,11 @@ fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
|
||||
cx,
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(upstream) = &announcement.upstream {
|
||||
rows.push(row(
|
||||
"Upstream",
|
||||
text(SharedString::from(upstream.clone())),
|
||||
cx,
|
||||
));
|
||||
rows.push(row("Upstream", text(upstream.display()), cx));
|
||||
}
|
||||
|
||||
if !announcement.hashtags.is_empty() {
|
||||
rows.push(row(
|
||||
"Hashtags",
|
||||
@@ -81,6 +80,7 @@ fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
|
||||
cx,
|
||||
));
|
||||
}
|
||||
|
||||
if !announcement.clone.is_empty() {
|
||||
rows.push(row(
|
||||
"Clone URLs",
|
||||
@@ -92,6 +92,7 @@ fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
|
||||
cx,
|
||||
));
|
||||
}
|
||||
|
||||
if !announcement.relays.is_empty() {
|
||||
rows.push(row(
|
||||
"Grasp Relays",
|
||||
@@ -103,6 +104,7 @@ fn announcement_rows(announcement: &Announcement, cx: &App) -> AnyElement {
|
||||
cx,
|
||||
));
|
||||
}
|
||||
|
||||
if !announcement.maintainers.is_empty() {
|
||||
rows.push(row(
|
||||
"Maintainers",
|
||||
|
||||
@@ -21,16 +21,13 @@ use utils::relative_time;
|
||||
|
||||
/// Detail panel of a single issue.
|
||||
pub struct IssueDetailView {
|
||||
focus_handle: FocusHandle,
|
||||
/// Repo store holding the issues and their statuses.
|
||||
store: Entity<RepoStore>,
|
||||
issue_id: EventId,
|
||||
contents: HashMap<EventId, SharedString>,
|
||||
/// Input state of the "leave a comment" textarea.
|
||||
comment_input: Entity<TextareaState>,
|
||||
/// Issue/comment bodies as shared strings, keyed by event ID, so
|
||||
/// re-renders don't clone full contents again (events are immutable,
|
||||
/// so the cache never needs invalidation).
|
||||
contents: HashMap<EventId, SharedString>,
|
||||
focus_handle: FocusHandle,
|
||||
}
|
||||
|
||||
impl IssueDetailView {
|
||||
@@ -283,7 +280,13 @@ impl Render for IssueDetailView {
|
||||
let content = self
|
||||
.contents
|
||||
.entry(issue.id)
|
||||
.or_insert_with(|| SharedString::from(issue.content.clone()))
|
||||
.or_insert_with(|| {
|
||||
if issue.content.is_empty() {
|
||||
SharedString::from("No description provided.")
|
||||
} else {
|
||||
SharedString::from(&issue.content)
|
||||
}
|
||||
})
|
||||
.clone();
|
||||
|
||||
(
|
||||
@@ -338,8 +341,7 @@ impl Render for IssueDetailView {
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.child(
|
||||
UserAvatar::new(author.clone())
|
||||
.picture(picture),
|
||||
UserAvatar::new(&author).picture(picture),
|
||||
)
|
||||
.child(author),
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Error;
|
||||
use assets::CustomIconName;
|
||||
@@ -26,9 +27,9 @@ use gpui_component::{
|
||||
VirtualListScrollHandle, h_flex, v_flex,
|
||||
};
|
||||
use nostr::prelude::{EventId, RelayUrl, ToBech32};
|
||||
use signed_core::Announcement;
|
||||
use signed_core::{Announcement, RepoAddr, filters};
|
||||
use signed_git::{CommitList, FileCommit};
|
||||
use signed_state::{Backend, GitStore, LocalReposStore, ProfileStore, RepoStore};
|
||||
use signed_state::{Backend, GitStore, LocalReposStore, ProfileStore, RepoListStore, RepoStore};
|
||||
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
|
||||
use signed_ui::{DropdownButton, PixelAvatar, UserAvatar, copy_row};
|
||||
|
||||
@@ -188,6 +189,9 @@ pub struct RepoDetailView {
|
||||
tasks: Vec<Task<Result<(), Error>>>,
|
||||
/// Subscriptions keeping the selectors' confirm events alive.
|
||||
_subscriptions: Vec<Subscription>,
|
||||
/// Upstream repository (from this fork's `u` tag) the user asked to
|
||||
/// open, while its announcement is still being fetched.
|
||||
pending_upstream: Option<RepoAddr>,
|
||||
}
|
||||
|
||||
impl RepoDetailView {
|
||||
@@ -315,6 +319,7 @@ impl RepoDetailView {
|
||||
focus_handle: cx.focus_handle(),
|
||||
tasks: Vec::new(),
|
||||
_subscriptions: subscriptions,
|
||||
pending_upstream: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -959,6 +964,77 @@ impl RepoDetailView {
|
||||
});
|
||||
}
|
||||
|
||||
/// Open the upstream repository (the `u` tag of this fork's announcement).
|
||||
/// When the upstream announcement is not in the local database yet,
|
||||
/// subscribe for it and open the panel as soon as it lands.
|
||||
fn open_upstream(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.pending_upstream.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(announcement) = self.announcement(cx).cloned() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(addr) = announcement.upstream.and_then(|upstream| upstream.addr) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(found) = RepoListStore::global(cx)
|
||||
.read(cx)
|
||||
.announcements
|
||||
.iter()
|
||||
.find(|a| a.addr() == addr)
|
||||
.cloned()
|
||||
{
|
||||
open_repo_panel(&self.dock_area, &found, window, &mut *cx);
|
||||
return;
|
||||
}
|
||||
|
||||
let backend = Backend::global(cx);
|
||||
backend.update(cx, |backend, cx| {
|
||||
backend.subscribe_bootstrap(vec![filters::announcement(&addr)], cx);
|
||||
});
|
||||
self.pending_upstream = Some(addr);
|
||||
|
||||
let task = cx.spawn_in(window, async move |this, cx| {
|
||||
for _ in 0..60 {
|
||||
cx.background_executor()
|
||||
.timer(Duration::from_millis(250))
|
||||
.await;
|
||||
|
||||
let opened = this.update_in(cx, |this, window, cx| {
|
||||
let Some(addr) = this.pending_upstream.clone() else {
|
||||
return true;
|
||||
};
|
||||
let found = RepoListStore::global(cx)
|
||||
.read(cx)
|
||||
.announcements
|
||||
.iter()
|
||||
.find(|a| a.addr() == addr)
|
||||
.cloned();
|
||||
match found {
|
||||
Some(found) => {
|
||||
this.pending_upstream = None;
|
||||
open_repo_panel(&this.dock_area, &found, window, &mut *cx);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
})?;
|
||||
|
||||
if opened {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
this.update(cx, |this, _cx| this.pending_upstream = None)?;
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.tasks.push(task);
|
||||
}
|
||||
|
||||
/// Check out `name` (a branch or tag picked in the header) and refresh
|
||||
/// the explorer once the switch completes.
|
||||
fn switch_ref(
|
||||
@@ -1332,6 +1408,7 @@ impl RepoDetailView {
|
||||
.text_ellipsis()
|
||||
.child(description),
|
||||
)
|
||||
.when_some(fork_row(&announcement, cx), |this, row| this.child(row))
|
||||
.child(
|
||||
h_flex()
|
||||
.mt_2()
|
||||
@@ -2015,3 +2092,76 @@ fn nostr_clone_url(announcement: &Announcement, nip05: Option<&str>) -> SharedSt
|
||||
|
||||
SharedString::from(url)
|
||||
}
|
||||
|
||||
/// The "Forked from …" row of the detail header: a clickable link to the
|
||||
/// upstream repository when the `u` tag references a NIP-34 repo,
|
||||
/// plain text when it only carries a git URL.
|
||||
fn fork_row(announcement: &Announcement, cx: &mut Context<RepoDetailView>) -> Option<AnyElement> {
|
||||
let upstream = announcement.upstream.as_ref()?;
|
||||
|
||||
let (label, clickable) = match &upstream.addr {
|
||||
Some(addr) => {
|
||||
// Prefer the upstream's display name when its announcement
|
||||
// is already known locally fall back to its repository id.
|
||||
let name = RepoListStore::global(cx)
|
||||
.read(cx)
|
||||
.announcements
|
||||
.iter()
|
||||
.find(|a| a.addr() == *addr)
|
||||
.map(|a| {
|
||||
a.name
|
||||
.clone()
|
||||
.unwrap_or_else(|| SharedString::from(a.id.clone()))
|
||||
})
|
||||
.unwrap_or_else(|| SharedString::from(addr.identifier.clone()));
|
||||
(SharedString::from(format!("Forked from {name}")), true)
|
||||
}
|
||||
None => (upstream.display(), false),
|
||||
};
|
||||
|
||||
let row = h_flex()
|
||||
.gap_1()
|
||||
.items_center()
|
||||
.min_w_0()
|
||||
.text_sm()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child(Icon::new(CustomIconName::GitBranch).small())
|
||||
.child(div().whitespace_nowrap().text_ellipsis().child(label));
|
||||
|
||||
Some(if clickable {
|
||||
row.id("fork-upstream")
|
||||
.cursor_pointer()
|
||||
.hover(|this| this.text_color(cx.theme().foreground))
|
||||
.on_click(cx.listener(|this, _ev, window, cx| this.open_upstream(window, cx)))
|
||||
.into_any_element()
|
||||
} else {
|
||||
row.into_any_element()
|
||||
})
|
||||
}
|
||||
|
||||
/// Open `announcement` as a repository panel in the dock's center, returning
|
||||
/// the new detail view. Shared by the explore list, the sidebar and fork
|
||||
/// links so every entry point opens repositories identically.
|
||||
pub(crate) fn open_repo_panel(
|
||||
dock_area: &WeakEntity<DockArea>,
|
||||
announcement: &Announcement,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Entity<RepoDetailView> {
|
||||
let detail =
|
||||
cx.new(|cx| RepoDetailView::new(dock_area.clone(), announcement.clone(), window, cx));
|
||||
|
||||
if let Some(dock_area) = dock_area.upgrade() {
|
||||
dock_area.update(cx, |dock_area, cx| {
|
||||
dock_area.add_panel_view(
|
||||
panel_handle(detail.clone()),
|
||||
DockPlacement::Center,
|
||||
None,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
detail
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ use gpui::{
|
||||
};
|
||||
use gpui_component::button::{Button, ButtonVariants};
|
||||
use gpui_component::clipboard::Clipboard;
|
||||
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
|
||||
use gpui_component::form::{field, v_form};
|
||||
use gpui_component::input::{Textarea, TextareaState};
|
||||
use gpui_component::list::ListItem;
|
||||
use gpui_component::scroll::{ScrollableElement, Scrollbar};
|
||||
@@ -20,12 +22,13 @@ use gpui_component::tab::{Tab, TabBar};
|
||||
use gpui_component::tag::Tag;
|
||||
use gpui_component::tree::{TreeEntry, TreeState, tree};
|
||||
use gpui_component::{
|
||||
ActiveTheme, Icon, Sizable, StyledExt, VirtualListScrollHandle, h_flex, v_flex, v_virtual_list,
|
||||
ActiveTheme, Icon, Sizable, StyledExt, VirtualListScrollHandle, WindowExt, h_flex, v_flex,
|
||||
v_virtual_list,
|
||||
};
|
||||
use nostr::prelude::{Event, EventId, Kind, Nip34Tag, PublicKey};
|
||||
use signed_core::{activity_subject, pull_request_patch};
|
||||
use signed_git::{CommitDiff, FileCommit, FileDiff, patch_commits, patch_diffs};
|
||||
use signed_state::{GitStore, ProfileStore, RepoStore};
|
||||
use signed_state::{Backend, GitStore, ProfileStore, RepoStore};
|
||||
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
|
||||
use signed_ui::{UserAvatar, placeholder, status_badge, tree_row};
|
||||
use utils::{relative_time, relative_time_secs};
|
||||
@@ -183,7 +186,7 @@ impl PullRequestDetailView {
|
||||
cx.notify();
|
||||
return;
|
||||
};
|
||||
let update = latest_update(store.pull_requests.iter(), &root.id);
|
||||
let update = latest_update(store.pull_requests.iter(), root);
|
||||
let tip = update
|
||||
.and_then(current_commit_of)
|
||||
.or_else(|| current_commit_of(root));
|
||||
@@ -1002,7 +1005,7 @@ impl PullRequestDetailView {
|
||||
/// Always-visible header: status badge and title, like the issue panel.
|
||||
fn render_header(&self, cx: &mut Context<Self>) -> AnyElement {
|
||||
let current_commit = self.current_commit.clone();
|
||||
let (title, status, branch) = {
|
||||
let (title, status, branch, author) = {
|
||||
let store = self.store.read(cx);
|
||||
let Some(root) = store
|
||||
.pull_requests
|
||||
@@ -1015,9 +1018,14 @@ impl PullRequestDetailView {
|
||||
activity_subject(root),
|
||||
store.status_of(root),
|
||||
branch_name_of(root),
|
||||
root.pubkey,
|
||||
)
|
||||
};
|
||||
|
||||
// Only the PR author may publish revisions (kind 1619, NIP-34).
|
||||
let backend = Backend::global(cx);
|
||||
let can_update = backend.read(cx).current_user() == Some(author);
|
||||
|
||||
v_flex()
|
||||
.px_4()
|
||||
.mb_4()
|
||||
@@ -1048,6 +1056,38 @@ impl PullRequestDetailView {
|
||||
.label(branch),
|
||||
)
|
||||
})
|
||||
.when(can_update, |this| {
|
||||
this.child(
|
||||
Button::new("update-pr")
|
||||
.ghost()
|
||||
.small()
|
||||
.icon(CustomIconName::GitPullRequest)
|
||||
.label("Update")
|
||||
.tooltip("Publish a new revision of this pull request")
|
||||
.on_click(cx.listener({
|
||||
let store = self.store.clone();
|
||||
let pr_id = self.pr_id;
|
||||
move |_this, _event, window, cx| {
|
||||
let root = store
|
||||
.read(cx)
|
||||
.pull_requests
|
||||
.iter()
|
||||
.find(|pr| {
|
||||
pr.id == pr_id && pr.kind == Kind::GitPullRequest
|
||||
})
|
||||
.cloned();
|
||||
if let Some(root) = root {
|
||||
open_update_pull_request_dialog(
|
||||
store.clone(),
|
||||
root,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
})),
|
||||
)
|
||||
})
|
||||
.when_some(current_commit, |this, id| {
|
||||
this.child(
|
||||
h_flex()
|
||||
@@ -1064,6 +1104,68 @@ impl PullRequestDetailView {
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the "update pull request" dialog: a patch input that submits a new
|
||||
/// revision through [`RepoStore::update_pull_request`] when confirmed.
|
||||
fn open_update_pull_request_dialog(
|
||||
store: Entity<RepoStore>,
|
||||
root: Event,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let patch = cx.new(|cx| {
|
||||
TextareaState::new(window, cx).placeholder("Paste the updated `git format-patch` output...")
|
||||
});
|
||||
// Both the dialog body and the submit button capture the root event;
|
||||
// share it instead of cloning into each closure.
|
||||
let root = Rc::new(root);
|
||||
|
||||
window.open_dialog(cx, move |dialog, _window, _cx| {
|
||||
let store = store.clone();
|
||||
let patch = patch.clone();
|
||||
let root = root.clone();
|
||||
|
||||
dialog
|
||||
.width(px(520.))
|
||||
.margin_top(px(50.))
|
||||
.content(move |body, _window, _cx| {
|
||||
body.child(
|
||||
DialogHeader::new()
|
||||
.child(DialogTitle::new().child("Update pull request"))
|
||||
.child(DialogDescription::new().child(
|
||||
"Publish a new revision with the output of `git format-patch`.",
|
||||
)),
|
||||
)
|
||||
.child(
|
||||
v_form().child(
|
||||
field()
|
||||
.label("Patch")
|
||||
.child(Textarea::new(&patch).h(px(160.))),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
DialogFooter::new().justify_end().child(
|
||||
Button::new("submit")
|
||||
.primary()
|
||||
.label("Update pull request")
|
||||
.tooltip("Update pull request")
|
||||
.on_click({
|
||||
let store = store.clone();
|
||||
let patch = patch.clone();
|
||||
let root = root.clone();
|
||||
move |_event, window, cx| {
|
||||
let patch = patch.read(cx).value().to_string();
|
||||
store.update(cx, |store, cx| {
|
||||
store.update_pull_request(&root, patch, cx);
|
||||
});
|
||||
window.close_dialog(cx);
|
||||
}
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
/// One sidebar section title.
|
||||
fn sidebar_title(text: &str, cx: &App) -> AnyElement {
|
||||
div()
|
||||
@@ -1121,11 +1223,13 @@ fn branch_name_of(event: &Event) -> Option<String> {
|
||||
}
|
||||
|
||||
/// The latest PR update (kind 1619) revising `root`, found via its NIP-22
|
||||
/// `E` tag pointing at the root PR event.
|
||||
fn latest_update<'a>(events: impl Iterator<Item = &'a Event>, root: &EventId) -> Option<&'a Event> {
|
||||
let root_hex = root.to_hex();
|
||||
/// `E` tag pointing at the root PR event. Only updates by the PR author
|
||||
/// count: the tip of a PR is only mutable by its author (NIP-34).
|
||||
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()
|
||||
@@ -1262,16 +1366,35 @@ mod tests {
|
||||
);
|
||||
|
||||
let events = [unrelated, revision(200), root.clone(), revision(300)];
|
||||
let latest = latest_update(events.iter(), &root.id).expect("an update");
|
||||
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.id).is_none());
|
||||
assert!(latest_update([&root].into_iter(), &root).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,23 +1,28 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use assets::CustomIconName;
|
||||
use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
|
||||
use gpui::prelude::*;
|
||||
use gpui::{
|
||||
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
|
||||
SharedString, Size, WeakEntity, Window, div, px, size,
|
||||
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, PathPromptOptions,
|
||||
Pixels, Render, SharedString, Size, WeakEntity, Window, div, px, size,
|
||||
};
|
||||
use gpui_component::alert::Alert;
|
||||
use gpui_component::button::{Button, ButtonVariants};
|
||||
use gpui_component::checkbox::Checkbox;
|
||||
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
|
||||
use gpui_component::form::{field, v_form};
|
||||
use gpui_component::input::{Input, InputState, Textarea, TextareaState};
|
||||
use gpui_component::scroll::Scrollbar;
|
||||
use gpui_component::{
|
||||
ActiveTheme, Icon, VirtualListScrollHandle, WindowExt, h_flex, v_flex, v_virtual_list,
|
||||
ActiveTheme, Disableable, Icon, IconName, VirtualListScrollHandle, WindowExt, h_flex, v_flex,
|
||||
v_virtual_list,
|
||||
};
|
||||
use nostr::prelude::{EventId, Kind};
|
||||
use signed_core::{RepoStatus, activity_subject};
|
||||
use signed_state::{ProfileStore, RepoStore};
|
||||
use signed_git::{format_patch_between, merge_base, patch_applies};
|
||||
use signed_state::{GitStore, ProfileStore, RepoStore};
|
||||
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
|
||||
use signed_ui::{SegmentButton, UserAvatar, placeholder, status_badge};
|
||||
use utils::relative_time;
|
||||
@@ -282,9 +287,55 @@ impl PullRequestsView {
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the "new pull request" dialog: a title, an optional description and
|
||||
/// a patch input that submit through [`RepoStore::open_pull_request`] when
|
||||
/// confirmed.
|
||||
/// A patch series generated from a local repository, with the metadata
|
||||
/// derived from it.
|
||||
struct GeneratedPatch {
|
||||
/// The `git format-patch` series (fills the patch textarea).
|
||||
patch: String,
|
||||
/// The merge base with the target branch, as hex.
|
||||
merge_base: Option<String>,
|
||||
}
|
||||
|
||||
/// State of the new pull request dialog, so the async generation, the
|
||||
/// apply check and the draft checkbox re-render.
|
||||
#[derive(Default)]
|
||||
struct NewPullRequestDialogState {
|
||||
draft: bool,
|
||||
/// The last generated patch series; its merge base is reused at submit
|
||||
/// only while the patch textarea is unchanged.
|
||||
generated: Option<GeneratedPatch>,
|
||||
/// Result of the pre-publish applicability check against the app's
|
||||
/// mirror clone of the target repository.
|
||||
apply_check: Option<Result<(), String>>,
|
||||
/// A patch generation is in flight.
|
||||
generating: bool,
|
||||
/// Error of the last generation attempt.
|
||||
error: Option<SharedString>,
|
||||
}
|
||||
|
||||
impl NewPullRequestDialogState {
|
||||
/// Text and whether it is good news, for the line under the patch field.
|
||||
fn apply_check_message(&self) -> Option<(SharedString, bool)> {
|
||||
match &self.apply_check {
|
||||
Some(Ok(())) => Some((
|
||||
"Applies cleanly to the repository's default branch".into(),
|
||||
true,
|
||||
)),
|
||||
Some(Err(error)) => Some((
|
||||
format!("May not apply cleanly to the repository's default branch: {error}").into(),
|
||||
false,
|
||||
)),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the "new pull request" dialog: a title, an optional description,
|
||||
/// an optional branch name and a patch input that submit through
|
||||
/// [`RepoStore::open_pull_request`] when confirmed. The patch can either be
|
||||
/// pasted, or generated from a local checkout: pick a repository, a source
|
||||
/// and a target branch, and the app runs `git format-patch` itself and
|
||||
/// checks the series against the app's mirror clone of the target.
|
||||
pub(super) fn open_new_pull_request_dialog(
|
||||
store: Entity<RepoStore>,
|
||||
window: &mut Window,
|
||||
@@ -293,25 +344,40 @@ pub(super) fn open_new_pull_request_dialog(
|
||||
let subject = cx.new(|cx| InputState::new(window, cx).placeholder("Pull request title"));
|
||||
let description =
|
||||
cx.new(|cx| TextareaState::new(window, cx).placeholder("Describe the change..."));
|
||||
let branch = cx.new(|cx| InputState::new(window, cx).placeholder("Branch name (optional)"));
|
||||
let repo_path = cx.new(|cx| InputState::new(window, cx).placeholder("Pick a local checkout…"));
|
||||
let source = cx.new(|cx| InputState::new(window, cx).placeholder("Source branch"));
|
||||
let target = cx.new(|cx| InputState::new(window, cx).placeholder("Target branch"));
|
||||
let patch = cx
|
||||
.new(|cx| TextareaState::new(window, cx).placeholder("Paste `git format-patch` output..."));
|
||||
let state = cx.new(|_| NewPullRequestDialogState::default());
|
||||
|
||||
window.open_dialog(cx, move |dialog, _window, _cx| {
|
||||
let subject = subject.clone();
|
||||
let description = description.clone();
|
||||
let branch = branch.clone();
|
||||
let repo_path = repo_path.clone();
|
||||
let source = source.clone();
|
||||
let target = target.clone();
|
||||
let patch = patch.clone();
|
||||
let store = store.clone();
|
||||
let state = state.clone();
|
||||
|
||||
dialog
|
||||
.width(px(520.))
|
||||
.width(px(560.))
|
||||
.margin_top(px(50.))
|
||||
.content(move |body, _window, _cx| {
|
||||
.content(move |body, _window, cx| {
|
||||
let generating = state.read(cx).generating;
|
||||
let draft = state.read(cx).draft;
|
||||
let error = state.read(cx).error.clone();
|
||||
let apply_check = state.read(cx).apply_check_message();
|
||||
body.child(
|
||||
DialogHeader::new()
|
||||
.child(DialogTitle::new().child("New pull request"))
|
||||
.child(
|
||||
DialogDescription::new()
|
||||
.child("Propose a change with the output of `git format-patch`."),
|
||||
DialogDescription::new().child(
|
||||
"Propose a change with the output of `git format-patch`.",
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
@@ -329,8 +395,147 @@ pub(super) fn open_new_pull_request_dialog(
|
||||
)
|
||||
.child(
|
||||
field()
|
||||
.label("Patch")
|
||||
.child(Textarea::new(&patch).h(px(160.))),
|
||||
.label("Local repository")
|
||||
.description(
|
||||
"Generate the patch from a local checkout; leave empty to paste it",
|
||||
)
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.items_center()
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.child(Input::new(&repo_path).disabled(true)),
|
||||
)
|
||||
.child(
|
||||
Button::new("choose-checkout")
|
||||
.icon(IconName::FolderOpen)
|
||||
.ghost()
|
||||
.tooltip("Choose local checkout")
|
||||
.on_click({
|
||||
let repo_path = repo_path.clone();
|
||||
let source = source.clone();
|
||||
let target = target.clone();
|
||||
let patch = patch.clone();
|
||||
let branch = branch.clone();
|
||||
let state = state.clone();
|
||||
let store = store.clone();
|
||||
move |_ev, window, cx| {
|
||||
choose_local_repo(
|
||||
&repo_path,
|
||||
&source,
|
||||
&target,
|
||||
&patch,
|
||||
&branch,
|
||||
&state,
|
||||
&store,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
Button::new("generate-patch")
|
||||
.ghost()
|
||||
.label("Generate")
|
||||
.tooltip(
|
||||
"Generate the patch from the local checkout",
|
||||
)
|
||||
.loading(generating)
|
||||
.disabled(generating)
|
||||
.on_click({
|
||||
let repo_path = repo_path.clone();
|
||||
let source = source.clone();
|
||||
let target = target.clone();
|
||||
let patch = patch.clone();
|
||||
let branch = branch.clone();
|
||||
let state = state.clone();
|
||||
let store = store.clone();
|
||||
move |_ev, window, cx| {
|
||||
let path =
|
||||
repo_path.read(cx).value().to_string();
|
||||
let source =
|
||||
source.read(cx).value().to_string();
|
||||
let target =
|
||||
target.read(cx).value().to_string();
|
||||
if !path.is_empty()
|
||||
&& !source.is_empty()
|
||||
&& !target.is_empty()
|
||||
{
|
||||
generate_patch(
|
||||
&state,
|
||||
&patch,
|
||||
&branch,
|
||||
path,
|
||||
source,
|
||||
target,
|
||||
&store,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
field()
|
||||
.label("Source branch")
|
||||
.child(Input::new(&source)),
|
||||
)
|
||||
.child(
|
||||
field()
|
||||
.label("Target branch")
|
||||
.child(Input::new(&target)),
|
||||
)
|
||||
.child(
|
||||
field()
|
||||
.label("Branch")
|
||||
.description("Optional: the branch the change is proposed from")
|
||||
.child(Input::new(&branch)),
|
||||
)
|
||||
.child(
|
||||
field().label("Patch").child(
|
||||
v_flex()
|
||||
.gap_1()
|
||||
.child(Textarea::new(&patch).h(px(140.)))
|
||||
.when_some(apply_check, |this, (message, ok)| {
|
||||
this.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_color(if ok {
|
||||
cx.theme().success
|
||||
} else {
|
||||
cx.theme().warning
|
||||
})
|
||||
.child(message),
|
||||
)
|
||||
})
|
||||
.when_some(error, |this, message| {
|
||||
this.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().danger)
|
||||
.child(message),
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
field().child(
|
||||
Checkbox::new("pr-draft")
|
||||
.label("Create as draft")
|
||||
.checked(draft)
|
||||
.on_click({
|
||||
let state = state.clone();
|
||||
move |checked, _window, cx| {
|
||||
state.update(cx, |state, _| state.draft = *checked);
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
@@ -339,20 +544,55 @@ pub(super) fn open_new_pull_request_dialog(
|
||||
.primary()
|
||||
.label("Create pull request")
|
||||
.tooltip("Create pull request")
|
||||
.loading(generating)
|
||||
.disabled(generating)
|
||||
.on_click({
|
||||
let subject = subject.clone();
|
||||
let description = description.clone();
|
||||
let branch = branch.clone();
|
||||
let patch = patch.clone();
|
||||
let repo_path = repo_path.clone();
|
||||
let store = store.clone();
|
||||
let state = state.clone();
|
||||
|
||||
move |_event, window, cx| {
|
||||
if state.read(cx).generating {
|
||||
return;
|
||||
}
|
||||
let subject = subject.read(cx).value().to_string();
|
||||
let description = description.read(cx).value().to_string();
|
||||
let branch = branch.read(cx).value().to_string();
|
||||
let patch = patch.read(cx).value().to_string();
|
||||
let subject = (!subject.is_empty()).then_some(subject);
|
||||
let branch = (!branch.is_empty()).then_some(branch);
|
||||
let draft = state.read(cx).draft;
|
||||
// The generated merge base stays valid
|
||||
// only while the patch is unchanged; an
|
||||
// edited patch falls back to none.
|
||||
let merge_base = state
|
||||
.read(cx)
|
||||
.generated
|
||||
.as_ref()
|
||||
.filter(|generated| generated.patch == patch)
|
||||
.and_then(|generated| generated.merge_base.clone());
|
||||
// The checkout (when set) is where the
|
||||
// tip commit is pushed from, so other
|
||||
// clients can fetch it.
|
||||
let repo_path = repo_path.read(cx).value().to_string();
|
||||
let push_from = (!repo_path.is_empty())
|
||||
.then(|| PathBuf::from(repo_path));
|
||||
|
||||
store.update(cx, |store, cx| {
|
||||
store.open_pull_request(subject, description, patch, cx);
|
||||
store.open_pull_request(
|
||||
subject,
|
||||
description,
|
||||
branch,
|
||||
patch,
|
||||
draft,
|
||||
merge_base,
|
||||
push_from,
|
||||
cx,
|
||||
);
|
||||
});
|
||||
|
||||
window.close_dialog(cx);
|
||||
@@ -364,6 +604,188 @@ pub(super) fn open_new_pull_request_dialog(
|
||||
});
|
||||
}
|
||||
|
||||
/// Prompt for a local checkout, fill the source/target defaults (the
|
||||
/// checkout's current branch and the repository's announced HEAD) and
|
||||
/// generate the patch series right away.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn choose_local_repo(
|
||||
repo_path: &Entity<InputState>,
|
||||
source: &Entity<InputState>,
|
||||
target: &Entity<InputState>,
|
||||
patch: &Entity<TextareaState>,
|
||||
branch: &Entity<InputState>,
|
||||
state: &Entity<NewPullRequestDialogState>,
|
||||
store: &Entity<RepoStore>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let handle = window.window_handle();
|
||||
let repo_path = repo_path.clone();
|
||||
let source = source.clone();
|
||||
let target = target.clone();
|
||||
let patch = patch.clone();
|
||||
let branch = branch.clone();
|
||||
let state = state.clone();
|
||||
let store = store.clone();
|
||||
// The announced HEAD branch is the natural target default.
|
||||
let target_default = store.read(cx).head.clone().unwrap_or_default();
|
||||
|
||||
let prompt = cx.prompt_for_paths(PathPromptOptions {
|
||||
files: false,
|
||||
directories: true,
|
||||
multiple: false,
|
||||
prompt: Some("Choose local checkout".into()),
|
||||
});
|
||||
|
||||
cx.spawn(async move |cx| {
|
||||
if let Ok(Ok(Some(mut paths))) = prompt.await
|
||||
&& let Some(path) = paths.pop()
|
||||
{
|
||||
let path = path.to_string_lossy().to_string();
|
||||
|
||||
// The checkout's current branch is the source default; resolve
|
||||
// it off the UI thread.
|
||||
let current = cx
|
||||
.background_executor()
|
||||
.spawn({
|
||||
let path = path.clone();
|
||||
async move {
|
||||
gix::open(Path::new(&path))
|
||||
.ok()
|
||||
.and_then(|repo| signed_git::current_branch(&repo).ok().flatten())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
let _ = handle.update(cx, |_, window, cx| {
|
||||
repo_path.update(cx, |input, cx| {
|
||||
input.set_value(path.clone(), window, cx);
|
||||
});
|
||||
source.update(cx, |input, cx| {
|
||||
input.set_value(current.clone().unwrap_or_default(), window, cx);
|
||||
});
|
||||
target.update(cx, |input, cx| {
|
||||
input.set_value(target_default.clone(), window, cx);
|
||||
});
|
||||
|
||||
if let Some(current) = current
|
||||
&& !current.is_empty()
|
||||
&& !target_default.is_empty()
|
||||
{
|
||||
generate_patch(
|
||||
&state,
|
||||
&patch,
|
||||
&branch,
|
||||
path,
|
||||
current,
|
||||
target_default,
|
||||
&store,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Generate the patch series `source..target` of the local checkout at
|
||||
/// `repo_path`, fill the patch textarea and record the merge base and the
|
||||
/// pre-publish applicability check in `state`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn generate_patch(
|
||||
state: &Entity<NewPullRequestDialogState>,
|
||||
patch_input: &Entity<TextareaState>,
|
||||
branch_input: &Entity<InputState>,
|
||||
repo_path: String,
|
||||
source: String,
|
||||
target: String,
|
||||
store: &Entity<RepoStore>,
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
state.update(cx, |state, cx| {
|
||||
state.generating = true;
|
||||
state.error = None;
|
||||
state.apply_check = None;
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
let cache = GitStore::global(cx).cache().clone();
|
||||
let (addr, clone_urls) = {
|
||||
let store = store.read(cx);
|
||||
(
|
||||
store.addr().clone(),
|
||||
store
|
||||
.announcement
|
||||
.as_ref()
|
||||
.map(|a| {
|
||||
a.clone
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<String>>()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
};
|
||||
|
||||
let handle = window.window_handle();
|
||||
let state = state.clone();
|
||||
let patch_input = patch_input.clone();
|
||||
let branch_input = branch_input.clone();
|
||||
|
||||
let task = cx.spawn(async move |cx| {
|
||||
// The branch-name tag defaults to the source branch; keep a copy
|
||||
// for the UI update after the background generation moves it.
|
||||
let source_label = source.clone();
|
||||
let generated = cx
|
||||
.background_executor()
|
||||
.spawn(async move {
|
||||
let base =
|
||||
merge_base(Path::new(&repo_path), &source, &target)?.ok_or_else(|| {
|
||||
anyhow::anyhow!("{source} and {target} share no common ancestor")
|
||||
})?;
|
||||
let patch = format_patch_between(Path::new(&repo_path), &base, &source)?;
|
||||
// Best-effort: does the series apply to the current default
|
||||
// branch of the app's mirror clone of the target repository?
|
||||
let check = cache
|
||||
.ensure_clone(&addr, &clone_urls)
|
||||
.ok()
|
||||
.and_then(|repo| repo.workdir().map(|workdir| workdir.to_path_buf()))
|
||||
.map(|workdir| patch_applies(&workdir, &patch).map_err(|e| e.to_string()));
|
||||
Ok::<_, anyhow::Error>((patch, Some(base), check))
|
||||
})
|
||||
.await;
|
||||
|
||||
let _ = handle.update(cx, |_, window, cx| match generated {
|
||||
Ok((patch, merge_base, check)) => {
|
||||
patch_input.update(cx, |input, cx| {
|
||||
input.set_value(patch.clone(), window, cx);
|
||||
});
|
||||
// The branch-name tag defaults to the source branch.
|
||||
if branch_input.read(cx).value().is_empty() {
|
||||
branch_input.update(cx, |input, cx| {
|
||||
input.set_value(source_label.clone(), window, cx);
|
||||
});
|
||||
}
|
||||
state.update(cx, |state, cx| {
|
||||
state.generating = false;
|
||||
state.generated = Some(GeneratedPatch { patch, merge_base });
|
||||
state.apply_check = check;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
Err(error) => state.update(cx, |state, cx| {
|
||||
state.generating = false;
|
||||
state.error = Some(error.to_string().into());
|
||||
cx.notify();
|
||||
}),
|
||||
});
|
||||
});
|
||||
task.detach();
|
||||
}
|
||||
|
||||
impl BasePanel for PullRequestsView {
|
||||
fn panel_name(&self) -> &'static str {
|
||||
"pull-requests"
|
||||
@@ -437,10 +859,33 @@ impl Render for PullRequestsView {
|
||||
let scroll_handle = self.scroll_handle.clone();
|
||||
let view = cx.entity().clone();
|
||||
|
||||
// Non-fatal warnings and errors of the last action (e.g. creating
|
||||
// or updating a PR), shown as dismissible banners above the list.
|
||||
let (last_error, last_warning) = {
|
||||
let store = self.store.read(cx);
|
||||
(store.last_error.clone(), store.last_warning.clone())
|
||||
};
|
||||
|
||||
v_flex()
|
||||
.size_full()
|
||||
.image_cache(image_cache("pull-requests", MAX_IMAGES))
|
||||
.child(self.render_header(cx))
|
||||
.when_some(last_warning, |this, warning| {
|
||||
this.child(Alert::warning("pr-warning", warning).banner().on_close({
|
||||
let store = self.store.clone();
|
||||
move |_event, _window, cx| {
|
||||
store.update(cx, |store, _| store.last_warning = None);
|
||||
}
|
||||
}))
|
||||
})
|
||||
.when_some(last_error, |this, error| {
|
||||
this.child(Alert::error("pr-error", error).banner().on_close({
|
||||
let store = self.store.clone();
|
||||
move |_event, _window, cx| {
|
||||
store.update(cx, |store, _| store.last_error = None);
|
||||
}
|
||||
}))
|
||||
})
|
||||
.child(
|
||||
v_flex()
|
||||
.relative()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use assets::CustomIconName;
|
||||
use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
|
||||
use dock::{BasePanel, DockArea, Panel, PanelEvent};
|
||||
use gpui::prelude::*;
|
||||
use gpui::{
|
||||
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
|
||||
@@ -19,7 +19,7 @@ use signed_ui::image_cache::{MAX_IMAGES, image_cache};
|
||||
use signed_ui::{SegmentButton, UserAvatar};
|
||||
use utils::relative_time;
|
||||
|
||||
use super::RepoDetailView;
|
||||
use super::open_repo_panel;
|
||||
|
||||
const COLUMNS: usize = 2;
|
||||
const CARD_HEIGHT: f32 = 40. + 64. + 48. + 2. + 6.;
|
||||
@@ -173,21 +173,7 @@ impl RepoListView {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let dock_area = self.dock_area.clone();
|
||||
let detail =
|
||||
cx.new(|cx| RepoDetailView::new(dock_area.clone(), announcement.clone(), window, cx));
|
||||
|
||||
if let Some(dock_area) = dock_area.upgrade() {
|
||||
dock_area.update(cx, |dock_area, cx| {
|
||||
dock_area.add_panel_view(
|
||||
panel_handle(detail),
|
||||
DockPlacement::Center,
|
||||
None,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
});
|
||||
}
|
||||
open_repo_panel(&self.dock_area, announcement, window, &mut *cx);
|
||||
}
|
||||
|
||||
fn render_card(
|
||||
@@ -215,6 +201,26 @@ impl RepoListView {
|
||||
.map(|label| SharedString::from(format!("Updated {label}")))
|
||||
.unwrap_or_default();
|
||||
|
||||
// Fork badge: the upstream's display name when its announcement is
|
||||
// known locally, otherwise its repository id from the `u` tag.
|
||||
let fork_label: Option<SharedString> =
|
||||
announcement.upstream.as_ref().and_then(|upstream| {
|
||||
let addr = upstream.addr.as_ref()?;
|
||||
let name = self
|
||||
.store
|
||||
.read(cx)
|
||||
.announcements
|
||||
.iter()
|
||||
.find(|a| a.addr() == *addr)
|
||||
.map(|a| {
|
||||
a.name
|
||||
.clone()
|
||||
.unwrap_or_else(|| SharedString::from(a.id.clone()))
|
||||
})
|
||||
.unwrap_or_else(|| SharedString::from(addr.identifier.clone()));
|
||||
Some(SharedString::from(format!("forked from {name}")))
|
||||
});
|
||||
|
||||
v_flex()
|
||||
.id(ix)
|
||||
.flex_1()
|
||||
@@ -228,11 +234,29 @@ impl RepoListView {
|
||||
.child(
|
||||
h_flex()
|
||||
.h_10()
|
||||
.text_sm()
|
||||
.font_semibold()
|
||||
.whitespace_nowrap()
|
||||
.text_ellipsis()
|
||||
.child(name),
|
||||
.gap_1p5()
|
||||
.items_center()
|
||||
.child(
|
||||
div()
|
||||
.min_w_0()
|
||||
.text_sm()
|
||||
.font_semibold()
|
||||
.whitespace_nowrap()
|
||||
.text_ellipsis()
|
||||
.child(name),
|
||||
)
|
||||
.when_some(fork_label, |this, label| {
|
||||
this.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.items_center()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.whitespace_nowrap()
|
||||
.child(Icon::new(CustomIconName::GitBranch).small())
|
||||
.child(label),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use dock::{DockArea, DockPlacement, panel_handle};
|
||||
use dock::DockArea;
|
||||
use gpui::prelude::*;
|
||||
use gpui::{App, Entity, PathPromptOptions, SharedString, WeakEntity, Window, div, px};
|
||||
use gpui_base::input::TextareaState;
|
||||
@@ -11,7 +11,7 @@ use settings::SettingsStore;
|
||||
use signed_core::Announcement;
|
||||
use signed_state::Backend;
|
||||
|
||||
use super::super::RepoDetailView;
|
||||
use super::super::open_repo_panel;
|
||||
use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers};
|
||||
|
||||
/// Shared state for the Create Repository dialog, so async results can be rendered.
|
||||
@@ -262,13 +262,5 @@ fn open_repo(
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let Some(dock_area) = dock_area.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let panel = cx.new(|cx| RepoDetailView::new(dock_area.downgrade(), announcement, window, cx));
|
||||
|
||||
dock_area.update(cx, |dock_area, cx| {
|
||||
dock_area.add_panel_view(panel_handle(panel), DockPlacement::Center, None, window, cx);
|
||||
});
|
||||
open_repo_panel(&dock_area, &announcement, window, cx);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ use signed_state::{Backend, BackendEvent, LocalReposStore, Profile, ProfileStore
|
||||
use signed_ui::image_cache::{MAX_IMAGES, image_cache};
|
||||
use signed_ui::{NavItem, PixelAvatar, UserAvatar, title_bar_drag_handlers};
|
||||
|
||||
use super::{RepoDetailView, RepoListView};
|
||||
use super::{RepoDetailView, RepoListView, open_repo_panel};
|
||||
|
||||
mod create_repo_dialog;
|
||||
pub(crate) mod grasp_servers;
|
||||
@@ -100,7 +100,8 @@ impl SidebarPanel {
|
||||
fn refresh_my_repos(&mut self, cx: &mut Context<Self>) {
|
||||
self.my_repos_subscription = None;
|
||||
|
||||
let author = Backend::global(cx).read(cx).current_user();
|
||||
let backend = Backend::global(cx);
|
||||
let author = backend.read(cx).current_user();
|
||||
self.my_repos = author.map(|author| cx.new(|cx| RepoListStore::new(Some(author), cx)));
|
||||
|
||||
if let Some(store) = self.my_repos.as_ref() {
|
||||
@@ -158,19 +159,7 @@ impl SidebarPanel {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let detail = cx.new(|cx| {
|
||||
RepoDetailView::new(self.dock_area.clone(), announcement.clone(), window, cx)
|
||||
});
|
||||
|
||||
let _ = self.dock_area.update(cx, |dock_area, cx| {
|
||||
dock_area.add_panel_view(
|
||||
panel_handle(detail),
|
||||
DockPlacement::Center,
|
||||
None,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
});
|
||||
open_repo_panel(&self.dock_area, announcement, window, &mut *cx);
|
||||
}
|
||||
|
||||
/// Open a local repository's detail view in the dock's center; the
|
||||
|
||||
+17
-4
@@ -1,12 +1,25 @@
|
||||
# TODO
|
||||
|
||||
## Local repository scan
|
||||
## Fork support
|
||||
|
||||
- [ ] Make the scanned directories configurable (currently fixed to Desktop and Documents).
|
||||
- [x] Fork badge on repo list cards (`repo_list.rs::render_card`).
|
||||
- [x] "Forked from …" text button in the repo detail header (`repo_detail/mod.rs::render_header`) and About dialog.
|
||||
- [x] Clicking the upstream opens it as a center panel (shared `open_repo_panel` helper).
|
||||
|
||||
## Create repository dialog
|
||||
## Pull request improvement
|
||||
|
||||
- [ ] Remember the folder picked in the create-repository dialog and default to it next time (currently defaults to Desktop).
|
||||
- [x] P1: `branch-name` tag + `r` EUC tag on PR creation; draft checkbox in the new-PR dialog.
|
||||
- [x] P1: `RepoStore::update_pull_request` (kind 1619 + root-revision patch) with an author-only "Update" button on the PR detail header.
|
||||
- [x] P1: `latest_update` filters by PR author.
|
||||
- [x] P2: local checkout picker in the new-PR dialog (folder picker + source/target branches + Generate): `signed_git::{merge_base, format_patch_between, patch_applies}`; `merge-base` tag now published; best-effort apply check shown under the patch field.
|
||||
- [x] P3: push tip to grasp servers under `refs/nostr/<event-id>` before publishing (from the local checkout); multi-commit series published as NIP-10-chained 1617 events with a 60 KB per-patch cap; PR list shows dismissible error/warning banners (incl. push failures).
|
||||
- [x] P4: merge status tags — `merge_pull_request` publishes 1631 with `applied-as-commits` + `r` per applied commit and `q`/`e`-reply tags per applied patch event.
|
||||
|
||||
### Pull request follow-ups
|
||||
|
||||
- [ ] GRASP-06 `/prs/<npub>/<id>.git` contributor endpoints + kind-10317 user grasp-list fallback.
|
||||
- [ ] Merge button in the PR detail view (`merge_pull_request` is store-only today), then fetch-and-merge (`merge-commit`) when the push backend is guaranteed.
|
||||
- [ ] Local-checkout generation for the update-PR dialog (currently paste-only).
|
||||
|
||||
## Performance: render path
|
||||
|
||||
|
||||
Reference in New Issue
Block a user