forked from EnterpriseDB/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
608 lines (544 loc) · 19 KB
/
gatsby-node.js
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
// this patch is required to consistently load all the doc files
const realFs = require("fs");
const path = require("path");
const gracefulFs = require("graceful-fs");
gracefulFs.gracefulify(realFs);
const { createFilePath } = require(`gatsby-source-filesystem`);
const { exec, execSync } = require("child_process");
const {
replacePathVersion,
filePathToDocType,
removeTrailingSlash,
isPathAnIndexPage,
pathToDepth,
mdxNodesToTree,
computeFrontmatterForTreeNode,
buildProductVersions,
reportMissingIndex,
treeToNavigation,
treeNodeToNavNode,
findPrevNextNavNodes,
configureRedirects,
configureLegacyRedirects,
readFile,
writeFile,
} = require("./src/constants/gatsby-utils.js");
const gitData = (() => {
// if this build was triggered by a GH action in response to a PR,
// use the head ref (the branch that someone is requesting be merged)
let branch = process.env.GITHUB_HEAD_REF;
// if this process was otherwise triggered by a GH action, use the current branch name
if (!branch) branch = process.env.GITHUB_REF;
// assuming this is triggered by a GH action, this will be the commit that triggered the workflow
let sha = process.env.GITHUB_SHA;
// non-GH Action build? Try actually running Git for the name & sha...
if (!branch) {
try {
branch = execSync("git rev-parse --abbrev-ref HEAD").toString();
sha = execSync("git rev-parse HEAD").toString();
} catch {}
}
if (!branch)
branch = process.env.APP_ENV === "production" ? "main" : "develop";
if (!sha) sha = "";
branch = branch
.trim()
.replace(/^refs\/heads\//, "")
.replace(/^refs\/tags\//, "");
sha = sha.trim();
return { branch, sha };
})();
exports.onCreateNode = async ({ node, getNode, actions, loadNodeContent }) => {
const { createNodeField } = actions;
if (node.internal.mediaType === "text/yaml") {
// See: https://github.com/gatsbyjs/gatsby/issues/34605
const content = await loadNodeContent(node);
createNodeField({ node, name: "content", value: content });
}
if (node.internal.type !== "Mdx") return;
const fileNode = getNode(node.parent);
const nodeFields = {
docType: filePathToDocType(node.fileAbsolutePath),
mtime: fileNode.mtime,
};
let relativeFilePath = createFilePath({ node, getNode });
if (nodeFields.docType === "doc") {
relativeFilePath = `/${fileNode.sourceInstanceName}${relativeFilePath}`;
}
Object.assign(nodeFields, {
path: relativeFilePath,
depth: pathToDepth(relativeFilePath),
});
if (nodeFields.docType === "doc") {
Object.assign(nodeFields, {
product: relativeFilePath.split("/")[1],
version: relativeFilePath.split("/")[2],
topic: "null",
});
} else if (nodeFields.docType === "advocacy") {
Object.assign(nodeFields, {
product: "null",
version: "0",
topic: relativeFilePath.split("/")[2],
});
}
for (const [name, value] of Object.entries(nodeFields)) {
createNodeField({ node, name: name, value: value });
}
};
exports.createPages = async ({ actions, graphql, reporter }) => {
const result = await graphql(`
query {
allMdx {
nodes {
id
frontmatter {
title
navTitle
description
redirects
iconName
originalFilePath
productStub
indexCards
originalFilePath
editTarget
navigation
legacyRedirects
legacyRedirectsGenerated
navigation
showInteractiveBadge
hideToC
katacodaPages {
scenario
account
}
katacodaPanel {
scenario
account
initializeCommand
codelanguages
}
hideVersion
displayBanner
directoryDefaults {
description
prevNext
iconName
editTarget
product
platform
indexCards
showInteractiveBadge
hideVersion
displayBanner
}
}
fields {
docType
path
depth
product
version
topic
}
fileAbsolutePath
}
}
allFile(filter: { extension: { eq: "yaml" } }) {
nodes {
id
relativePath
sourceInstanceName
}
}
}
`);
if (result.errors) {
reporter.panic("createPages graphql query has errors!", result.errors);
}
// this is critical to avoiding excessive Netlify deploy times: it ensures the pages are ordered consistently from build to build
result.data.allMdx.nodes = result.data.allMdx.nodes.sort((a, b) =>
a.fields.path.localeCompare(b.fields.path),
);
const { nodes } = result.data.allMdx;
const productVersions = buildProductVersions(nodes);
processFileNodes(result.data.allFile.nodes, productVersions, actions);
// it should be possible to remove these in the future,
// they are only used for navLinks generation
const learn = nodes.filter((file) => file.fields.docType === "advocacy");
// perform depth first preorder traversal
const treeRoot = mdxNodesToTree(nodes);
const navStack = [treeRoot];
let curr = null;
while (navStack.length > 0) {
curr = navStack.pop();
curr.children.forEach((child) => navStack.push(child));
// build ordered navigation for immediate children
// treeToNavigation will use this data
const addedChildPaths = {};
curr.navigationNodes = [];
(curr.mdxNode?.frontmatter?.navigation || []).forEach((navEntry) => {
if (navEntry.startsWith("#")) {
curr.navigationNodes.push({
path: null,
title: navEntry.replace("#", "").trim(),
});
return;
}
const navChild = curr.children.find((child) => {
if (addedChildPaths[child.path]) return false;
const navName = child.path.split("/").slice(-2)[0];
return navName.toLowerCase() === navEntry.toLowerCase();
});
if (!navChild?.mdxNode) return;
addedChildPaths[navChild.path] = true;
curr.navigationNodes.push(treeNodeToNavNode(navChild));
});
curr.children
.filter((child) => !addedChildPaths[child.path])
.map((child) => treeNodeToNavNode(child))
.sort((a, b) => a.path.localeCompare(b.path))
.forEach((child) => curr.navigationNodes.push(child));
// exit here if we're not dealing with an actual page
if (!curr.mdxNode) {
reportMissingIndex(reporter, curr);
continue;
}
const node = curr.mdxNode;
// set computed frontmatter
node.frontmatter = computeFrontmatterForTreeNode(curr);
// build navigation tree
const navigationDepth = 1;
let navRoot = curr;
while (navRoot.depth > navigationDepth && navRoot?.parent?.mdxNode)
navRoot = navRoot.parent;
const navTree = treeToNavigation(navRoot, node);
// determine next and previous nodes
const prevNext = findPrevNextNavNodes(navTree, curr);
const { docType } = node.fields;
const isLatest =
docType === "doc"
? productVersions[node.fields.product][0] === node.fields.version
: false;
configureRedirects(
node.fields.path,
isLatest,
node.frontmatter.redirects,
actions,
);
if (docType === "doc") {
createDoc(navTree, prevNext, node, productVersions, actions);
} else if (docType === "advocacy") {
createAdvocacy(navTree, prevNext, node, learn, actions);
}
}
};
const createDoc = (navTree, prevNext, doc, productVersions, actions) => {
const isLatest =
productVersions[doc.fields.product][0] === doc.fields.version;
if (isLatest) {
actions.createRedirect({
fromPath: doc.fields.path,
toPath: replacePathVersion(doc.fields.path),
redirectInBrowser: true,
isPermanent: false,
force: true,
});
}
// configure legacy redirects
if (!doc.frontmatter.productStub) {
configureLegacyRedirects({
toPath: doc.fields.path,
toLatestPath: replacePathVersion(doc.fields.path),
redirects: (doc.frontmatter.legacyRedirects || []).concat(
doc.frontmatter.legacyRedirectsGenerated || [],
),
actions,
});
}
const isIndexPage = isPathAnIndexPage(doc.fileAbsolutePath);
const docsRepoUrl = "https://github.com/EnterpriseDB/docs";
// don't encourage folks to edit on main - set the edit links to develop in production builds
const branch = gitData.branch === "main" ? "develop" : gitData.branch;
const fileUrlSegment =
removeTrailingSlash(doc.fields.path) +
(isIndexPage ? "/index.mdx" : ".mdx");
const githubFileLink = `${docsRepoUrl}/commits/${branch}/product_docs/docs${fileUrlSegment}`;
const githubEditLink = `${docsRepoUrl}/edit/${branch}/product_docs/docs${fileUrlSegment}`;
const githubIssuesLink = `${docsRepoUrl}/issues/new?title=Feedback%20on%20${encodeURIComponent(
fileUrlSegment,
)}`;
const template = doc.frontmatter.productStub ? "doc-stub.js" : "doc.js";
const path = isLatest ? replacePathVersion(doc.fields.path) : doc.fields.path;
actions.createPage({
path: path,
component: require.resolve(`./src/templates/${template}`),
context: {
frontmatter: doc.frontmatter,
pagePath: path,
navTree,
prevNext,
versions: productVersions[doc.fields.product],
nodeId: doc.id,
githubFileLink: githubFileLink,
githubEditLink: githubEditLink,
githubIssuesLink: githubIssuesLink,
isIndexPage: isIndexPage,
potentialLatestPath: replacePathVersion(doc.fields.path), // the latest url for this path (may not exist!)
potentialLatestNodePath: replacePathVersion(
doc.fields.path,
productVersions[doc.fields.product][0],
), // the latest version number path (may not exist!), needed for query
},
});
(doc.frontmatter.katacodaPages || []).forEach((katacodaPage) => {
if (!katacodaPage.scenario || !katacodaPage.account) {
throw new Error(
`katacoda scenario or account missing for ${doc.fields.path}`,
);
}
const path = `${doc.fields.path}${katacodaPage.scenario}`;
actions.createPage({
path: path,
component: require.resolve("./src/templates/katacoda-page.js"),
context: {
...katacodaPage,
pagePath: path,
learn: {
title: doc.frontmatter.title,
description: doc.frontmatter.description,
},
},
});
});
};
const createAdvocacy = (navTree, prevNext, doc, learn, actions) => {
// configure legacy redirects
configureLegacyRedirects({
toPath: doc.fields.path,
toLatestPath: doc.fields.path,
redirects: (doc.frontmatter.legacyRedirects || []).concat(
doc.frontmatter.legacyRedirectsGenerated || [],
),
actions,
});
const navLinks = learn.filter(
(node) => node.fields.topic === doc.fields.topic,
);
const advocacyDocsRepoUrl = "https://github.com/EnterpriseDB/docs";
// don't encourage folks to edit on main - set the edit links to develop in production builds
const branch = gitData.branch === "main" ? "develop" : gitData.branch;
const isIndexPage = isPathAnIndexPage(doc.fileAbsolutePath);
const fileUrlSegment =
removeTrailingSlash(doc.fields.path) +
(isIndexPage ? "/index.mdx" : ".mdx");
const githubFileLink = `${advocacyDocsRepoUrl}/commits/${branch}/advocacy_docs${fileUrlSegment}`;
const githubEditLink = `${advocacyDocsRepoUrl}/edit/${branch}/advocacy_docs${fileUrlSegment}`;
const githubIssuesLink = `${advocacyDocsRepoUrl}/issues/new?title=Regarding%20${encodeURIComponent(
fileUrlSegment,
)}`;
// workaround for https://github.com/gatsbyjs/gatsby/issues/26520
actions.createPage({
path: doc.fields.path,
component: require.resolve("./src/templates/learn-doc.js"),
context: {},
});
actions.createPage({
path: doc.fields.path,
component: require.resolve("./src/templates/learn-doc.js"),
context: {
nodeId: doc.id,
frontmatter: doc.frontmatter,
pagePath: doc.fields.path,
navLinks: navLinks,
prevNext,
navTree,
githubFileLink: githubFileLink,
githubEditLink: githubEditLink,
githubIssuesLink: githubIssuesLink,
isIndexPage: isIndexPage,
},
});
(doc.frontmatter.katacodaPages || []).forEach((katacodaPage) => {
if (!katacodaPage.scenario || !katacodaPage.account) {
throw new Error(
`katacoda scenario or account missing for ${doc.fields.path}`,
);
}
const path = `${doc.fields.path}${katacodaPage.scenario}`;
actions.createPage({
path: path,
component: require.resolve("./src/templates/katacoda-page.js"),
context: {
...katacodaPage,
pagePath: path,
learn: {
title: doc.frontmatter.title,
description: doc.frontmatter.description,
},
},
});
});
};
const processFileNodes = (fileNodes, productVersions, actions) => {
fileNodes.forEach((node) => {
const product =
node.sourceInstanceName === "advocacy_docs"
? ""
: node.sourceInstanceName;
const version = node.relativePath.split(path.sep)[0];
const isLatest = product ? productVersions[product][0] === version : false;
let urlPath = path.join(path.sep, product, node.relativePath);
if (isLatest) {
const latestPath = replacePathVersion(urlPath);
actions.createRedirect({
fromPath: urlPath,
toPath: latestPath,
redirectInBrowser: true,
isPermanent: false,
force: true,
});
urlPath = latestPath;
}
actions.createPage({
path: urlPath,
component: require.resolve("./src/templates/file.js"),
context: {
nodeId: node.id,
},
});
});
};
exports.sourceNodes = async ({
actions: { createNode },
createNodeId,
createContentDigest,
}) => {
// create edb-git node
createNode({
...gitData,
id: createNodeId("edb-git"),
internal: {
type: "edbGit",
contentDigest: createContentDigest(gitData),
},
});
};
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type Mdx implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
description: String
prevNext: Boolean
iconName: String
product: String
platform: String
originalFilePath: String
indexCards: TileModes
editTarget: EditTargets
legacyRedirects: [String]
legacyRedirectsGenerated: [String]
showInteractiveBadge: Boolean
hideToC: Boolean
hideVersion: Boolean
displayBanner: String
directoryDefaults: DirectoryDefaults
}
enum TileModes {
none
simple
full
}
enum EditTargets {
github
originalFilePath
none
}
type DirectoryDefaults {
description: String
prevNext: Boolean
iconName: String
product: String
platform: String
indexCards: TileModes
editTarget: EditTargets
showInteractiveBadge: Boolean
hideVersion: Boolean
displayBanner: String
}
`;
createTypes(typeDefs);
};
exports.onPreBootstrap = () => {
console.log(`
_____ ____ _____ ____
| __|| \\ | __ | | \\ ___ ___ ___
| __|| | || __ -| | | || . || _||_ -|
|_____||____/ |_____| |____/ |___||___||___|
`);
};
exports.onPostBuild = async ({ reporter, pathPrefix }) => {
realFs.copyFileSync(
path.join(__dirname, "/netlify.toml"),
path.join(__dirname, "/public/netlify.toml"),
);
const originalRedirects = await readFile("public/_redirects");
// rewrite legacy redirects to exclude the /docs prefix
const prefixRE = new RegExp(`^${pathPrefix}/edb-docs/`);
let rewrittenRedirects = originalRedirects
.split("\n")
.map((line) => line.replace(prefixRE, "/edb-docs/"))
.join("\n");
if (rewrittenRedirects.length === originalRedirects.length) {
reporter.warn("no legacy redirects were rewritten, did something change?");
}
await writeFile(
"public/_redirects",
`${rewrittenRedirects}
# Catch-all legacy redirects
/edb-docs/d/edb-backup-and-recovery-tool/* /docs/bart/latest/ 301
/edb-docs/d/edb-postgres-enterprise-manager/* /docs/pem/latest/ 301
/edb-docs/d/edb-postgres-advanced-server/* /docs/epas/latest/ 301
/edb-docs/d/postgresql/* /docs/supported-open-source/postgresql/ 301
/edb-docs/d/edb-postgres-failover-manager/* /docs/efm/latest/ 301
/edb-docs/d/edb-postgres-replication-server/* /docs/eprs/latest/ 301
/edb-docs/d/pgadmin-4/* /docs/supported-open-source/pgadmin/ 301
/edb-docs/d/edb-postgres-language-pack/* /docs/epas/latest/language_pack/ 301
/edb-docs/d/edb-postgres-migration-toolkit/* /docs/migration_toolkit/latest/ 301
/edb-docs/d/edb-postgres-migration-portal/* /docs/migration_portal/latest/ 301
/edb-docs/d/edb-postgres-hadoop-data-adapter/* /docs/hadoop_data_adapter/latest/ 301
/edb-docs/d/jdbc-connector/* /docs/jdbc_connector/latest/ 301
/edb-docs/d/edb-postgres-ocl-connector/* /docs/ocl_connector/latest/ 301
/edb-docs/d/edb-postgres-net-connector/* /docs/net_connector/latest/ 301
/edb-docs/d/edb-postgres-odbc-connector/* /docs/odbc_connector/latest/ 301
/edb-docs/p/edb-postgres-advanced-server/* /docs/epas/latest/ 301
/edb-docs/p/postgresql/* /docs/supported-open-source/postgresql/ 301
/edb-docs/p/edb-postgres-replication-server/* /docs/eprs/latest/ 301
/edb-docs/p/edb-postgres-failover-manager/* /docs/efm/latest/ 301
/edb-docs/p/pgadmin-4/* /docs/supported-open-source/pgadmin/ 301
/edb-docs/p/edb-postgres-migration-toolkit/* /docs/migration_toolkit/latest/ 301
/edb-docs/p/edb-postgres-hadoop-data-adapter/* /docs/hadoop_data_adapter/latest/ 301
/edb-docs/p/edb-postgres-language-pack/* /docs/epas/latest/language_pack/ 301
/edb-docs/p/jdbc-connector/* /docs/jdbc_connector/latest/ 301
/edb-docs/p/edb-postgres-net-connector/* /docs/net_connector/latest/ 301
/edb-docs/p/edb-postgres-slony-replication/* /docs/slony/latest/ 301
/edb-docs/p/pgpool-ii/* /docs/pgpool/latest/ 301
/edb-docs/p/edb-postgres-mysql-data-adapter/* /docs/mysql_data_adapter/latest/ 301
/edb-docs/p/edb-postgres-postgis/* /docs/postgis/latest/ 301
/edb-docs/p/pgbouncer/* /docs/pgbouncer/latest/ 301
/edb-docs/p/edb-postgres-mongodb-data-adapter/* /docs/mongo_data_adapter/latest/ 301
/edb-docs/p/edb-postgres-migration-portal/* /docs/migration_portal/latest/ 301
/edb-docs/p/edb-postgres-enterprise-manager/* /docs/pem/latest/ 301
/edb-docs/p/edbplus/* /docs/edb_plus/latest/ 301
/edb-docs/p/edb-postgres-odbc-connector/* /docs/odbc_connector/latest/ 301
/edb-docs/p/edb-postgres-ocl-connector/* /docs/ocl_connector/latest/ 301
/edb-docs/p/edb-backup-and-recovery-tool/* /docs/bart/latest/ 301
/edb-docs/* /docs/ 301
# Netlify pathPrefix path rewrite
${pathPrefix}/* /:splat 200`,
);
};