aboutsummaryrefslogtreecommitdiff
path: root/app.js
blob: 51c89581dd63cd6ef65d221e66c8e5092feb9732 (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
const express = require("express");
const api = require("./api/v1");
const git = require("./api/git");
const yaml = require('js-yaml');
const fs = require('fs');
const { exit } = require("process");

let settings;

try {
	settings = yaml.load(fs.readFileSync("./settings.yml", 'utf8'));
} catch(e) {
	throw(e);
}

const mandatory_settings = ["host", "port", "title", "about", "base_dir"];
const missing_settings_key = mandatory_settings.find(key => settings.hasOwnProperty(key) === false);
if(missing_settings_key) {
	console.error(`Error: missing key in settings.yml: ${missing_settings_key}`);
	exit(1);
}

const app = express();

app.get(/.*\.(css|js|ico)$/, (req, res, next) =>
{
	fs.access(`dist${req.path}`, err =>
	{
		if(err) {
			next();
			return;
		}
		res.sendFile(`dist${req.path}`, { root: __dirname });
	});
});

app.use("/api/v1", (req, res, next) =>
{
	req.settings = settings;
	next();
}, api);

app.use("/:repo", async (req, res, next) =>
{
	let repo_dirs = await git.getRepos(settings["base_dir"]);

	if(repo_dirs["error"]) {
		res.status(500).send("Internal server error!");
		return;
	}

	if(!repo_dirs["data"].includes(req.params.repo)) {
		res.status(404).send("404: Page not found");
		return;
	}
	next();
})

app.get("/:repo", (req, res, next) =>
{
	res.redirect(`/${req.params.repo}/log`);
});

app.get("/:repo/:page", (req, res, next) =>
{
	const pages = ["log", "refs", "tree"];
	if(!pages.includes(req.params.page)) {
		next();
		return;
	}
	
	res.sendFile("dist/app.html", { root: __dirname });
});

app.get("/", (req, res) =>
{
	res.sendFile("dist/app.html", { root: __dirname });
});

app.use((req, res) =>
{
	res.status(404).send("404: Page not found");
});

app.listen(settings["port"], settings["host"], () => console.log(`App is running on ${settings["host"]}:${settings["port"]}`));