1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
|
use std::{fs::File, io::BufReader, str::FromStr};
use anyhow::{bail, Context, Result};
use nostr::{secp256k1::XOnlyPublicKey, FromBech32, Tag, ToBech32};
use serde::{Deserialize, Serialize};
#[cfg(not(test))]
use crate::client::Client;
#[cfg(test)]
use crate::client::MockConnect;
use crate::{
client::Connect,
git::{Repo, RepoActions},
};
#[derive(Default)]
pub struct RepoRef {
pub name: String,
pub description: String,
pub root_commit: String,
pub git_server: String,
pub relays: Vec<String>,
pub maintainers: Vec<XOnlyPublicKey>,
// code languages and hashtags
}
impl TryFrom<nostr::Event> for RepoRef {
type Error = anyhow::Error;
fn try_from(event: nostr::Event) -> Result<Self> {
if !event.kind.as_u64().eq(&REPO_REF_KIND) {
bail!("incorrect kind");
}
let mut r = Self::default();
if let Some(t) = event.tags.iter().find(|t| t.as_vec()[0].eq("name")) {
r.name = t.as_vec()[1].clone();
}
if let Some(t) = event.tags.iter().find(|t| t.as_vec()[0].eq("description")) {
r.description = t.as_vec()[1].clone();
}
if let Some(t) = event.tags.iter().find(|t| t.as_vec()[0].eq("git-server")) {
r.git_server = t.as_vec()[1].clone();
}
if let Some(t) = event.tags.iter().find(|t| t.as_vec()[0].eq("d")) {
r.root_commit = t.as_vec()[1].clone();
}
r.relays = event
.tags
.iter()
.filter(|t| t.as_vec()[0].eq("relay"))
.map(|t| t.as_vec()[1].clone())
.collect();
for tag in event.tags.iter().filter(|t| t.as_vec()[0].eq("p")) {
let pk = tag.as_vec()[1].clone();
r.maintainers.push(
nostr_sdk::prelude::XOnlyPublicKey::from_str(&pk)
.context(format!("cannot convert {pk} into a valid nostr public key"))
.context("invalid repository event")?,
);
}
Ok(r)
}
}
static REPO_REF_KIND: u64 = 30_317;
impl RepoRef {
pub fn to_event(&self, keys: &nostr::Keys) -> Result<nostr::Event> {
nostr_sdk::EventBuilder::new(
nostr::event::Kind::Custom(REPO_REF_KIND),
"",
&[
vec![
Tag::Identifier(self.root_commit.to_string()),
Tag::Reference(format!("r-{}", self.root_commit)),
Tag::Name(self.name.clone()),
Tag::Description(self.description.clone()),
Tag::Generic(
nostr::TagKind::Custom("git-server".to_string()),
vec![self.git_server.clone()],
),
Tag::Reference(self.git_server.clone()),
],
self.relays.iter().map(|r| Tag::Relay(r.into())).collect(),
self.maintainers
.iter()
.map(|pk| Tag::PubKey(*pk, None))
.collect(),
// code languages and hashtags
]
.concat(),
)
.to_event(keys)
.context("failed to create repository reference event")
}
}
pub async fn fetch(
git_repo: &Repo,
root_commit: String,
#[cfg(test)] client: &MockConnect,
#[cfg(not(test))] client: &Client,
// TODO: more rubust way of finding repo events
fallback_relays: Vec<String>,
) -> Result<RepoRef> {
let repo_config = get_repo_config_from_yaml(git_repo);
// TODO: check events only from maintainers. get relay list of maintainters.
// check those relays.
let mut repo_event_filter = nostr::Filter::default()
.kind(nostr::Kind::Custom(REPO_REF_KIND))
.identifier(root_commit);
let mut relays = fallback_relays;
if let Ok(repo_config) = repo_config {
repo_event_filter =
repo_event_filter.pubkeys(extract_pks(repo_config.maintainers.clone())?);
relays = repo_config.relays.clone();
}
let events: Vec<nostr::Event> = client.get_events(relays, vec![repo_event_filter]).await?;
RepoRef::try_from(
events
.iter()
.filter(|e| e.kind.as_u64() == REPO_REF_KIND)
.max_by_key(|e| e.created_at)
.context("cannot find repository reference event")?
.clone(),
)
}
#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq, Eq)]
pub struct RepoConfigYaml {
pub maintainers: Vec<String>,
pub relays: Vec<String>,
}
pub fn get_repo_config_from_yaml(git_repo: &Repo) -> Result<RepoConfigYaml> {
let path = git_repo.get_path()?.join("maintainers.yaml");
let file = File::open(path)
.context("should open maintainers.yaml if it exists")
.context("maintainers.yaml doesnt exist")?;
let reader = BufReader::new(file);
let repo_config_yaml: RepoConfigYaml = serde_yaml::from_reader(reader)
.context("should read maintainers.yaml with serde_yaml")
.context("maintainers.yaml incorrectly formatted")?;
Ok(repo_config_yaml)
}
pub fn extract_pks(pk_strings: Vec<String>) -> Result<Vec<XOnlyPublicKey>> {
let mut pks: Vec<XOnlyPublicKey> = vec![];
for s in pk_strings {
pks.push(
nostr_sdk::prelude::XOnlyPublicKey::from_bech32(s.clone())
.context(format!("cannot convert {s} into a valid nostr public key"))?,
);
}
Ok(pks)
}
pub fn save_repo_config_to_yaml(
git_repo: &Repo,
maintainers: Vec<XOnlyPublicKey>,
relays: Vec<String>,
) -> Result<()> {
let path = git_repo.get_path()?.join("maintainers.yaml");
let file = if path.exists() {
std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path)
.context("cannot open maintainers.yaml file with write and truncate options")?
} else {
std::fs::File::create(path).context("cannot create maintainers.yaml file")?
};
let mut maintainers_npubs = vec![];
for m in maintainers {
maintainers_npubs.push(
m.to_bech32()
.context("cannot convert public key into npub")?,
);
}
serde_yaml::to_writer(
file,
&RepoConfigYaml {
maintainers: maintainers_npubs,
relays,
},
)
.context("cannot write maintainers to maintainers.yaml file serde_yaml")
}
#[cfg(test)]
mod tests {
use test_utils::*;
use super::*;
fn create() -> nostr::Event {
RepoRef {
name: "test name".to_string(),
description: "test description".to_string(),
root_commit: "23471389461".to_string(),
git_server: "https://localhost:1000".to_string(),
relays: vec!["ws://relay1.io".to_string(), "ws://relay2.io".to_string()],
maintainers: vec![TEST_KEY_1_KEYS.public_key(), TEST_KEY_2_KEYS.public_key()],
}
.to_event(&TEST_KEY_1_KEYS)
.unwrap()
}
mod try_from {
use super::*;
#[test]
fn name() {
assert_eq!(RepoRef::try_from(create()).unwrap().name, "test name",)
}
#[test]
fn description() {
assert_eq!(
RepoRef::try_from(create()).unwrap().description,
"test description",
)
}
#[test]
fn root_commit() {
assert_eq!(
RepoRef::try_from(create()).unwrap().root_commit,
"23471389461",
)
}
#[test]
fn git_server() {
assert_eq!(
RepoRef::try_from(create()).unwrap().git_server,
"https://localhost:1000",
)
}
#[test]
fn relays() {
assert_eq!(
RepoRef::try_from(create()).unwrap().relays,
vec!["ws://relay1.io".to_string(), "ws://relay2.io".to_string()],
)
}
#[test]
fn maintainers() {
assert_eq!(
RepoRef::try_from(create()).unwrap().maintainers,
vec![TEST_KEY_1_KEYS.public_key(), TEST_KEY_2_KEYS.public_key()],
)
}
}
mod to_event {
use super::*;
mod tags {
use super::*;
#[test]
fn name() {
assert!(
create()
.tags
.iter()
.any(|t| t.as_vec()[0].eq("name") && t.as_vec()[1].eq("test name"))
)
}
#[test]
fn description() {
assert!(create().tags.iter().any(
|t| t.as_vec()[0].eq("description") && t.as_vec()[1].eq("test description")
))
}
#[test]
fn root_commit_as_d_replaceable_event_identifier() {
assert!(
create()
.tags
.iter()
.any(|t| t.as_vec()[0].eq("d") && t.as_vec()[1].eq("23471389461"))
)
}
#[test]
fn git_server() {
assert!(create().tags.iter().any(|t| t.as_vec()[0].eq("git-server")
&& t.as_vec()[1].eq("https://localhost:1000")))
}
#[test]
fn git_server_as_reference() {
assert!(
create().tags.iter().any(
|t| t.as_vec()[0].eq("r") && t.as_vec()[1].eq("https://localhost:1000")
)
)
}
#[test]
fn root_commit_as_reference() {
assert!(
create()
.tags
.iter()
.any(|t| t.as_vec()[0].eq("r") && t.as_vec()[1].eq("r-23471389461"))
)
}
#[test]
fn relays() {
let event = create();
let relay_tags = event
.tags
.iter()
.filter(|t| t.as_vec()[0].eq("relay"))
.collect::<Vec<&nostr::Tag>>();
assert_eq!(relay_tags[0].as_vec().len(), 2);
assert_eq!(relay_tags[0].as_vec()[1], "ws://relay1.io");
assert_eq!(relay_tags[1].as_vec()[1], "ws://relay2.io");
}
#[test]
fn maintainers() {
let event = create();
let p_tags = event
.tags
.iter()
.filter(|t| t.as_vec()[0].eq("p"))
.collect::<Vec<&nostr::Tag>>();
assert_eq!(p_tags[0].as_vec().len(), 2);
assert_eq!(
p_tags[0].as_vec()[1],
TEST_KEY_1_KEYS.public_key().to_string()
);
assert_eq!(
p_tags[1].as_vec()[1],
TEST_KEY_2_KEYS.public_key().to_string()
);
}
#[test]
fn no_other_tags() {
assert_eq!(create().tags.len(), 10)
}
}
}
}
|