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

use crate::errors::{ Result };
use crate::git::{ GitRoot };

use axum::{ Router, serve };
use axum::extract::{ Path, State };
use axum::response::{ Html, };
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::process::{ ExitCode };
use std::str::{ FromStr };
use std::sync::{ Arc };

// -------------------------------------------------------------------------------------------------
// 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<SetParameter>,
}

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

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

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

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

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

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

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

#[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<()> {
	// Configure tracing (aka logging)
	tracing_subscriber::registry()
		.with(tracing_subscriber::fmt::layer())
		.init();

	// Parse command line arguments
	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)?;

	// Prepare the list of configuration files to read
	if !arguments.configuration_files.is_empty() {
		for path in arguments.configuration_files {
			tracing::debug!("Found configuration file: {}", path);
			builder = builder.add_source(config::File::with_name(&path));
		}
	} else {
		tracing::warn!("No configuration files detected; using default settings");
	}

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

	// Actually read the configuration files
	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")?;

	// Scan the git root for repositories
	let git = GitRoot::open(std::path::Path::new(&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(),
		git,
		tera,
	};

	// Configure the router
	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 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(())
}

// -------------------------------------------------------------------------------------------------
// 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,
	objects: Vec<ObjectMetadata>,
}

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

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

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

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()?.iter().map(|r| {
			RepositoryMetadata {
				name: r.name(),
				link: format!("/repository/{}", r.name())
			}
		}).collect(),
	};
	context.insert("application", &application_context);
	context.insert("index", &index_context);
	Ok(context)
}

fn repository_context(application_state: &ApplicationState, repository: &str) -> Result<Context> {
	let mut context = Context::new();
	let application_context = ApplicationContext {
		name: application_state.application_name.clone(),
	};
	let repository_context = RepositoryContext {
		name: repository.to_string(),
		objects: vec![ObjectMetadata { name: "foo.txt".to_string(), kind: ObjectKind::TextFile, link: format!("/repository/{}/object/{}", repository, "deadbeef") }],
	};
	context.insert("application", &application_context);
	context.insert("repository", &repository_context);
	Ok(context)
}