chore: restructure backend
This commit is contained in:
@@ -7,6 +7,15 @@ pub enum DiffLineKind {
|
||||
Deletion,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DiffStatus {
|
||||
Added,
|
||||
Modified,
|
||||
Deleted,
|
||||
Renamed,
|
||||
Copied,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DiffLine {
|
||||
pub kind: DiffLineKind,
|
||||
@@ -55,15 +64,6 @@ impl DiffHunk {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DiffStatus {
|
||||
Added,
|
||||
Modified,
|
||||
Deleted,
|
||||
Renamed,
|
||||
Copied,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileDiff {
|
||||
pub path: String,
|
||||
|
||||
@@ -81,39 +81,42 @@ impl FileCommit {
|
||||
},
|
||||
String::from_utf8_lossy(author.name).trim().to_string(),
|
||||
time.seconds,
|
||||
format_commit_date(time),
|
||||
Self::format_date(time),
|
||||
commit.parent_ids().map(|id| id.to_string()).collect(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats a gix time as "Nov 21, 2026 at 4:40 AM GMT+7" in the commit's own offset.
|
||||
pub(crate) fn format_commit_date(time: gix::date::Time) -> String {
|
||||
let Ok(timestamp) = jiff::Timestamp::from_second(time.seconds) else {
|
||||
return String::new();
|
||||
};
|
||||
let Ok(offset) = jiff::tz::Offset::from_seconds(time.offset) else {
|
||||
return String::new();
|
||||
};
|
||||
let datetime = offset.to_datetime(timestamp);
|
||||
/// Formats a gix time as "Nov 21, 2026 at 4:40 AM GMT+7" in the commit's own offset.
|
||||
pub(crate) fn format_date(time: gix::date::Time) -> String {
|
||||
let Ok(timestamp) = jiff::Timestamp::from_second(time.seconds) else {
|
||||
return String::new();
|
||||
};
|
||||
|
||||
let label = datetime.strftime("%b %-d, %Y at %-I:%M %p").to_string();
|
||||
format!("{label} {}", gmt_label(time.offset))
|
||||
}
|
||||
let Ok(offset) = jiff::tz::Offset::from_seconds(time.offset) else {
|
||||
return String::new();
|
||||
};
|
||||
|
||||
/// The GMT offset label for a seconds offset, e.g. "GMT", "GMT+7", "GMT-5:30".
|
||||
fn gmt_label(offset: i32) -> String {
|
||||
if offset == 0 {
|
||||
return "GMT".to_owned();
|
||||
let datetime = offset.to_datetime(timestamp);
|
||||
let label = datetime.strftime("%b %-d, %Y at %-I:%M %p").to_string();
|
||||
|
||||
format!("{label} {}", Self::gmt_label(time.offset))
|
||||
}
|
||||
|
||||
let sign = if offset < 0 { '-' } else { '+' };
|
||||
let total_minutes = offset.abs() / 60;
|
||||
let hours = total_minutes / 60;
|
||||
let minutes = total_minutes % 60;
|
||||
if minutes == 0 {
|
||||
format!("GMT{sign}{hours}")
|
||||
} else {
|
||||
format!("GMT{sign}{hours}:{minutes:02}")
|
||||
/// The GMT offset label for a seconds offset, e.g. "GMT", "GMT+7", "GMT-5:30".
|
||||
fn gmt_label(offset: i32) -> String {
|
||||
if offset == 0 {
|
||||
return "GMT".to_owned();
|
||||
}
|
||||
|
||||
let sign = if offset < 0 { '-' } else { '+' };
|
||||
let total_minutes = offset.abs() / 60;
|
||||
let hours = total_minutes / 60;
|
||||
let minutes = total_minutes % 60;
|
||||
|
||||
if minutes == 0 {
|
||||
format!("GMT{sign}{hours}")
|
||||
} else {
|
||||
format!("GMT{sign}{hours}:{minutes:02}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,16 +8,13 @@ mod scan;
|
||||
mod sync;
|
||||
mod worktree;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use cache::GitCache;
|
||||
pub use diff::{CommitDiff, DiffHunk, DiffLine, DiffLineKind, DiffStatus, FileDiff};
|
||||
pub use history::{CommitList, FileCommit, MAX_LISTED_COMMITS};
|
||||
pub use nip34::{GraspSignals, Nip34Binding, Nip34Kind};
|
||||
pub use patch::PatchParser;
|
||||
pub use repo::{Repo, RepoRefState};
|
||||
pub use scan::{LocalRepo, find_git_repos};
|
||||
pub use scan::LocalRepo;
|
||||
pub use sync::{RefSync, RepoSyncStatus};
|
||||
pub use worktree::WorktreeSnapshot;
|
||||
|
||||
@@ -34,18 +31,3 @@ where
|
||||
self.map_err(|exn| anyhow::Error::from(exn.into_error()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn git_in(dir: &std::path::Path, args: &[&str]) -> anyhow::Result<String> {
|
||||
let output = Repo::run_git(dir, args, "git")?;
|
||||
|
||||
if !output.status.success() {
|
||||
anyhow::bail!(
|
||||
"git {} failed: {}",
|
||||
args.join(" "),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
||||
}
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
use nostr::prelude::*;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub(crate) struct Nip34Json {
|
||||
pub(crate) identifier: Option<String>,
|
||||
pub(crate) owner: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Nip34Kind {
|
||||
Initialized,
|
||||
@@ -13,6 +7,12 @@ pub enum Nip34Kind {
|
||||
ToolingOnly,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub(crate) struct Nip34Json {
|
||||
pub(crate) identifier: Option<String>,
|
||||
pub(crate) owner: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct GraspSignals {
|
||||
pub nip34_json: bool,
|
||||
|
||||
@@ -3,7 +3,7 @@ use diffy::patch_set::{FileOperation, FilePatch, ParseOptions, PatchSet};
|
||||
use diffy::{Hunk, Line};
|
||||
|
||||
use crate::diff::{CommitDiff, DiffHunk, DiffLineKind, DiffStatus, FileDiff, HunkBuilder};
|
||||
use crate::history::{FileCommit, format_commit_date};
|
||||
use crate::history::FileCommit;
|
||||
|
||||
pub struct PatchParser;
|
||||
|
||||
@@ -75,7 +75,7 @@ impl PatchParser {
|
||||
.map(Self::name_from_address)
|
||||
.unwrap_or_default(),
|
||||
time.map(|time| time.seconds).unwrap_or(0),
|
||||
time.map(format_commit_date).unwrap_or_default(),
|
||||
time.map(FileCommit::format_date).unwrap_or_default(),
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1847,7 +1847,9 @@ impl Repo {
|
||||
}
|
||||
|
||||
/// Matches grasp URLs by shape: two path segments with an npub owner.
|
||||
pub(crate) fn is_grasp_url(url: &str) -> bool {
|
||||
///
|
||||
/// Returns whether a URL has the grasp server clone shape.
|
||||
pub fn is_grasp_url(url: &str) -> bool {
|
||||
let Ok(parsed) = Url::parse(url) else {
|
||||
return false;
|
||||
};
|
||||
@@ -1943,240 +1945,3 @@ impl Repo {
|
||||
.unwrap_or_else(|| url.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Creates a fresh repository in a temp directory.
|
||||
fn init_repo() -> (tempfile::TempDir, std::path::PathBuf) {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("repo");
|
||||
std::fs::create_dir_all(&path).expect("mkdir");
|
||||
git(&path, &["init", "-q"]);
|
||||
(dir, path)
|
||||
}
|
||||
|
||||
/// Runs `git` in `dir`, failing the test on a non-zero exit.
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let status = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.env("GIT_AUTHOR_NAME", "Test Author")
|
||||
.env("GIT_AUTHOR_EMAIL", "test@example.com")
|
||||
.env("GIT_COMMITTER_NAME", "Test Author")
|
||||
.env("GIT_COMMITTER_EMAIL", "test@example.com")
|
||||
.env("GIT_EDITOR", "true")
|
||||
.args(args)
|
||||
.status()
|
||||
.expect("spawn git");
|
||||
assert!(status.success(), "git {args:?} failed");
|
||||
}
|
||||
|
||||
/// Generates a fresh public key.
|
||||
fn key() -> PublicKey {
|
||||
Keys::generate().public_key()
|
||||
}
|
||||
|
||||
/// Encodes a NIP-34 coordinate as an `naddr` string.
|
||||
fn naddr(kind: Kind, owner: PublicKey, identifier: &str) -> String {
|
||||
let coordinate = Coordinate::new(kind, owner).identifier(identifier);
|
||||
Nip19Coordinate::new(coordinate, Vec::<RelayUrl>::new())
|
||||
.to_bech32()
|
||||
.expect("naddr")
|
||||
}
|
||||
|
||||
/// Opens the repository at `path` and returns its NIP-34 binding.
|
||||
fn binding_of(path: &Path) -> Option<Nip34Binding> {
|
||||
Repo::open(path).ok()?.nip34_binding()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_repository_has_no_binding() {
|
||||
let (_dir, path) = init_repo();
|
||||
assert!(binding_of(&path).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nip34_json_marks_a_repository_initialized() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let npub = owner.to_bech32().expect("npub");
|
||||
std::fs::write(
|
||||
path.join("nip34.json"),
|
||||
format!(r#"{{"identifier":"my-repo","owner":"{npub}"}}"#),
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nip34_json);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_nip34_json_is_ignored() {
|
||||
let (_dir, path) = init_repo();
|
||||
std::fs::write(path.join("nip34.json"), b"not json").expect("write");
|
||||
|
||||
assert!(binding_of(&path).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_patch_applies_cleanly_to_parent() {
|
||||
let (dir, path) = init_repo();
|
||||
git(&path, &["config", "user.name", "Test Author"]);
|
||||
git(&path, &["config", "user.email", "test@example.com"]);
|
||||
std::fs::write(path.join("file.txt"), "one\n").expect("write");
|
||||
git(&path, &["add", "."]);
|
||||
git(&path, &["commit", "-q", "-m", "first"]);
|
||||
std::fs::write(path.join("file.txt"), "two\n").expect("write");
|
||||
std::fs::write(path.join("file2.txt"), "added\n").expect("write");
|
||||
git(&path, &["add", "."]);
|
||||
git(&path, &["commit", "-q", "-m", "second"]);
|
||||
|
||||
let patch = Repo::open(&path)
|
||||
.expect("open repo")
|
||||
.commit_patch("HEAD")
|
||||
.expect("commit patch");
|
||||
assert!(patch.contains("diff --git a/file.txt b/file.txt"));
|
||||
assert!(patch.contains("diff --git a/file2.txt b/file2.txt"));
|
||||
assert!(patch.contains("--- /dev/null"));
|
||||
assert!(patch.contains("+added"));
|
||||
|
||||
let patch_path = dir.path().join("head.patch");
|
||||
std::fs::write(&patch_path, &patch).expect("write patch");
|
||||
git(&path, &["checkout", "-q", "--detach", "HEAD~1"]);
|
||||
git(
|
||||
&path,
|
||||
&["apply", patch_path.to_str().expect("utf8 patch path")],
|
||||
);
|
||||
|
||||
let applied = std::fs::read_to_string(path.join("file.txt")).expect("read");
|
||||
assert_eq!(applied, "two\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(path.join("file2.txt")).expect("read"),
|
||||
"added\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nak_exclude_and_state_refs_are_detected() {
|
||||
let (_dir, path) = init_repo();
|
||||
|
||||
std::fs::create_dir_all(path.join(".git/info")).expect("mkdir");
|
||||
std::fs::write(path.join(".git/info/exclude"), "nip34.json\n").expect("write");
|
||||
|
||||
git(&path, &["commit", "-q", "--allow-empty", "-m", "initial"]);
|
||||
git(
|
||||
&path,
|
||||
&["update-ref", "refs/heads/nip34/state/HEAD", "HEAD"],
|
||||
);
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nip34_excluded);
|
||||
assert!(binding.signals.nip34_state_refs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nostr_repo_config_marks_a_repository_initialized() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
|
||||
git(&path, &["config", "nostr.repo", &naddr]);
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nostr_repo_config);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_written_nostr_repo_marker_is_detected() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
|
||||
|
||||
Repo::open(&path)
|
||||
.expect("open")
|
||||
.set_nostr_repo(&naddr)
|
||||
.expect("write marker");
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nostr_repo_config);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nostr_remote_is_a_nip34_clone() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let npub = owner.to_bech32().expect("npub");
|
||||
let url = format!("nostr://{npub}/relay.ngit.dev/my-repo");
|
||||
git(&path, &["remote", "add", "origin", &url]);
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Cloned);
|
||||
assert!(binding.signals.nostr_remote);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nak_grasp_remote_marks_a_repository_initialized() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let npub = owner.to_bech32().expect("npub");
|
||||
let url = format!("https://gitnostr.com/{npub}/my-repo.git");
|
||||
git(
|
||||
&path,
|
||||
&["config", "remote.nip34/grasp/gitnostr.com.url", &url],
|
||||
);
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nip34_grasp_remote);
|
||||
assert!(binding.signals.grasp_remote);
|
||||
assert_eq!(binding.grasp_urls, vec![url]);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nostr_cache_alone_is_tooling_only() {
|
||||
let (_dir, path) = init_repo();
|
||||
std::fs::write(path.join(".git/nostr-cache.lmdb"), b"cache").expect("write");
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::ToolingOnly);
|
||||
assert!(binding.signals.nostr_cache);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grasp_urls_are_recognised_by_shape() {
|
||||
let owner = key();
|
||||
let npub = owner.to_bech32().expect("npub");
|
||||
|
||||
assert!(Repo::is_grasp_url(&format!(
|
||||
"https://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
assert!(Repo::is_grasp_url(&format!(
|
||||
"grasp://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
|
||||
assert!(!Repo::is_grasp_url("https://gitnostr.com/my-repo.git"));
|
||||
assert!(!Repo::is_grasp_url(
|
||||
"https://gitnostr.com/not-a-pubkey/my-repo.git"
|
||||
));
|
||||
assert!(!Repo::is_grasp_url(&format!(
|
||||
"ssh://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,69 +19,69 @@ impl LocalRepo {
|
||||
pub fn new(path: PathBuf, nip34: Option<Nip34Binding>) -> Self {
|
||||
Self { path, nip34 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds git repositories under `root` up to `SCAN_MAX_DEPTH` deep, without descending into them.
|
||||
pub fn find_git_repos(root: &Path) -> Vec<LocalRepo> {
|
||||
let Ok(root) = root.canonicalize() else {
|
||||
return Vec::new();
|
||||
};
|
||||
/// Finds git repositories under `root` up to `SCAN_MAX_DEPTH` deep, without descending into them.
|
||||
pub fn find_all(root: &Path) -> Vec<Self> {
|
||||
let Ok(root) = root.canonicalize() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let found = Arc::new(Mutex::new(Vec::<PathBuf>::new()));
|
||||
let found = Arc::new(Mutex::new(Vec::<PathBuf>::new()));
|
||||
|
||||
let walker = WalkBuilder::new(&root)
|
||||
.max_depth(Some(SCAN_MAX_DEPTH))
|
||||
.require_git(false)
|
||||
.filter_entry({
|
||||
let found = found.clone();
|
||||
move |entry| {
|
||||
let Some(kind) = entry.file_type() else {
|
||||
return true;
|
||||
};
|
||||
let walker = WalkBuilder::new(&root)
|
||||
.max_depth(Some(SCAN_MAX_DEPTH))
|
||||
.require_git(false)
|
||||
.filter_entry({
|
||||
let found = found.clone();
|
||||
move |entry| {
|
||||
let Some(kind) = entry.file_type() else {
|
||||
return true;
|
||||
};
|
||||
|
||||
if !kind.is_dir() {
|
||||
return true;
|
||||
}
|
||||
if !kind.is_dir() {
|
||||
return true;
|
||||
}
|
||||
|
||||
if entry.file_name() == std::ffi::OsStr::new(".git") {
|
||||
return false;
|
||||
}
|
||||
if entry.file_name() == std::ffi::OsStr::new(".git") {
|
||||
return false;
|
||||
}
|
||||
|
||||
let dir = entry.path();
|
||||
let Ok(repo) = gix::discover(dir) else {
|
||||
return true;
|
||||
};
|
||||
let dir = entry.path();
|
||||
let Ok(repo) = gix::discover(dir) else {
|
||||
return true;
|
||||
};
|
||||
|
||||
let Some(workdir) = repo.workdir() else {
|
||||
return false;
|
||||
};
|
||||
let Some(workdir) = repo.workdir() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if workdir != dir {
|
||||
return true;
|
||||
}
|
||||
if workdir != dir {
|
||||
return true;
|
||||
}
|
||||
|
||||
match found.lock() {
|
||||
Ok(mut repos) => repos.push(dir.to_path_buf()),
|
||||
Err(poisoned) => poisoned.into_inner().push(dir.to_path_buf()),
|
||||
match found.lock() {
|
||||
Ok(mut repos) => repos.push(dir.to_path_buf()),
|
||||
Err(poisoned) => poisoned.into_inner().push(dir.to_path_buf()),
|
||||
}
|
||||
false
|
||||
}
|
||||
false
|
||||
}
|
||||
})
|
||||
.build();
|
||||
})
|
||||
.build();
|
||||
|
||||
for _ in walker {}
|
||||
for _ in walker {}
|
||||
|
||||
let mut repos = match found.lock() {
|
||||
Ok(mut repos) => std::mem::take(&mut *repos),
|
||||
Err(poisoned) => std::mem::take(&mut *poisoned.into_inner()),
|
||||
};
|
||||
repos.sort();
|
||||
let mut repos = match found.lock() {
|
||||
Ok(mut repos) => std::mem::take(&mut *repos),
|
||||
Err(poisoned) => std::mem::take(&mut *poisoned.into_inner()),
|
||||
};
|
||||
|
||||
repos
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
let nip34 = Repo::open(&path).ok().and_then(|repo| repo.nip34_binding());
|
||||
LocalRepo::new(path, nip34)
|
||||
})
|
||||
.collect()
|
||||
repos.sort();
|
||||
repos
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
let nip34 = Repo::open(&path).ok().and_then(|repo| repo.nip34_binding());
|
||||
LocalRepo::new(path, nip34)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use nostr::prelude::Keys;
|
||||
use nostr::prelude::*;
|
||||
use signed_core::RepoAddr;
|
||||
|
||||
use super::*;
|
||||
use signed_git::{DiffStatus, GitCache, LocalRepo, Nip34Binding, Nip34Kind, PatchParser, Repo};
|
||||
|
||||
#[test]
|
||||
fn blocks_parent_components() {
|
||||
@@ -827,6 +826,11 @@ fn git_run(dir: &Path, args: &[&str]) -> std::process::Output {
|
||||
output
|
||||
}
|
||||
|
||||
fn git_in(dir: &Path, args: &[&str]) -> anyhow::Result<String> {
|
||||
let output = git_run(dir, args);
|
||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_git_repos_reports_the_outermost_repository() {
|
||||
let root = tempfile::tempdir().expect("tempdir");
|
||||
@@ -837,7 +841,7 @@ fn find_git_repos_reports_the_outermost_repository() {
|
||||
let plain_dir = root.path().join("plain").join("deep");
|
||||
std::fs::create_dir_all(&plain_dir).expect("mkdir");
|
||||
|
||||
let repos = find_git_repos(root.path());
|
||||
let repos = LocalRepo::find_all(root.path());
|
||||
|
||||
assert_eq!(repos.len(), 1);
|
||||
assert_eq!(repos[0].path, repo_dir.canonicalize().expect("canonical"));
|
||||
@@ -855,7 +859,7 @@ fn find_git_repos_skips_repositories_nested_in_repositories() {
|
||||
std::fs::create_dir_all(&nested).expect("mkdir");
|
||||
git_run(&nested, &["init", "-q"]);
|
||||
|
||||
let repos = find_git_repos(root.path());
|
||||
let repos = LocalRepo::find_all(root.path());
|
||||
|
||||
assert_eq!(repos.len(), 1);
|
||||
assert_eq!(repos[0].path, outer.canonicalize().expect("canonical"));
|
||||
@@ -869,7 +873,7 @@ fn find_git_repos_ignores_a_repository_above_the_scan_root() {
|
||||
let root = outer.path().join("scan");
|
||||
std::fs::create_dir_all(&root).expect("mkdir");
|
||||
|
||||
assert!(find_git_repos(&root).is_empty());
|
||||
assert!(LocalRepo::find_all(&root).is_empty());
|
||||
}
|
||||
|
||||
/// Creates an empty bare server repository for push tests.
|
||||
@@ -1066,3 +1070,232 @@ fn read_at_reads_the_files_of_that_commit() {
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a fresh repository in a temp directory.
|
||||
fn init_repo() -> (tempfile::TempDir, std::path::PathBuf) {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("repo");
|
||||
std::fs::create_dir_all(&path).expect("mkdir");
|
||||
git(&path, &["init", "-q"]);
|
||||
(dir, path)
|
||||
}
|
||||
|
||||
/// Runs `git` in `dir`, failing the test on a non-zero exit.
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let status = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.env("GIT_AUTHOR_NAME", "Test Author")
|
||||
.env("GIT_AUTHOR_EMAIL", "test@example.com")
|
||||
.env("GIT_COMMITTER_NAME", "Test Author")
|
||||
.env("GIT_COMMITTER_EMAIL", "test@example.com")
|
||||
.env("GIT_EDITOR", "true")
|
||||
.args(args)
|
||||
.status()
|
||||
.expect("spawn git");
|
||||
assert!(status.success(), "git {args:?} failed");
|
||||
}
|
||||
|
||||
/// Generates a fresh public key.
|
||||
fn key() -> PublicKey {
|
||||
Keys::generate().public_key()
|
||||
}
|
||||
|
||||
/// Encodes a NIP-34 coordinate as an `naddr` string.
|
||||
fn naddr(kind: Kind, owner: PublicKey, identifier: &str) -> String {
|
||||
let coordinate = Coordinate::new(kind, owner).identifier(identifier);
|
||||
Nip19Coordinate::new(coordinate, Vec::<RelayUrl>::new())
|
||||
.to_bech32()
|
||||
.expect("naddr")
|
||||
}
|
||||
|
||||
/// Opens the repository at `path` and returns its NIP-34 binding.
|
||||
fn binding_of(path: &Path) -> Option<Nip34Binding> {
|
||||
Repo::open(path).ok()?.nip34_binding()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_repository_has_no_binding() {
|
||||
let (_dir, path) = init_repo();
|
||||
assert!(binding_of(&path).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nip34_json_marks_a_repository_initialized() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let npub = owner.to_bech32().expect("npub");
|
||||
std::fs::write(
|
||||
path.join("nip34.json"),
|
||||
format!(r#"{{"identifier":"my-repo","owner":"{npub}"}}"#),
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nip34_json);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_nip34_json_is_ignored() {
|
||||
let (_dir, path) = init_repo();
|
||||
std::fs::write(path.join("nip34.json"), b"not json").expect("write");
|
||||
|
||||
assert!(binding_of(&path).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_patch_applies_cleanly_to_parent() {
|
||||
let (dir, path) = init_repo();
|
||||
git(&path, &["config", "user.name", "Test Author"]);
|
||||
git(&path, &["config", "user.email", "test@example.com"]);
|
||||
std::fs::write(path.join("file.txt"), "one\n").expect("write");
|
||||
git(&path, &["add", "."]);
|
||||
git(&path, &["commit", "-q", "-m", "first"]);
|
||||
std::fs::write(path.join("file.txt"), "two\n").expect("write");
|
||||
std::fs::write(path.join("file2.txt"), "added\n").expect("write");
|
||||
git(&path, &["add", "."]);
|
||||
git(&path, &["commit", "-q", "-m", "second"]);
|
||||
|
||||
let patch = Repo::open(&path)
|
||||
.expect("open repo")
|
||||
.commit_patch("HEAD")
|
||||
.expect("commit patch");
|
||||
assert!(patch.contains("diff --git a/file.txt b/file.txt"));
|
||||
assert!(patch.contains("diff --git a/file2.txt b/file2.txt"));
|
||||
assert!(patch.contains("--- /dev/null"));
|
||||
assert!(patch.contains("+added"));
|
||||
|
||||
let patch_path = dir.path().join("head.patch");
|
||||
std::fs::write(&patch_path, &patch).expect("write patch");
|
||||
git(&path, &["checkout", "-q", "--detach", "HEAD~1"]);
|
||||
git(
|
||||
&path,
|
||||
&["apply", patch_path.to_str().expect("utf8 patch path")],
|
||||
);
|
||||
|
||||
let applied = std::fs::read_to_string(path.join("file.txt")).expect("read");
|
||||
assert_eq!(applied, "two\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(path.join("file2.txt")).expect("read"),
|
||||
"added\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nak_exclude_and_state_refs_are_detected() {
|
||||
let (_dir, path) = init_repo();
|
||||
|
||||
std::fs::create_dir_all(path.join(".git/info")).expect("mkdir");
|
||||
std::fs::write(path.join(".git/info/exclude"), "nip34.json\n").expect("write");
|
||||
|
||||
git(&path, &["commit", "-q", "--allow-empty", "-m", "initial"]);
|
||||
git(
|
||||
&path,
|
||||
&["update-ref", "refs/heads/nip34/state/HEAD", "HEAD"],
|
||||
);
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nip34_excluded);
|
||||
assert!(binding.signals.nip34_state_refs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nostr_repo_config_marks_a_repository_initialized() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
|
||||
git(&path, &["config", "nostr.repo", &naddr]);
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nostr_repo_config);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_written_nostr_repo_marker_is_detected() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo");
|
||||
|
||||
Repo::open(&path)
|
||||
.expect("open")
|
||||
.set_nostr_repo(&naddr)
|
||||
.expect("write marker");
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nostr_repo_config);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nostr_remote_is_a_nip34_clone() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let npub = owner.to_bech32().expect("npub");
|
||||
let url = format!("nostr://{npub}/relay.ngit.dev/my-repo");
|
||||
git(&path, &["remote", "add", "origin", &url]);
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Cloned);
|
||||
assert!(binding.signals.nostr_remote);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nak_grasp_remote_marks_a_repository_initialized() {
|
||||
let (_dir, path) = init_repo();
|
||||
let owner = key();
|
||||
let npub = owner.to_bech32().expect("npub");
|
||||
let url = format!("https://gitnostr.com/{npub}/my-repo.git");
|
||||
git(
|
||||
&path,
|
||||
&["config", "remote.nip34/grasp/gitnostr.com.url", &url],
|
||||
);
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::Initialized);
|
||||
assert!(binding.signals.nip34_grasp_remote);
|
||||
assert!(binding.signals.grasp_remote);
|
||||
assert_eq!(binding.grasp_urls, vec![url]);
|
||||
assert_eq!(binding.owner, Some(owner));
|
||||
assert_eq!(binding.identifier.as_deref(), Some("my-repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nostr_cache_alone_is_tooling_only() {
|
||||
let (_dir, path) = init_repo();
|
||||
std::fs::write(path.join(".git/nostr-cache.lmdb"), b"cache").expect("write");
|
||||
|
||||
let binding = binding_of(&path).expect("binding");
|
||||
assert_eq!(binding.kind, Nip34Kind::ToolingOnly);
|
||||
assert!(binding.signals.nostr_cache);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grasp_urls_are_recognised_by_shape() {
|
||||
let owner = key();
|
||||
let npub = owner.to_bech32().expect("npub");
|
||||
|
||||
assert!(Repo::is_grasp_url(&format!(
|
||||
"https://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
assert!(Repo::is_grasp_url(&format!(
|
||||
"grasp://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
|
||||
assert!(!Repo::is_grasp_url("https://gitnostr.com/my-repo.git"));
|
||||
assert!(!Repo::is_grasp_url(
|
||||
"https://gitnostr.com/not-a-pubkey/my-repo.git"
|
||||
));
|
||||
assert!(!Repo::is_grasp_url(&format!(
|
||||
"ssh://gitnostr.com/{npub}/my-repo.git"
|
||||
)));
|
||||
}
|
||||
Reference in New Issue
Block a user