This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
forked from primer/doctocat
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgatsby-node.js
103 lines (90 loc) · 2.72 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
const path = require('path');
const readPkgUp = require('read-pkg-up');
const getPkgRepo = require('get-pkg-repo');
const axios = require('axios');
const uniqBy = require('lodash.uniqby');
const dotenv = require('dotenv');
dotenv.config();
exports.createPages = async ({ graphql, actions }, themeOptions) => {
const repo = getPkgRepo(readPkgUp.sync().package);
const { data } = await graphql(`
{
allMdx {
nodes {
fileAbsolutePath
tableOfContents
parent {
... on File {
relativeDirectory
name
}
}
}
}
}
`);
// Turn every MDX file into a page.
return Promise.all(
data.allMdx.nodes.map(async (node) => {
const pagePath = path
.join(
node.parent.relativeDirectory,
node.parent.name === 'index' ? '/' : node.parent.name,
)
.replace(/\\/g, '/'); // Convert Windows backslash paths to forward slash paths: foo\\bar → foo/bar
const rootAbsolutePath = path.resolve(
process.cwd(),
themeOptions.repoRootPath || '.',
);
const fileRelativePath = path.relative(
rootAbsolutePath,
node.fileAbsolutePath,
);
const editUrl = getEditUrl(repo, fileRelativePath);
const contributors = await fetchContributors(repo, fileRelativePath);
actions.createPage({
path: pagePath,
component: node.fileAbsolutePath,
context: {
editUrl,
contributors,
tableOfContents: node.tableOfContents,
// We don't need to add `frontmatter` to the page context here
// because gatsby-plugin-mdx automatically does that.
// Source: https://git.io/fjQDa
},
});
}),
);
};
function getEditUrl(repo, filePath) {
return `https://github.com/${repo.user}/${repo.project}/edit/master/${filePath}`;
}
async function fetchContributors(repo, filePath) {
try {
const { data } = await axios.get(
`https://api.github.com/repos/${repo.user}/${repo.project}/commits?sha=${process.env.BRANCH}&path=${filePath}`,
{
headers: {
Authorization: `token ${process.env.GITHUB_TOKEN}`,
Accept: 'application/vnd.github.v3.raw',
},
},
);
const commits = data
.map((commit) => ({
login: commit.author && commit.author.login,
latestCommit: {
date: commit.commit.author.date,
url: commit.html_url,
},
}))
.filter((contributor) => Boolean(contributor.login));
return uniqBy(commits, 'login');
} catch (error) {
console.error(
`[ERROR] Unable to fetch contributors for ${filePath}. ${error.message}`,
);
return [];
}
}