Create a cloud function to generate HTML diffs for Phabricator revisions (#3494)

This commit is contained in:
Suhaib Mujahid 2023-06-02 10:02:11 -04:00 коммит произвёл GitHub
Родитель a8d07e8f15
Коммит 3032922276
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
2 изменённых файлов: 95 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,88 @@
const https = require("https");
const functions = require("@google-cloud/functions-framework");
const Diff2html = require("diff2html");
const agent = new https.Agent({ keepAlive: true });
const headers = new Headers({
"User-Agent": "bugbug-diff2html",
});
const configuration = {
// Diff2Html Configuration
outputFormat: "line-by-line",
matching: "lines",
renderNothingWhenEmpty: false,
diffStyle: "word",
// Diff2HtmlUI Configuration
synchronisedScroll: true,
highlight: true,
fileListToggle: true,
fileListStartVisible: false,
fileContentToggle: true,
stickyFileHeaders: true,
};
/**
* Responds to any HTTP request.
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
functions.http("revisionDiff2html", (req, res) => {
res.set("Access-Control-Allow-Origin", "*");
let revision_id = req.query.revision_id;
let diff_id = req.query.diff_id;
let enableJS = req.query.format !== "html";
if (isNaN(revision_id) || isNaN(diff_id)) {
res.status(400).send("Invalid IDs");
return;
}
const url = `https://phabricator.services.mozilla.com/D${revision_id}?id=${diff_id}&download=true`;
fetch(url, { agent, headers })
.then((res) => res.text())
.then((text) => strDiff2Html(text, enableJS))
.then((output) => res.status(200).send(output))
.catch((err) => res.status(500).send(`Error: ${err.message}`));
});
const jsTemplate = `
<meta charset="utf-8" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.1/styles/github.min.css"
/>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/diff2html/bundles/js/diff2html-ui.min.js"
></script>
<script>
document.addEventListener("DOMContentLoaded", () => {
const targetElement = document.getElementById("diff");
const diff2htmlUi = new Diff2HtmlUI(targetElement);
diff2htmlUi.fileListToggle(false);
diff2htmlUi.fileContentToggle();
diff2htmlUi.synchronisedScroll();
diff2htmlUi.highlightCode();
});
</script>
`;
function strDiff2Html(strDiff, enableJS) {
const diffHtml = Diff2html.html(strDiff, configuration);
return `<!DOCTYPE html>
<html lang="en-us">
<head>${enableJS ? jsTemplate : ""}
<link
rel="stylesheet"
type="text/css"
href="https://cdn.jsdelivr.net/npm/diff2html/bundles/css/diff2html.min.css"
/>
</head>
<body>
<div id="diff">${diffHtml}</div>
</body>
</html>
`;
}

Просмотреть файл

@ -0,0 +1,7 @@
{
"name": "diff2html-revision",
"dependencies": {
"@google-cloud/functions-framework": "^3.1.2",
"diff2html": "3.4.35"
}
}