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

use crate::errors::{ Result, Error };
use crate::git::{ Git, RepositoryExtensions, OwnedTreeEntry };

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))
		.route("/repository/:repository", get(repository))
		.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(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(
	State(application_state): State<Arc<ApplicationState>>,
	Path(repository): Path<String>)
-> Result<Html<String>> {
	let context = repository_context(&application_state, &repository)?;
	let html = application_state.tera.render("repository.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,
	files: Vec<FileMetadata>,
}

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

#[derive(Serialize)]
struct FileMetadata {
	kind: FileKind,
	name: String,
	link: String,
}

#[derive(Serialize)]
enum FileKind {
	Directory,
	TextFile,
}

impl TryFrom<OwnedTreeEntry> for FileMetadata {
	type Error = Error;

	fn try_from(entry: OwnedTreeEntry) -> Result<FileMetadata> {
		Ok(FileMetadata {
			kind: entry.kind.try_into()?,
			name: entry.name,
			link: "/".to_string(),
		})
	}
}

impl TryFrom<git2::ObjectType> for FileKind {
	type Error = Error;

	fn try_from(t: git2::ObjectType) -> Result<FileKind> {
		use git2::ObjectType::*;

		match t {
			Tree => Ok(FileKind::Directory),
			Blob => Ok(FileKind::TextFile),
			_ => Err(Error::UnexpectedObjectType(t)),
		}
	}
}

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_name: &str) -> Result<Context> {
	let mut context = Context::new();

	let repo = application_state.git.find_repository_by_name(repository_name)?;
	let repo_head_contents = repo
		.list_commit_tree_by_name("HEAD")?
		.into_iter()
		.map(|entry| entry.try_into())
		.collect::<Result<Vec<FileMetadata>>>()?;

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

	let repository_context = RepositoryContext {
		name: repository_name.to_string(),
		files: repo_head_contents,
	};

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

	Ok(context)
}