1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | 'use strict';
|
14 |
|
15 | const escape = require('escape-html');
|
16 |
|
17 | const git = require('isomorphic-git');
|
18 | git.plugins.set('fs', require('fs'));
|
19 |
|
20 | const { debug } = require('@adobe/helix-log');
|
21 | const { resolveCommit, determineRefPathName } = require('./git');
|
22 | const { resolveRepositoryPath } = require('./utils');
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | function createMiddleware(options, urlType) {
|
32 | |
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | return async (req, res, next) => {
|
40 | const { owner } = req.params;
|
41 | const repoName = req.params.repo;
|
42 | let refName = req.params.ref || 'master';
|
43 | let fpath = req.params[0] || '';
|
44 |
|
45 | const repPath = resolveRepositoryPath(options, owner, repoName);
|
46 |
|
47 |
|
48 | const parsed = await determineRefPathName(repPath, `${req.params.ref}/${req.params[0]}`);
|
49 | if (parsed) {
|
50 | refName = parsed.ref;
|
51 | fpath = parsed.pathName;
|
52 | }
|
53 |
|
54 |
|
55 | while (fpath.length && fpath[0] === '/') {
|
56 |
|
57 | fpath = fpath.substr(1);
|
58 | }
|
59 |
|
60 |
|
61 | res.header('Content-Type', 'text/html');
|
62 |
|
63 | resolveCommit(repPath, refName)
|
64 | .then((commitOid) => git.readObject({ dir: repPath, oid: commitOid, filepath: fpath })
|
65 | .catch(() => null))
|
66 | .then((blobOrTree) => {
|
67 | if (!blobOrTree) {
|
68 | if (!fpath.length && urlType === 'tree') {
|
69 |
|
70 | res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>tree view not implemented yet.</body></html>`);
|
71 | } else {
|
72 | res.status(404).send(`not found: ${escape(fpath)}`);
|
73 | }
|
74 | return;
|
75 | }
|
76 |
|
77 | const { type } = blobOrTree;
|
78 | if (!fpath.length && type === 'tree' && urlType === 'root') {
|
79 |
|
80 | res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>root view not implemented yet.</body></html>`);
|
81 | } else if (type === 'tree' && urlType === 'tree') {
|
82 |
|
83 | res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>directory view not implemented yet.</body></html>`);
|
84 | } else if (type === 'blob' && urlType === 'blob') {
|
85 |
|
86 | res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>file view not implemented yet.</body></html>`);
|
87 | } else {
|
88 | res.status(404).send(`not found: ${escape(fpath)}`);
|
89 | }
|
90 | })
|
91 | .catch((err) => {
|
92 | debug(`[htmlHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
|
93 | next(err);
|
94 | });
|
95 | };
|
96 | }
|
97 | module.exports = createMiddleware;
|