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
296
297
298
299
300
301
use axum::{ Router, serve };
use axum::extract::{ State };
use axum::http::{ StatusCode };
use axum::response::{ Html, IntoResponse, Response };
use axum::routing::{ get };
use clap::{ Parser };
use config::{ Config };
use serde::{ Serialize };
use tera::{ Context, Tera };
use tracing_subscriber::layer::{ SubscriberExt };
use tracing_subscriber::util::{ SubscriberInitExt };
use tokio::net::{ TcpListener };
use tower_http::services::{ ServeDir };
use tower_http::trace::{ TraceLayer };

use std::fmt;
use std::fs;
use std::io;
use std::path::{ PathBuf };
use std::process::{ ExitCode };
use std::str::{ FromStr };
use std::sync::{ Arc };

// -------------------------------------------------------------------------------------------------
// Error handling ----------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

type Result<T> = ::std::result::Result<T, Error>;

#[derive(Debug)]
enum Error {
	ConfigError(config::ConfigError),
	IoError(io::Error),
	TeraError(tera::Error),
	InvalidGitRoot(io::Error),
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		use Error::*;

		match *self {
			ConfigError(ref e) => write!(f, "Config error: {}", e),
			IoError(ref e) => write!(f, "IO error: {}", e),
			TeraError(ref e) => write!(f, "Tera error: {}", e),
			InvalidGitRoot(ref e) => write!(f, "Invalid git.root: {}", e),
		}
	}
}

impl From<config::ConfigError> for Error {
	fn from(e: config::ConfigError) -> Error {
		Error::ConfigError(e)
	}
}

impl From<io::Error> for Error {
	fn from(e: io::Error) -> Error {
		Error::IoError(e)
	}
}

impl From<tera::Error> for Error {
	fn from(e: tera::Error) -> Error {
		Error::TeraError(e)
	}
}

impl IntoResponse for Error {
	fn into_response(self) -> Response {
		use Error::*;

		tracing::error!("Error when building response: {}", &self);

		let body = match self {
			ConfigError(..) => "The server encountered an unexpected error",
			IoError(..) => "The server encountered an unexpected error",
			TeraError(..) => "The server encountered an unexpected error",
			InvalidGitRoot(..) => "The server encountered an unexpected error",
		};

		(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
	}
}

// -------------------------------------------------------------------------------------------------
// Argument parsing --------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

#[derive(Parser)]
#[command(author, version, about)]
struct Arguments {
	/// Additional configuration files to load (may be passed multiple times)
	#[arg(id="configuration_file", short, long)]
	configuration_files: Vec<String>,

	/// Additional configuration parameters to use (may be passed multiple times; overrides configuration files)
	#[arg(id="set_parameter", short, long)]
	configuration_parameters: Vec<ArgumentPair>,
}

#[derive(Debug, Clone)]
struct ArgumentPair(String, String);

impl FromStr for ArgumentPair {
	type Err = clap::Error;

	fn from_str(s: &str) -> ::std::result::Result<ArgumentPair, clap::Error> {
		let parts: Vec<&str> = s.splitn(2, "=").collect();

		if parts.len() != 2 {
			return Err(clap::Error::new(clap::error::ErrorKind::WrongNumberOfValues));
		}

		Ok(ArgumentPair(parts[0].to_string(), parts[1].to_string()))
	}
}

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

struct ApplicationState {
	application_name: String,
	repositories: Vec<Repository>,
	tera: Tera,
}

struct Repository {
	name: String,
	path: PathBuf,
}

impl Repository {
	fn new(name: String, path: PathBuf) -> Repository {
		Repository {
			name,
			path
		}
	}
}

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

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

async fn run_server() -> Result<()> {
	let arguments = Arguments::parse();

	// Set up default configuration values
	let mut builder = Config::builder()
		.set_default("application.name", "Gitten")?
		.set_default("network.host", "localhost")?
		.set_default("network.port", 8080)?;

	// Read any configuration files
	for path in arguments.configuration_files {
		builder = builder.add_source(config::File::with_name(&path));
	}

	// Apply configuration parameters specified on the command line
	for parameter in arguments.configuration_parameters {
		builder = builder.set_override(parameter.0, parameter.1)?;
	}

	let config = builder.build()?;

	// Retrieve any configuration values we need
	let application_name = config.get_string("application.name")?;
	let git_root = config.get_string("git.root")?;
	let network_host = config.get_string("network.host")?;
	let network_port = config.get_int("network.port")?;

	// Configure tracing
	tracing_subscriber::registry()
		.with(tracing_subscriber::fmt::layer())
		.init();

	// Scan the git root for repositories
	let repositories = discover_git_repositories(&git_root)?;

	// Configure Tera (the templating engine)
	let tera = Tera::new("templates/**/*.tera.html")?;

	// Configure the shared server state object
	let application_state = ApplicationState {
		application_name: application_name.clone(),
		repositories,
		tera,
	};

	// Configure the router
	let router = Router::new()
		.layer(TraceLayer::new_for_http())
		.route("/", get(index))
		.nest_service("/static", ServeDir::new("static"))
		.with_state(Arc::new(application_state));

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

	serve(listener, router).await?;
	Ok(())
}

// -------------------------------------------------------------------------------------------------
// Git repositories --------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------

fn discover_git_repositories(git_root: &str) -> Result<Vec<Repository>> {
	let iterator = match fs::read_dir(git_root) {
		Ok(it) => Ok(it),
		Err(e) => Err(Error::InvalidGitRoot(e)),
	}?;

	let mut repositories = Vec::new();

	for entry in iterator {
		let repo_path = entry?.path();

		if !repo_path.is_dir() {
			tracing::debug!("{} is not a directory", repo_path.display());
			continue;
		}

		if repo_path.extension() != Some(std::ffi::OsStr::new("git")) {
			tracing::debug!("{} is not a git repository", repo_path.display());
			continue;
		}

		let Some(repo_name) = repo_path.file_stem() else {
			tracing::debug!("{} doesn't have a file stem", repo_path.display());
			continue;
		};

		let Some(repo_name) = repo_name.to_str() else {
			tracing::debug!("{} isn't valid UTF-8", repo_path.display());
			continue;
		};

		tracing::debug!("Detected git repository {} at {}", repo_name, repo_path.display());
		let repository = Repository::new(repo_name.to_string(), repo_path);
		repositories.push(repository);
	}

	Ok(repositories)
}

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

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

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

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

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

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

fn page_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.repositories.iter().map(|r| { RepositoryContext { name: r.name.clone(), link: "/".to_string() } }).collect(),
	};
	context.insert("application", &application_context);
	context.insert("index", &index_context);
	Ok(context)
}