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 getCurrentSha = async branch => {
19 if (!octokit) {
20 const {Octokit} = await import('@octokit/rest')
21 octokit = new Octokit({auth: process.env.GITHUB_TOKEN})
22 }
23 const {data} = await octokit.repos.getBranch({
24 ...opts,
25 branch,
26 })
27 return data.commit.sha
28 }
29
30 const getFile = async ({sha, ref, path}) => {
31 if (!octokit) {
32 const {Octokit} = await import('@octokit/rest')
33 octokit = new Octokit({auth: process.env.GITHUB_TOKEN})
34 }
35 const {data} = await (sha
36 ? octokit.git.getBlob({
37 ...opts,
38 file_sha: sha,
39 })
40 : octokit.repos.getContent({
41 ...opts,
42 ref,
43 path: path.split(sep).join(posix.sep),
44 }))
45 return Buffer.from(data.content, data.encoding)
46 }
47
48 const pathExists = async (ref, path) => {
49 if (!octokit) {
50 const {Octokit} = await import('@octokit/rest')
51 octokit = new Octokit({auth: process.env.GITHUB_TOKEN})
52 }
53 try {
54 await octokit.repos.getContent({
55 ...opts,
56 ref,
57 path: path.split(sep).join(posix.sep),
58 })
59 return path
60 } catch (err) {
61 /* istanbul ignore next */
62 if (!err.status === 404) {
63 throw err
64 }
65 }
66 return null
67 }
68
69 module.exports = {
70 getFile,
71 pathExists,
72 getCurrentSha,
73 nwo: `${owner}/${repo}`,
74 }