Echo Writes Code

gitten.rs

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
mod configuration;
mod errors;
mod git;

use crate::errors::{ Result };
use crate::git::{ Git, GitObjectKind, GitObjectMetadata, Oid, Repository, RepositoryExtensions };

use axum::{ Router, serve };
use axum::extract::{ Path, State };
use axum::response::{ Html, };
use axum::routing::{ get };
use serde::{ Serialize };
use tera::{ Context, Tera };
use tokio::net::{ TcpListener };
use tower_http::services::{ ServeDir };
use tower_http::trace::{ TraceLayer };

use std::process::{ ExitCode };
use std::sync::{ Arc };

// -------------------------------------------------------------------------------------------------
// Application -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

#[tokio::main]
async fn main() -> ExitCode {
	let result = run_server().await;

	match result {
		Ok(_) => ExitCode::SUCCESS,
		Err(e) => {
			eprintln!("{}", e);
			ExitCode::FAILURE
		},
	}
}

struct ApplicationState {
	application_name: String,
	git: Git,
	tera: Tera,
}

async fn run_server() -> Result<()> {
	let configuration = configuration::configure()?;

	// Configure the shared server state object
	let application_state = ApplicationState {
		application_name: configuration.application_name.clone(),
		git: Git::open(std::path::Path::new(&configuration.git_root))?,
		tera: Tera::new("templates/**/*.tera.html")?,
	};

	// Define the application routing structure
	let router = Router::new()
		.layer(TraceLayer::new_for_http())
		.route("/", get(index_handler))
		.route("/repository/:repository", get(repository_handler))
		.route("/repository/:repository/tree/:tree", get(tree_handler))
		.route("/repository/:repository/blob/:blob", get(blob_handler))
		.nest_service("/static", ServeDir::new("static"))
		.with_state(Arc::new(application_state));

	// Bind to an address
	let address = format!("{}:{}", configuration.network_host, configuration.network_port);
	let listener = TcpListener::bind(address).await?;
	tracing::debug!("{} v0.1.0 now listening on {}", configuration.application_name, listener.local_addr()?);

	// Start the server
	serve(listener, router).await?;
	Ok(())
}

// -------------------------------------------------------------------------------------------------
// Route handlers ----------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

async fn index_handler(State(application_state): State<Arc<ApplicationState>>) -> Result<Html<String>> {
	let context = index_context(&application_state)?;
	let html = application_state.tera.render("index.tera.html", &context)?;
	Ok(Html(html))
}

async fn repository_handler(
	State(application_state): State<Arc<ApplicationState>>,
	Path(repository_name): Path<String>,
) -> Result<Html<String>> {
	let repository = application_state.git.find_repository_by_name(&repository_name)?;
	let context = repository_context(&application_state, &repository)?;

	let html = if repository.is_empty()? {
		application_state.tera.render("empty_repository.tera.html", &context)?
	} else {
		application_state.tera.render("repository.tera.html", &context)?
	};

	Ok(Html(html))
}

async fn tree_handler(
	State(application_state): State<Arc<ApplicationState>>,
	Path((repository_name, tree_id)): Path<(String, String)>,
) -> Result<Html<String>> {
	let repository = application_state.git.find_repository_by_name(&repository_name)?;
	let tree_id = Oid::from_str(&tree_id)?;
	let context = tree_context(&application_state, &repository, tree_id)?;
	let html = application_state.tera.render("tree.tera.html", &context)?;
	Ok(Html(html))
}

async fn blob_handler(
	State(application_state): State<Arc<ApplicationState>>,
	Path((repository_name, blob_id)): Path<(String, String)>,
) -> Result<Html<String>> {
	let repository = application_state.git.find_repository_by_name(&repository_name)?;
	let blob_id = Oid::from_str(&blob_id)?;
	let context = blob_context(&application_state, &repository, blob_id)?;
	let html = application_state.tera.render("blob.tera.html", &context)?;
	Ok(Html(html))
}

// -------------------------------------------------------------------------------------------------
// Template contexts -------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

#[derive(Serialize)]
struct ApplicationContext {
	name: String,
}

#[derive(Serialize)]
struct IndexContext {
	repositories: Vec<RepositoryMetadata>,
}

#[derive(Serialize)]
struct RepositoryContext {
	name: String,
	trees: Vec<GitObjectMetadata>,
	blobs: Vec<GitObjectMetadata>,
}

#[derive(Serialize)]
struct TreeContext {
	path: String,
	trees: Vec<GitObjectMetadata>,
	blobs: Vec<GitObjectMetadata>,
}

#[derive(Serialize)]
struct BlobContext {
	path: String,
	text: String,
	lines: Vec<String>,
}

#[derive(Serialize)]
struct RepositoryMetadata {
	name: String,
	link: String,
}

fn index_context(application_state: &ApplicationState) -> Result<Context> {
	let mut context = Context::new();

	let application_context = ApplicationContext {
		name: application_state.application_name.clone(),
	};

	let index_context = IndexContext {
		repositories: application_state.git.repositories()?.map(|r| {
			let repo_name = r?.name()?;
			Ok(RepositoryMetadata {
				name: repo_name.clone(),
				link: format!("/repository/{}", repo_name),
			})
		}).collect::<Result<Vec<RepositoryMetadata>>>()?,
	};

	context.insert("application", &application_context);
	context.insert("index", &index_context);

	Ok(context)
}

fn repository_context(application_state: &ApplicationState, repository: &Repository) -> Result<Context> {
	let mut context = Context::new();

	let head_content = if !repository.is_empty()? {
		repository
			.list_tree_by_commit_name("HEAD")?
			.into_iter()
			.collect()
	} else {
		Vec::new()
	};

	let trees = head_content
		.iter()
		.filter(|object| object.kind == GitObjectKind::Tree)
		.map(|object| object.clone())
		.collect::<Vec<_>>();

	let blobs = head_content
		.iter()
		.filter(|object| object.kind == GitObjectKind::Blob)
		.map(|object| object.clone())
		.collect::<Vec<_>>();

	let application_context = ApplicationContext {
		name: application_state.application_name.clone(),
	};

	let repository_context = RepositoryContext {
		name: repository.name()?,
		trees,
		blobs,
	};

	context.insert("application", &application_context);
	context.insert("repository", &repository_context);

	Ok(context)
}

fn tree_context(application_state: &ApplicationState, repository: &Repository, tree_id: Oid) -> Result<Context> {
	let mut context = Context::new();

	let tree_path = format!("{}/{}", repository.name()?, tree_id);
	let tree_content = repository
		.list_tree_by_id(tree_id)?
		.into_iter()
		.collect::<Vec<_>>();

	let trees = tree_content
		.iter()
		.filter(|object| object.kind == GitObjectKind::Tree)
		.map(|object| object.clone())
		.collect::<Vec<_>>();

	let blobs = tree_content
		.iter()
		.filter(|object| object.kind == GitObjectKind::Blob)
		.map(|object| object.clone())
		.collect::<Vec<_>>();

	let application_context = ApplicationContext {
		name: application_state.application_name.clone(),
	};

	let tree_context = TreeContext {
		path: tree_path,
		trees,
		blobs,
	};

	context.insert("application", &application_context);
	context.insert("tree", &tree_context);

	Ok(context)
}

fn blob_context(application_state: &ApplicationState, repository: &Repository, blob_id: Oid) -> Result<Context> {
	let mut context = Context::new();

	let blob_path = format!("{}/{}", repository.name()?, blob_id);
	let blob_text = repository.get_blob_text_by_id(blob_id)?;
	let blob_lines = {
		let mut line = 1;

		blob_text
			.lines()
			.map(|_| {
				let next = line;
				line += 1;
				next.to_string()
			})
			.collect::<Vec<_>>()
	};

	let application_context = ApplicationContext {
		name: application_state.application_name.clone(),
	};

	let blob_context = BlobContext {
		path: blob_path,
		text: blob_text,
		lines: blob_lines,
	};

	context.insert("application", &application_context);
	context.insert("blob", &blob_context);

	Ok(context)
}