-
Notifications
You must be signed in to change notification settings - Fork 30
/
fetch-repo.js
77 lines (61 loc) · 2.14 KB
/
fetch-repo.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
import { join as pathJoin } from 'path'
import regexParam from 'regexparam'
import fetch from 'isomorphic-unfetch'
const githubBlobUrl = regexParam('blob/:ref/*')
const isEmpty = obj =>
[Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length
const exec = (path, result) => {
let i = 0
let out = {}
let matches = result.pattern.exec(path) || {}
while (i < result.keys.length) out[result.keys[i]] = matches[++i] || null
return out
}
export default ({ isMarkdownPath, GITHUB_TOKEN, ALTERNATIVE_README_NAMES }) => {
const fetchReadme = ({ owner, repo, path, ref }) => {
return fetch(`https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${ref}`, {
headers: {
Accept: 'application/vnd.github.v3.raw',
Authorization: `token ${GITHUB_TOKEN}`
}
})
}
const fetchRepo = async ({ owner, repo }) => {
const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`, {
headers: {
Authorization: `token ${GITHUB_TOKEN}`
}
})
return response.json()
}
const fetchReadmeFromSource = async ({ owner, repo, ref, paths }) => {
for (const path of paths) {
const response = await fetchReadme({ owner, repo, ref, path })
if (response.status === 200) {
const markdown = await response.text()
return { markdown, path }
}
}
return {}
}
return async ({ owner, repo, path = '' }) => {
let ref
if (!isEmpty(path)) {
const execResult = exec(`/${path}`, githubBlobUrl)
if (execResult.ref) {
ref = execResult.ref
path = path.replace(`blob/${ref}`, '')
}
} else if (repo.includes('@')) {
;[repo, ref] = repo.split('@')
}
const paths = isMarkdownPath(path)
? [path]
: ALTERNATIVE_README_NAMES.map(readmeName => pathJoin(path, readmeName))
const info = await fetchRepo({ owner, repo })
if (!ref) ref = info.default_branch
const { markdown, path: inferPath } = await fetchReadmeFromSource({ owner, repo, paths, ref })
const source = { path: inferPath, owner, repo, paths, ref }
return { markdown, source, ...info }
}
}