1 const {posix, sep} = require('node:path')
2
3 if (!process.env.GITHUB_TOKEN) {
4 throw new Error('GITHUB_TOKEN env var is required to build CLI docs')
5 }
6
7 let octokit
8 const owner = 'npm'
9 const repo = 'cli'
10 const opts = {owner, repo}
11
12 const getFile = async ({sha, ref, path}) => {
13 if (!octokit) {
14 const {Octokit} = await import('@octokit/rest')
15 octokit = new Octokit({auth: process.env.GITHUB_TOKEN})
16 }
17 const {data} = await (sha
18 ? octokit.git.getBlob({
19 ...opts,
20 file_sha: sha,
21 })
22 : octokit.repos.getContent({
23 ...opts,
24 ref,
25 path: path.split(sep).join(posix.sep),
26 }))
27 return Buffer.from(data.content, data.encoding)
28 }
29
30 const pathExists = async (ref, path) => {
31 if (!octokit) {
32 const {Octokit} = await import('@octokit/rest')
33 octokit = new Octokit({auth: process.env.GITHUB_TOKEN})
34 }
35 try {
36 await octokit.repos.getContent({
37 ...opts,
38 ref,
39 path: path.split(sep).join(posix.sep),
40 })
41 return path
42 } catch (err) {
43 /* istanbul ignore next */
44 if (!err.status === 404) {
45 throw err
46 }
47 }
48 return null
49 }
50
51 module.exports = {
52 getFile,
53 pathExists,
54 nwo: `${owner}/${repo}`,
55 }