|
1 | 1 | // @ts-check |
2 | 2 |
|
| 3 | +import os from 'os' |
| 4 | +import fs from 'fs' |
| 5 | +import path from 'path' |
| 6 | + |
| 7 | +/** @type boolean */ |
| 8 | +let hasRepoScope; |
| 9 | + |
3 | 10 | /** |
4 | 11 | * An Octoherd script to download files from repositories |
5 | 12 | * |
|
10 | 17 | * @param {string} options.source Path to the destination directory |
11 | 18 | * @param {string} options.target File path to download. Note: Directories are not supported yet |
12 | 19 | */ |
13 | | -export async function script( |
14 | | - octokit, |
15 | | - repository, |
16 | | - { ignoreArchived, source, target } |
17 | | -) {} |
| 20 | +export async function script(octokit, repository, { source, target = process.cwd(), ignoreArchived = true }) { |
| 21 | + if (!hasRepoScope) { |
| 22 | + const { headers } = await octokit.request("HEAD /"); |
| 23 | + const scopes = new Set(headers["x-oauth-scopes"].split(", ")); |
| 24 | + |
| 25 | + if (!scopes.has("repo")) { |
| 26 | + throw new Error( |
| 27 | + `The "repo" scope is required for this script. Create a token at https://github.com/settings/tokens/new?scopes=repo then run the script with "-T <paste token here>"` |
| 28 | + ); |
| 29 | + } |
| 30 | + hasRepoScope = true; |
| 31 | + } |
| 32 | + |
| 33 | + if (ignoreArchived && repository.archived) { |
| 34 | + octokit.log.warn(`IGNORE repository is archived`); |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + if (!source) { |
| 39 | + octokit.log.error('Please specify a source file to download with --source=README.md') |
| 40 | + process.exit(1); |
| 41 | + } |
| 42 | + |
| 43 | + if (!target) { |
| 44 | + octokit.log.error('Please specify a source file to download with --source=README.md --target=./out') |
| 45 | + process.exit(1); |
| 46 | + } |
| 47 | + |
| 48 | + await octokit.request( |
| 49 | + `GET /repos/{owner}/{repo}/contents/${source}`, |
| 50 | + { |
| 51 | + owner: repository.owner.login, |
| 52 | + repo: repository.name, |
| 53 | + headers: { |
| 54 | + Accept: "application/vnd.github.v3.raw" |
| 55 | + } |
| 56 | + } |
| 57 | + ).then((res) => { |
| 58 | + octokit.log.info(`Download ${source}`); |
| 59 | + |
| 60 | + // Expand the ~ character to a users home directory |
| 61 | + const newTarget = target.replace("~", os.homedir) |
| 62 | + |
| 63 | + const targetFile = path.join(newTarget, repository.owner.login, repository.name, source); |
| 64 | + const targetPath = path.join(newTarget, repository.owner.login, repository.name, path.dirname(source)); |
| 65 | + |
| 66 | + if (!fs.existsSync(targetPath)) { |
| 67 | + fs.mkdirSync(targetPath, { recursive: true }); |
| 68 | + } |
| 69 | + |
| 70 | + fs.writeFileSync(targetFile, res.data) |
| 71 | + }).catch(error => { |
| 72 | + if (error.status === 404) { |
| 73 | + octokit.log.warn(`File ${source} not found`); |
| 74 | + return false; |
| 75 | + } |
| 76 | + |
| 77 | + throw error; |
| 78 | + }) |
| 79 | +} |
0 commit comments