summary refs log tree commit diff
path: root/fleet/pkgs/naut/src/main.rs
blob: ed38a961093908cfce7a95babc0b172ab9516086 (plain)
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
// SPDX-FileCopyrightText: V <v@unfathomable.blue>
// SPDX-License-Identifier: OSL-3.0

use {
	anyhow::{anyhow, Error, Result},
	git2::{Oid, Repository, Sort},
	irc::client::prelude::*,
	pin_utils::pin_mut,
	std::{env, fs::remove_file, io::ErrorKind},
	tokio::{
		io::{AsyncBufRead, AsyncBufReadExt, BufReader, Lines},
		net::UnixListener,
		select, spawn,
		sync::{mpsc, mpsc::UnboundedSender},
	},
	tokio_stream::{wrappers::UnboundedReceiverStream, StreamExt},
};

#[derive(Debug)]
struct Batch {
	lines: Vec<String>,
}

#[tokio::main]
async fn main() -> Result<()> {
	let (tx, rx) = mpsc::unbounded_channel::<Batch>();

	let listener = bind(env::var("NAUT_SOCK")?.as_str())?;
	spawn(async move {
		loop {
			let (stream, _) = listener.accept().await.unwrap();

			let tx = tx.clone();

			let conn = async move {
				let lines = BufReader::new(stream).lines();
				let repo = Repository::open("/var/lib/git/basin")?;

				handle(repo, lines, tx).await?;
				Ok::<(), Error>(())
			};

			spawn(async move {
				if let Err(e) = conn.await {
					eprintln!("Failed to handle request: {e}");
				}
			});
		}
	});

	let channel = "#ripple";
	let client_config = Config {
		server: Some("irc.libera.chat".to_owned()),
		password: Some(env::var("NAUT_PASS")?),
		nickname: Some("naut".to_owned()),
		realname: Some("blub blub".to_owned()),
		version: Some(format!("naut {}", env!("CARGO_PKG_VERSION"))),
		source: Some("https://src.unfathomable.blue/tree/fleet/pkgs/naut".to_owned()),
		channels: vec![channel.to_owned()],
		..Default::default()
	};

	let rx = UnboundedReceiverStream::new(rx).fuse();
	pin_mut!(rx);

	loop {
		let mut client = Client::from_config(client_config.clone()).await?;
		client.identify()?;

		let sender = client.sender();

		let stream = client.stream()?.fuse();
		pin_mut!(stream);

		loop {
			select! {
				message = stream.next() => match message {
					Some(_) => {},
					None => break,
				},
				Some(batch) = rx.next() => {
					for line in batch.lines {
						sender.send_privmsg("#ripple", line.to_owned())?;
					}
				},
			}
		}
	}
}

fn bind(path: &str) -> Result<UnixListener> {
	match remove_file(path) {
		Ok(()) => (),
		Err(e) if e.kind() == ErrorKind::NotFound => (),
		Err(e) => return Err(e.into()),
	}

	UnixListener::bind(path).map_err(Error::from)
}

async fn handle(
	repo: Repository,
	mut lines: Lines<impl AsyncBufRead + Unpin>,
	tx: UnboundedSender<Batch>,
) -> Result<()> {
	while let Some(line) = lines.next_line().await? {
		let args: Vec<_> = line.splitn(3, ' ').collect();

		let old = Oid::from_str(args[0])?;
		let new = Oid::from_str(args[1])?;
		let r#ref = repo.find_reference(args[2])?;
		let ref_name = r#ref.shorthand().unwrap();

		let mut lines = vec![];

		if r#ref.is_branch() {
			if new.is_zero() {
				lines.push(format!("branch {ref_name} deleted (was {old})"));
			} else {
				let mut walker = repo.revwalk()?;
				walker.set_sorting(Sort::REVERSE)?;
				walker.push(new)?;

				if old.is_zero() {
					lines.push(format!("new branch created: {ref_name}"));

					// We cannot use repo.head directly, as that comes resolved already.
					let head = repo.find_reference("HEAD")?;

					// Hide commits also present from HEAD (unless this *is* HEAD, in which we do want them).
					// This avoids duplicating notifications for commits that we've already seen, provided we
					// only push branches that are forked directly from HEAD (or one of its ancestors).
					if ref_name != head.symbolic_target().unwrap() {
						if let Ok(base) = repo.merge_base(head.resolve()?.target().unwrap(), new) {
							walker.hide(base)?;
						}
					}
				} else {
					walker.hide(old)?;
				}

				let commits: Vec<_> = walker
					.map(|x| repo.find_commit(x.unwrap()).unwrap())
					.filter(|c| {
						// TODO(edef): we need a saner model here
						// history that doesn't descend from the monorepo root shouldn't make it here at all
						c.parents()
							.next()
							.map(|parent| {
								let t1 = parent.tree().unwrap().get_name("ripple").map(|e| e.id());
								let t2 = c.tree().unwrap().get_name("ripple").map(|e| e.id());
								t1 != t2
							})
							.unwrap_or_default()
					})
					.collect();

				if !commits.is_empty() {
					lines.push(format!(
						"{} {} pushed to {ref_name}",
						commits.len(),
						if commits.len() == 1 {
							"commit"
						} else {
							"commits"
						},
					));

					for commit in commits {
						lines.push(format!(
							"  {} \"{}\" by {}",
							commit.as_object().short_id()?.as_str().unwrap(),
							commit.summary().unwrap(),
							commit.author().name().unwrap()
						));
					}
				}
			}
		} else if r#ref.is_tag() {
			lines.push(if new.is_zero() {
				format!("tag {ref_name} deleted (was {old})")
			} else if old.is_zero() {
				format!("commit {new} tagged as {ref_name}")
			} else {
				format!("tag {ref_name} modified (was {old}, now {new})")
			});
		} else {
			return Err(anyhow!(
				"Received a reference that's neither a branch nor tag: {}",
				args[2]
			));
		}

		tx.send(Batch { lines })?;
	}

	Ok(())
}