Skip to content

Commit

Permalink
Merge pull request #15 from adRise/rename_option_name
Browse files Browse the repository at this point in the history
rename options and fix broken tests
  • Loading branch information
zhiyelee authored Dec 24, 2021
2 parents 798d0de + 1e31e71 commit 437fab6
Show file tree
Hide file tree
Showing 11 changed files with 468 additions and 32 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2018
},
"rules": {}
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/unit_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ jobs:
steps:
- uses: actions/checkout@v2
- run: npm install
- name: lint
run: yarn lint
- name: run unit test
run: yarn test
- name: Coveralls
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,22 @@ Default: true

The action will skip PRs that have failed checks.

### `sort`

**Optional**

What to sort results by. Can be either `created`, `updated`, `popularity` (comment count) or `long-running` (age, filtering by pulls updated in the last month).

Notice: this is an option provided by github rest api. In this github action, we simply proxy this parameter (and the `direction` paramter below). Check more [here](https://octokit.github.io/rest.js/v18#pulls-list)

### `direction`

**Optional**

The direction of the sort. Can be either `asc` or `desc`. Default: `desc` when sort is `created` or sort is not specified, otherwise `asc`.

This github action doesn't set any default parameters.

## Example usage

```yml
Expand All @@ -82,6 +98,8 @@ jobs:
base: 'master'
required_approval_count: 2
require_passed_checks: false
sort: 'created'
direction: 'desc'
```
Replace the `VERSION_YOU_WANT_TO_USE` with the actual version you want to use, check the version format [here](https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstepsuses)
Expand Down
6 changes: 3 additions & 3 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ inputs:
required: false
description: 'If the action should skip PRs that have failed checks, defaults to `true`'
default: 'true'
github_sort:
sort:
required: false
description: 'What to sort results by. Can be either `created`, `updated`, `popularity` (comment count) or `long-running` (age, filtering by pulls updated in the last month).'
github_sort_direction:
direction:
required: false
description: 'The direction of the github_sort. Can be either `asc` or `desc`. Default: `desc` when github_sort is created or github_sort is not specified, otherwise `asc`.'
description: 'The direction of the sort. Can be either `asc` or `desc`. Default: `desc` when `sort` is `created` or `sort` is not specified, otherwise `asc`.'

runs:
using: 'node12'
Expand Down
28 changes: 18 additions & 10 deletions dest/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5841,7 +5841,7 @@ var core = __nccwpck_require__(186);
// CONCATENATED MODULE: ./src/lib/github.js
const github_core = __nccwpck_require__(186);
const github = __nccwpck_require__(438);
const { log, printFailReason, wait } = __nccwpck_require__(103);
const { log, printFailReason, wait, isStringTrue } = __nccwpck_require__(103);

const getOctokit = () => {
const token = github_core.getInput('token');
Expand All @@ -5852,16 +5852,22 @@ const getOpenPRs = async () => {
const octokit = getOctokit();
const repo = github.context.repo;
const baseBranch = github_core.getInput('base');
const githubSort = github_core.getInput('github_sort').toLowerCase() || null;
const githubSortDirection =
github_core.getInput('github_sort_direction').toLowerCase() || null;
const sort = github_core.getInput('sort');
const sortDirection = github_core.getInput('direction');

let sortConfig = {};
if (sort) {
sortConfig = {
sort: sort.toLowerCase(),
direction: sortDirection ? sortDirection.toLowerCase() : undefined,
};
}

const { data } = await octokit.pulls.list({
...repo,
base: baseBranch,
state: 'open',
sort: githubSort,
direction: githubSortDirection,
...sortConfig,
});

return data;
Expand Down Expand Up @@ -5988,9 +5994,9 @@ const getApprovalStatus = async (pullNumber) => {
const getAutoUpdateCandidate = async (openPRs) => {
if (!openPRs) return null;

const requiredApprovalCount = github_core.getInput('required_approval_count');
const requirePassedChecks =
github_core.getInput('require_passed_checks').toUpperCase() === 'TRUE';
const requirePassedChecks = isStringTrue(
github_core.getInput('require_passed_checks'),
);

// only update `auto merge` enabled PRs
const autoMergeEnabledPRs = openPRs.filter((item) => item.auto_merge);
Expand Down Expand Up @@ -6099,12 +6105,14 @@ __nccwpck_require__.r(__webpack_exports__);
/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
/* harmony export */ "log": () => /* binding */ log,
/* harmony export */ "printFailReason": () => /* binding */ printFailReason,
/* harmony export */ "wait": () => /* binding */ wait
/* harmony export */ "wait": () => /* binding */ wait,
/* harmony export */ "isStringTrue": () => /* binding */ isStringTrue
/* harmony export */ });
const log = console.info.bind(null, 'LOG >');
const printFailReason = (pullNumber, reason) =>
log(`Won't update #${pullNumber}, the reason:\n > ${reason}`);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const isStringTrue = (str = '') => str.toLowerCase() === 'true';


/***/ }),
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "Automatically update PR branch",
"main": "dest/index.js",
"scripts": {
"lint": "eslint -c .eslintrc.json src",
"test": "jest src --coverage --verbose",
"jest-dev": "jest src --coverage --verbose --watch",
"build": "ncc build src/index.js -o dest"
Expand All @@ -19,6 +20,7 @@
"@babel/preset-env": "^7.12.13",
"@vercel/ncc": "^0.27.0",
"babel-jest": "^26.6.3",
"eslint": "^8.5.0",
"jest": "^26.6.3"
}
}
24 changes: 15 additions & 9 deletions src/lib/github.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const core = require('@actions/core');
const github = require('@actions/github');
const { log, printFailReason, wait } = require('./util');
const { log, printFailReason, wait, isStringTrue } = require('./util');

const getOctokit = () => {
const token = core.getInput('token');
Expand All @@ -11,16 +11,22 @@ export const getOpenPRs = async () => {
const octokit = getOctokit();
const repo = github.context.repo;
const baseBranch = core.getInput('base');
const githubSort = core.getInput('github_sort').toLowerCase() || null;
const githubSortDirection =
core.getInput('github_sort_direction').toLowerCase() || null;
const sort = core.getInput('sort');
const sortDirection = core.getInput('direction');

let sortConfig = {};
if (sort) {
sortConfig = {
sort: sort.toLowerCase(),
direction: sortDirection ? sortDirection.toLowerCase() : undefined,
};
}

const { data } = await octokit.pulls.list({
...repo,
base: baseBranch,
state: 'open',
sort: githubSort,
direction: githubSortDirection,
...sortConfig,
});

return data;
Expand Down Expand Up @@ -147,9 +153,9 @@ export const getApprovalStatus = async (pullNumber) => {
export const getAutoUpdateCandidate = async (openPRs) => {
if (!openPRs) return null;

const requiredApprovalCount = core.getInput('required_approval_count');
const requirePassedChecks =
core.getInput('require_passed_checks').toUpperCase() === 'TRUE';
const requirePassedChecks = isStringTrue(
core.getInput('require_passed_checks'),
);

// only update `auto merge` enabled PRs
const autoMergeEnabledPRs = openPRs.filter((item) => item.auto_merge);
Expand Down
41 changes: 37 additions & 4 deletions src/lib/github.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,18 @@ const utils = require('./util');

jest.mock('@actions/core');
jest.mock('@actions/github');
jest.mock('./util');
jest.mock('./util', () => {
const originalUtil = jest.requireActual('./util');
const mockList = ['log', 'printFailReason', 'wait'];
const mockedMethods = {};
Object.keys(originalUtil).forEach((methodName) => {
mockedMethods[methodName] = originalUtil[methodName];
if (mockList.includes(methodName)) {
mockedMethods[methodName] = jest.fn();
}
});
return mockedMethods;
});

const token = 'FAKE_TOKEN';
const base = 'FAKE_BASE';
Expand All @@ -16,7 +27,7 @@ const fakeEnv = {
token,
base,
required_approval_count: requiredApprovalCount,
require_passed_checks: 'true'
require_passed_checks: 'true',
};

const oldEnv = process.env;
Expand Down Expand Up @@ -112,6 +123,28 @@ describe('getOpenPRs()', () => {

expect(res).toEqual(mockedResponse.data);
});
test('should pass sort config if set', async () => {
process.env = {
...oldEnv,
...fakeEnv,
sort: 'updated',
direction: 'desc',
};
core.getInput.mockImplementation((name) => process.env[name]);

const mockedMethod = jest.fn().mockResolvedValue(mockedResponse);
github.getOctokit.mockReturnValue({
pulls: { list: mockedMethod },
});
await gitLib.getOpenPRs(pullNumber);

expect(mockedMethod).toHaveBeenCalledWith(
expect.objectContaining({
sort: 'updated',
direction: 'desc',
}),
);
});
});

describe('getMergeableStatus()', () => {
Expand Down Expand Up @@ -356,7 +389,7 @@ describe('getAutoUpdateCandidate()', () => {
expect(mockedGet).toHaveBeenCalledTimes(0);
expect(res).toBe(null);
});

test('PR with mergeable !== true will not be selected', async () => {
// has 2 approvals, not request for change review
const reviews = {
Expand Down Expand Up @@ -516,7 +549,7 @@ describe('getAutoUpdateCandidate()', () => {
const res = await gitLib.getAutoUpdateCandidate(prList);
expect(res).toBe(prList[0]);
});

test('Should return the first PR if it is all good', async () => {
// has 2 approvals, no request for change review
const reviews = {
Expand Down
1 change: 1 addition & 0 deletions src/lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export const log = console.info.bind(null, 'LOG >');
export const printFailReason = (pullNumber, reason) =>
log(`Won't update #${pullNumber}, the reason:\n > ${reason}`);
export const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export const isStringTrue = (str = '') => str.toLowerCase() === 'true';
14 changes: 14 additions & 0 deletions src/lib/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,17 @@ describe('log()', () => {
expect(console.info).toHaveBeenLastCalledWith('LOG >', msg);
});
});

describe('isStringTrue()', () => {
const isStringTrue = utils.isStringTrue;
test('should return the correct value based on the string', () => {
expect(isStringTrue('true')).toBe(true);
expect(isStringTrue('True')).toBe(true);
expect(isStringTrue('TRUE')).toBe(true);
expect(isStringTrue('tRue')).toBe(true);
expect(isStringTrue('false')).toBe(false);
expect(isStringTrue('False')).toBe(false);
expect(isStringTrue('FALSE')).toBe(false);
expect(isStringTrue('fAlse')).toBe(false);
});
});
Loading

0 comments on commit 437fab6

Please sign in to comment.