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