Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use GHA's token #310

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,5 @@ jobs:

- name: Run tests
run: npm test
env:
AUTH_GITHUB: ${{ github.token }}
2 changes: 1 addition & 1 deletion lib/flags.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const gitHubAuthFlag = {
'Follow https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token to create an API token. The API token needs access to public repositories.',
'',
'Then use the flag like this:',
chalk.greenBright(' --github-auth=my-user-name:abcdef01234567890')
chalk.greenBright(' --github-auth=github_pat_abcdef01234567890')
]
};

Expand Down
23 changes: 9 additions & 14 deletions lib/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,7 @@ try re-running it with ${chalk.cyan('--elmjson <path-to-elm.json>')}.`,

const forTests = args['FOR-TESTS'];

// eslint-disable-next-line unicorn/no-useless-undefined -- Bad TS type.
const {gitHubUser = undefined, gitHubPassword = undefined} = args[
'github-auth'
]
? parseGitHubAuth(subcommand, args['github-auth'])
: {};
const gitHubPat = parseGitHubAuth(subcommand, args['github-auth']);

const localElmReviewSrc = process.env.LOCAL_ELM_REVIEW_SRC;

Expand Down Expand Up @@ -324,9 +319,8 @@ try re-running it with ${chalk.cyan('--elmjson <path-to-elm.json>')}.`,
resultCachePath: (appHash) =>
path.join(elmStuffFolder(), 'result-cache', appHash),

// GitHub tokens
gitHubUser,
gitHubPassword
// GitHub token
gitHubPat
};
}

Expand Down Expand Up @@ -653,12 +647,14 @@ I recommend you try to gain network access and try again.`,

/**
* @param {Subcommand | null} subcommand
* @param {string} gitHubAuth
* @returns {{gitHubUser: string | undefined, gitHubPassword: string | undefined} | never}
* @param {string | undefined} gitHubAuth
* @returns {string | undefined | never}
*/
function parseGitHubAuth(subcommand, gitHubAuth) {
if (gitHubAuth === undefined) return;

const split = gitHubAuth.split(':');
if (split.length !== 2) {
if (split.length !== 2 && split.length !== 1) {
reportErrorAndExit(
new ErrorMessage.CustomError(
'INVALID FLAG ARGUMENT',
Expand All @@ -673,8 +669,7 @@ ${Flags.buildFlag(subcommand, Flags.gitHubAuthFlag)}`
);
}

const [gitHubUser, gitHubPassword] = split;
return {gitHubUser, gitHubPassword};
return split.length === 2 ? split[1] : split[0];
}

/**
Expand Down
50 changes: 31 additions & 19 deletions lib/remote-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,21 +197,31 @@ ${error.message}`
}
}

/** @type {ErrorMessageInfo} */
const rateLimitErrorMessage = {
title: 'GITHUB RATE LIMIT EXCEEDED',
message: `It looks like you exceeded the GitHub rate limit by using "--template" too many
times, this will likely last for 30 minutes.

In the meantime, you can use \`--github-auth your-github-username:your-api-token\`.
Follow this guide: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token to create an API token, and give it access to public repositories.
/**
* @param {boolean} hasPat
* @param {string} resetTime
* @returns {ErrorMessageInfo}
*/
function rateLimitErrorMessage(hasPat, resetTime) {
return {
title: 'GITHUB RATE LIMIT EXCEEDED',
message: `It looks like you exceeded the GitHub rate limit by using "--template" too many
times, this will likely last until ${resetTime}.
${
hasPat
? ''
: `
In the meantime, you can use \`--github-auth=your-api-token\`.
Follow this guide: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token to create an API token, and give it access to public repositories.`
}

To avoid this problem and to make the review process faster, consider setting up
elm-review in your project:

elm-review init
elm-review init --template <some-configuration>`
};
};
}

/**
* @param {string} repoName
Expand Down Expand Up @@ -358,12 +368,11 @@ async function downloadFile(url, dest) {
* @returns {Promise<unknown>}
*/
async function makeGitHubApiRequest(options, url, handleNotFound) {
/** @type {OptionsOfJSONResponseBody}} */
const parameters = {responseType: 'json'};
if (options.gitHubUser && options.gitHubPassword) {
parameters.username = options.gitHubUser;
parameters.password = options.gitHubPassword;
}
/** @type {OptionsOfJSONResponseBody} */
const parameters = {
responseType: 'json',
headers: {Authorization: `BEARER: ${options.gitHubPat}`}
};

Debug.log(`Making API request to GitHub: ${url}`);
try {
Expand All @@ -381,11 +390,14 @@ async function makeGitHubApiRequest(options, url, handleNotFound) {
Debug.log(`# body:\n${JSON.stringify(error.response.body, null, 4)}`);
if (error.name === 'HTTPError') {
switch (error.response.statusCode) {
case 429:
case 403: {
throw new ErrorMessage.CustomError(
rateLimitErrorMessage.title,
rateLimitErrorMessage.message
);
const hasPat = options.gitHubPat !== undefined;
const rateLimitReset = error.response.headers['x-ratelimit-reset'];
const resetTime = new Date(rateLimitReset * 1000).toLocaleString();
const {title, message} = rateLimitErrorMessage(hasPat, resetTime);

throw new ErrorMessage.CustomError(title, message);
}

case 404:
Expand Down
3 changes: 1 addition & 2 deletions lib/types/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ export type Options = OptionsBase & {
fileCachePath: () => Path;
resultCachePath: (appHash: AppHash) => Path;

gitHubUser: string | undefined;
gitHubPassword: string | undefined;
gitHubPat?: string | undefined;
};

export type ReviewOptions = Options & {
Expand Down
2 changes: 1 addition & 1 deletion test/flags.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ test('Running new-package --compiler without an argument', async () => {
});

test('Running --github-auth with a bad value', async () => {
const output = await TestCli.runAndExpectError('--github-auth=bad');
const output = await TestCli.runAndExpectError('--github-auth=::');
expect(output).toMatchFile(testName('github-auth-bad-argument'));
});

Expand Down
2 changes: 1 addition & 1 deletion test/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ replace_script() {
}

# If you get errors like rate limit exceeded, you can run these tests
# with "AUTH_GITHUB=gitHubUserName:token"
# with "AUTH_GITHUB=token"
# Follow this guide: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token
# to create an API token, and give it access to public repositories.
if [ -z "${AUTH_GITHUB:-}" ]
Expand Down
4 changes: 2 additions & 2 deletions test/snapshots/flags/github-auth-bad-argument.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
-- INVALID FLAG ARGUMENT -------------------------------------------------------

The value bad passed to --github-auth is not a valid one.
The value :: passed to --github-auth is not a valid one.

Here is the documentation for this flag:

Expand All @@ -9,5 +9,5 @@ Here is the documentation for this flag:
Follow https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token to create an API token. The API token needs access to public repositories.

Then use the flag like this:
--github-auth=my-user-name:abcdef01234567890
--github-auth=github_pat_abcdef01234567890

4 changes: 2 additions & 2 deletions turbo.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://turbo.build/schema.json",
"globalEnv": ["NO_COLOR", "LOCAL_ELM_REVIEW_SRC", "ELM_HOME"],
"globalPassThroughEnv": ["GITHUB_TOKEN", "AUTH_GITHUB"],
"globalEnv": ["NO_COLOR", "LOCAL_ELM_REVIEW_SRC"],
"globalPassThroughEnv": ["AUTH_GITHUB", "ELM_HOME"],
"tasks": {
"elm-format": {
"inputs": [
Expand Down
Loading