Skip to content

Commit

Permalink
Add PR label
Browse files Browse the repository at this point in the history
  • Loading branch information
sorenlouv committed Oct 29, 2017
1 parent dda4f25 commit ebb42f7
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 66 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"name": "Run file",
"program": "${file}"
},
{
Expand Down
16 changes: 10 additions & 6 deletions src/cli.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
const github = require('./github');
const { ensureConfigAndFoldersExists, validateConfig } = require('./configs');
const {
ensureConfigAndFoldersExists,
validateConfig,
getRepoConfig
} = require('./configs');
const {
promptRepoInfo,
promptCommit,
Expand All @@ -11,7 +15,7 @@ const {
} = require('./cliService');

function init(config, options) {
let commit, versions, reference, owner, repoName;
let commit, versions, reference, owner, repoName, repoConfig;

return ensureConfigAndFoldersExists()
.then(() => validateConfig(config))
Expand All @@ -20,14 +24,13 @@ function init(config, options) {
.then(({ owner: _owner, repoName: _repoName }) => {
owner = _owner;
repoName = _repoName;
repoConfig = getRepoConfig(owner, repoName, config.repositories);
})
.then(() =>
promptCommit(owner, repoName, options.own ? config.username : null)
)
.then(c => (commit = c))
.then(() =>
promptVersions(owner, repoName, config.repositories, options.multiple)
)
.then(() => promptVersions(repoConfig.versions, options.multiple))
.then(v => (versions = v))
.then(() => getReference(owner, repoName, commit.sha))
.then(ref => (reference = ref))
Expand All @@ -39,7 +42,8 @@ function init(config, options) {
commit,
reference,
versions,
username: config.username
username: config.username,
labels: repoConfig.labels
})
)
.catch(handleErrors);
Expand Down
75 changes: 38 additions & 37 deletions src/cliService.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,15 @@ const {
setupRepo
} = require('./git');

function sequentially(items, handler) {
return items.reduce(
(p, item) => p.then(() => handler(item)),
Promise.resolve()
);
}

const service = {};
service.doBackportVersions = ({
owner,
repoName,
commit,
reference,
versions,
username
username,
labels
}) => {
return sequentially(versions, version => {
return service
Expand All @@ -39,7 +33,8 @@ service.doBackportVersions = ({
commit,
reference,
version,
username
username,
labels
})
.then(res => console.log(`View pull request: ${res.data.html_url}\n`))
.catch(service.handleErrors);
Expand All @@ -52,13 +47,12 @@ service.doBackportVersion = ({
commit,
reference,
version,
username
username,
labels = []
}) => {
const backportBranchName = getBackportBranchName(version, reference);

console.log(
`Backporting ${service.getReferenceValue(reference)} to ${version}`
);
console.log(`Backporting ${getReferenceLong(reference)} to ${version}`);

return withSpinner(
resetAndPullMaster(owner, repoName).then(() =>
Expand All @@ -81,7 +75,14 @@ service.doBackportVersion = ({
username
);
return withSpinner(
github.createPullRequest(owner, repoName, payload),
github.createPullRequest(owner, repoName, payload).then(res => {
if (labels.length > 0) {
return github
.addLabels(owner, repoName, res.data.number, labels)
.then(() => res);
}
return res;
}),
'Creating pull request'
);
});
Expand Down Expand Up @@ -144,13 +145,7 @@ service.promptCommit = (owner, repoName, username) => {
.then(({ commit }) => commit);
};

service.promptVersions = (
owner,
repoName,
repositories,
multipleChoice = false
) => {
const versions = getVersions(owner, repoName, repositories);
service.promptVersions = (versions, multipleChoice = false) => {
if (multipleChoice) {
return prompts.checkboxVersions(versions).then(({ versions }) => versions);
}
Expand Down Expand Up @@ -207,15 +202,27 @@ service.handleErrors = e => {
}
};

service.getReferenceValue = reference => {
return reference.type === 'pullRequest'
? `pull request #${reference.value}`
: `commit ${reference.value}`;
};
function sequentially(items, handler) {
return items.reduce(
(p, item) => p.then(() => handler(item)),
Promise.resolve()
);
}

function getReferenceValue({ type, value }, { short }) {
if (type === 'pullRequest') {
return short ? `pr-${value}` : `pull request #${value}`;
}

function getVersions(owner, repoName, repositories) {
return repositories.find(repo => repo.name === `${owner}/${repoName}`)
.versions;
return short ? `commit-${value}` : `commit ${value}`;
}

function getReferenceLong(reference) {
return getReferenceValue(reference, { short: false });
}

function getReferenceShort(reference) {
return getReferenceValue(reference, { short: true });
}

function isCherrypickConflict(e) {
Expand Down Expand Up @@ -246,24 +253,18 @@ function cherrypickAndPrompt(owner, repoName, sha) {
}

function getBackportBranchName(version, reference) {
const refValue = getReferenceValueShort(reference);
const refValue = getReferenceShort(reference);
return `backport/${version}/${refValue}`;
}

function getReferenceValueShort(reference) {
return reference.type === 'pullRequest'
? `pr-${reference.value}`
: `commit-${reference.value}`;
}

function getCurrentFullRepoName(fullRepoNames, cwd) {
const currentDir = path.basename(cwd);
return fullRepoNames.find(name => name.endsWith(`/${currentDir}`));
}

function getPullRequestPayload(commitMessage, version, reference, username) {
const backportBranchName = getBackportBranchName(version, reference);
const refValue = service.getReferenceValue(reference);
const refValue = getReferenceLong(reference);

return {
title: `[${version}] ${commitMessage}`,
Expand Down
5 changes: 5 additions & 0 deletions src/configs.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ function ensureConfigAndFoldersExists() {
});
}

function getRepoConfig(owner, repoName, repositories) {
return repositories.find(repo => repo.name === `${owner}/${repoName}`);
}

function getConfigTemplate() {
return utils.readFile(path.join(__dirname, 'configTemplate.json'), 'utf8');
}
Expand Down Expand Up @@ -63,5 +67,6 @@ function getConfig() {
module.exports = {
ensureConfigAndFoldersExists,
getConfig,
getRepoConfig,
validateConfig
};
5 changes: 0 additions & 5 deletions src/git.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,11 @@ function resetAndPullMaster(owner, repoName) {
);
}

function getCommit(repo, sha) {
return repo.getCommit(sha);
}

module.exports = {
resetAndPullMaster,
cherrypick,
cloneRepo,
createAndCheckoutBranch,
getCommit,
repoExists,
setupRepo,
push
Expand Down
10 changes: 10 additions & 0 deletions src/github.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ function createPullRequest(owner, repoName, payload) {
.catch(throwGithubError);
}

function addLabels(owner, repoName, pullNumber, labels) {
return axios
.post(
`https://api.github.com/repos/${owner}/${repoName}/issues/${pullNumber}/labels?access_token=${accessToken}`,
labels
)
.catch(throwGithubError);
}

function getPullRequestByCommit(owner, repoName, commitSha) {
return axios(
`https://api.github.com/search/issues?q=repo:${owner}/${repoName}+${commitSha}&access_token=${accessToken}`
Expand All @@ -69,6 +78,7 @@ function setAccessToken(_accessToken) {

module.exports = {
setAccessToken,
addLabels,
createPullRequest,
getCommits,
getPullRequestByCommit
Expand Down
52 changes: 35 additions & 17 deletions test/cliService.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,37 +13,59 @@ describe('doBackportVersion', () => {
beforeEach(() => {
mockBackportDirPath();
utils.exec = jest.fn().mockReturnValue(Promise.resolve());
nock('https://api.github.com')
.post(`/repos/elastic/kibana/pulls`)

this.addLabelMock = nock('https://api.github.com')
.post(`/repos/elastic/kibana/issues/1337/labels`, ['backport'])
.query(true)
.reply(200, {});
});

it('with pull request reference', () => {
this.createPRMock = nock('https://api.github.com')
.post(`/repos/elastic/kibana/pulls`, {
title: '[6.x] myCommitMessage',
body: 'Backports pull request #myPullRequest to 6.x',
head: 'sqren:backport/6.x/pr-myPullRequest',
base: '6.x'
})
.query(true)
.reply(200, {
number: 1337,
html_url: 'myHtmlUrl'
});
});

it('with pull request reference', () => {
return cliService
.doBackportVersion({
owner: 'elastic',
repoName: 'kibana',
commit: { message: 'myCommitMessage' },
reference: { type: 'pullRequest', value: 'myPullRequest' },
version: '6.x',
username: 'sqren'
username: 'sqren',
labels: ['backport']
})
.then(res => {
expect(JSON.parse(res.config.data)).toEqual({
base: '6.x',
body: 'Backports pull request #myPullRequest to 6.x',
head: 'sqren:backport/6.x/pr-myPullRequest',
title: '[6.x] myCommitMessage'
});
expect(res.config).toMatchSnapshot();
expect(utils.exec.mock.calls).toMatchSnapshot();
expect(this.createPRMock.isDone()).toBe(true);
expect(this.addLabelMock.isDone()).toBe(true);
});
});

it('with commit reference', () => {
this.createPRMock = nock('https://api.github.com')
.post(`/repos/elastic/kibana/pulls`, {
title: '[6.x] myCommitMessage',
body: 'Backports commit myCommitSha to 6.x',
head: 'sqren:backport/6.x/commit-myCommitSha',
base: '6.x'
})
.query(true)
.reply(200, {
number: 1337,
html_url: 'myHtmlUrl'
});

return cliService
.doBackportVersion({
owner: 'elastic',
Expand All @@ -54,14 +76,10 @@ describe('doBackportVersion', () => {
username: 'sqren'
})
.then(res => {
expect(JSON.parse(res.config.data)).toEqual({
base: '6.x',
body: 'Backports commit myCommitSha to 6.x',
head: 'sqren:backport/6.x/commit-myCommitSha',
title: '[6.x] myCommitMessage'
});
expect(res.config).toMatchSnapshot();
expect(utils.exec.mock.calls).toMatchSnapshot();
expect(this.createPRMock.isDone()).toBe(true);
expect(this.addLabelMock.isDone()).toBe(false);
});
});
});
Expand Down

0 comments on commit ebb42f7

Please sign in to comment.