refactor: pass object to platform.initRepo

Also renames repoName to repository
This commit is contained in:
Rhys Arkins 2018-01-25 12:24:13 +01:00
parent 6fc2e52452
commit 9363fd8acf
11 changed files with 348 additions and 251 deletions

View file

@ -70,13 +70,13 @@ async function getRepos(token, endpoint) {
} }
// Initialize GitHub by getting base branch and SHA // Initialize GitHub by getting base branch and SHA
async function initRepo(repoName, token, endpoint, forkMode, forkToken) { async function initRepo({ repository, token, endpoint, forkMode, forkToken }) {
logger.debug(`initRepo("${repoName}")`); logger.debug(`initRepo("${repository}")`);
if (token) { if (token) {
logger.debug('Setting token in env for use by gh-got'); logger.debug('Setting token in env for use by gh-got');
process.env.GITHUB_TOKEN = token; process.env.GITHUB_TOKEN = token;
} else if (!process.env.GITHUB_TOKEN) { } else if (!process.env.GITHUB_TOKEN) {
throw new Error(`No token found for GitHub repository ${repoName}`); throw new Error(`No token found for GitHub repository ${repository}`);
} }
if (endpoint) { if (endpoint) {
logger.debug('Setting endpoint in env for use by gh-got'); logger.debug('Setting endpoint in env for use by gh-got');
@ -86,12 +86,12 @@ async function initRepo(repoName, token, endpoint, forkMode, forkToken) {
// config is used by the platform api itself, not necessary for the app layer to know // config is used by the platform api itself, not necessary for the app layer to know
config = {}; config = {};
get.reset(); get.reset();
config.repoName = repoName; config.repository = repository;
// platformConfig is passed back to the app layer and contains info about the platform they require // platformConfig is passed back to the app layer and contains info about the platform they require
const platformConfig = {}; const platformConfig = {};
let res; let res;
try { try {
res = await get(`repos/${repoName}`); res = await get(`repos/${repository}`);
logger.trace({ repositoryDetails: res.body }, 'Repository details'); logger.trace({ repositoryDetails: res.body }, 'Repository details');
if (res.body.archived) { if (res.body.archived) {
logger.info( logger.info(
@ -102,12 +102,12 @@ async function initRepo(repoName, token, endpoint, forkMode, forkToken) {
platformConfig.privateRepo = res.body.private === true; platformConfig.privateRepo = res.body.private === true;
platformConfig.isFork = res.body.fork === true; platformConfig.isFork = res.body.fork === true;
config.owner = res.body.owner.login; config.owner = res.body.owner.login;
logger.debug(`${repoName} owner = ${config.owner}`); logger.debug(`${repository} owner = ${config.owner}`);
// Use default branch as PR target unless later overridden. // Use default branch as PR target unless later overridden.
config.defaultBranch = res.body.default_branch; config.defaultBranch = res.body.default_branch;
// Base branch may be configured but defaultBranch is always fixed // Base branch may be configured but defaultBranch is always fixed
config.baseBranch = config.defaultBranch; config.baseBranch = config.defaultBranch;
logger.debug(`${repoName} default branch = ${config.baseBranch}`); logger.debug(`${repository} default branch = ${config.baseBranch}`);
// GitHub allows administrators to block certain types of merge, so we need to check it // GitHub allows administrators to block certain types of merge, so we need to check it
if (res.body.allow_rebase_merge) { if (res.body.allow_rebase_merge) {
config.mergeMethod = 'rebase'; config.mergeMethod = 'rebase';
@ -139,18 +139,21 @@ async function initRepo(repoName, token, endpoint, forkMode, forkToken) {
config.parentSha = await getBaseCommitSHA(); config.parentSha = await getBaseCommitSHA();
delete config.baseCommitSHA; delete config.baseCommitSHA;
// save parent name then delete // save parent name then delete
config.parentRepo = config.repoName; config.parentRepo = config.repository;
delete config.repoName; delete config.repository;
// Get list of existing repos // Get list of existing repos
const existingRepos = (await get('user/repos?per_page=100', { const existingRepos = (await get('user/repos?per_page=100', {
token: forkToken || process.env.GITHUB_TOKEN, token: forkToken || process.env.GITHUB_TOKEN,
paginate: true, paginate: true,
})).body.map(r => r.full_name); })).body.map(r => r.full_name);
config.repoName = (await get.post(`repos/${repoName}/forks`, { config.repository = (await get.post(`repos/${repository}/forks`, {
token: forkToken || process.env.GITHUB_TOKEN, token: forkToken || process.env.GITHUB_TOKEN,
})).body.full_name; })).body.full_name;
if (existingRepos.includes(config.repoName)) { if (existingRepos.includes(config.repository)) {
logger.info({ repository_fork: config.repoName }, 'Found existing fork'); logger.info(
{ repository_fork: config.repository },
'Found existing fork'
);
// Need to update base branch // Need to update base branch
logger.debug( logger.debug(
{ baseBranch: config.baseBranch, parentSha: config.parentSha }, { baseBranch: config.baseBranch, parentSha: config.parentSha },
@ -159,7 +162,7 @@ async function initRepo(repoName, token, endpoint, forkMode, forkToken) {
// This is a lovely "hack" by GitHub that lets us force update our fork's master // This is a lovely "hack" by GitHub that lets us force update our fork's master
// with the base commit from the parent repository // with the base commit from the parent repository
await get.patch( await get.patch(
`repos/${config.repoName}/git/refs/heads/${config.baseBranch}`, `repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
{ {
body: { body: {
sha: config.parentSha, sha: config.parentSha,
@ -168,7 +171,7 @@ async function initRepo(repoName, token, endpoint, forkMode, forkToken) {
} }
); );
} else { } else {
logger.info({ repository_fork: config.repoName }, 'Created fork'); logger.info({ repository_fork: config.repository }, 'Created fork');
// Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete // Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
await delay(30000); await delay(30000);
} }
@ -230,7 +233,7 @@ async function getBaseCommitSHA() {
async function getBranchProtection(branchName) { async function getBranchProtection(branchName) {
const res = await get( const res = await get(
`repos/${config.repoName}/branches/${branchName}/protection` `repos/${config.repository}/branches/${branchName}/protection`
); );
return res.body; return res.body;
} }
@ -254,11 +257,11 @@ async function getFileList(branchName = config.baseBranch) {
} }
try { try {
const res = await get( const res = await get(
`repos/${config.repoName}/git/trees/${branchName}?recursive=true` `repos/${config.repository}/git/trees/${branchName}?recursive=true`
); );
if (res.body.truncated) { if (res.body.truncated) {
logger.warn( logger.warn(
{ repository: config.repoName }, { repository: config.repository },
'repository tree is truncated' 'repository tree is truncated'
); );
} }
@ -272,7 +275,7 @@ async function getFileList(branchName = config.baseBranch) {
throw new Error('uninitiated'); throw new Error('uninitiated');
} }
logger.info( logger.info(
{ repository: config.repoName }, { repository: config.repository },
'Error retrieving git tree - no files detected' 'Error retrieving git tree - no files detected'
); );
config.fileList = []; config.fileList = [];
@ -287,7 +290,7 @@ async function getFileList(branchName = config.baseBranch) {
async function branchExists(branchName) { async function branchExists(branchName) {
logger.debug(`branchExists(${branchName})`); logger.debug(`branchExists(${branchName})`);
const branchList = (await get( const branchList = (await get(
`repos/${config.repoName}/branches?per_page=100`, `repos/${config.repository}/branches?per_page=100`,
{ paginate: true } { paginate: true }
)).body.map(branch => branch.name); )).body.map(branch => branch.name);
return branchList.includes(branchName); return branchList.includes(branchName);
@ -295,7 +298,7 @@ async function branchExists(branchName) {
async function getAllRenovateBranches(branchPrefix) { async function getAllRenovateBranches(branchPrefix) {
logger.trace('getAllRenovateBranches'); logger.trace('getAllRenovateBranches');
const allBranches = (await get(`repos/${config.repoName}/git/refs/heads`)) const allBranches = (await get(`repos/${config.repository}/git/refs/heads`))
.body; .body;
return allBranches.reduce((arr, branch) => { return allBranches.reduce((arr, branch) => {
if (branch.ref.indexOf(`refs/heads/${branchPrefix}`) === 0) { if (branch.ref.indexOf(`refs/heads/${branchPrefix}`) === 0) {
@ -340,7 +343,7 @@ async function getBranchStatus(branchName, requiredStatusChecks) {
logger.warn({ requiredStatusChecks }, `Unsupported requiredStatusChecks`); logger.warn({ requiredStatusChecks }, `Unsupported requiredStatusChecks`);
return 'failed'; return 'failed';
} }
const gotString = `repos/${config.repoName}/commits/${branchName}/status`; const gotString = `repos/${config.repository}/commits/${branchName}/status`;
const res = await get(gotString); const res = await get(gotString);
logger.debug( logger.debug(
{ state: res.body.stage, statuses: res.body.statuses }, { state: res.body.stage, statuses: res.body.statuses },
@ -351,7 +354,7 @@ async function getBranchStatus(branchName, requiredStatusChecks) {
async function getBranchStatusCheck(branchName, context) { async function getBranchStatusCheck(branchName, context) {
const branchCommit = await getBranchCommit(branchName); const branchCommit = await getBranchCommit(branchName);
const url = `repos/${config.repoName}/commits/${branchCommit}/statuses`; const url = `repos/${config.repository}/commits/${branchCommit}/statuses`;
const res = await get(url); const res = await get(url);
for (const check of res.body) { for (const check of res.body) {
if (check.context === context) { if (check.context === context) {
@ -369,7 +372,7 @@ async function setBranchStatus(
targetUrl targetUrl
) { ) {
const branchCommit = await getBranchCommit(branchName); const branchCommit = await getBranchCommit(branchName);
const url = `repos/${config.repoName}/statuses/${branchCommit}`; const url = `repos/${config.repository}/statuses/${branchCommit}`;
const options = { const options = {
state, state,
description, description,
@ -384,7 +387,7 @@ async function setBranchStatus(
async function deleteBranch(branchName) { async function deleteBranch(branchName) {
const options = config.forkToken ? { token: config.forkToken } : undefined; const options = config.forkToken ? { token: config.forkToken } : undefined;
await get.delete( await get.delete(
`repos/${config.repoName}/git/refs/heads/${branchName}`, `repos/${config.repository}/git/refs/heads/${branchName}`,
options options
); );
} }
@ -399,7 +402,9 @@ async function mergeBranch(branchName, mergeType) {
); );
} }
if (mergeType === 'branch-push') { if (mergeType === 'branch-push') {
const url = `repos/${config.repoName}/git/refs/heads/${config.baseBranch}`; const url = `repos/${config.repository}/git/refs/heads/${
config.baseBranch
}`;
const options = { const options = {
body: { body: {
sha: await getBranchCommit(branchName), sha: await getBranchCommit(branchName),
@ -412,7 +417,7 @@ async function mergeBranch(branchName, mergeType) {
throw new Error('branch-push failed'); throw new Error('branch-push failed');
} }
} else if (mergeType === 'branch-merge-commit') { } else if (mergeType === 'branch-merge-commit') {
const url = `repos/${config.repoName}/merges`; const url = `repos/${config.repository}/merges`;
const options = { const options = {
body: { body: {
base: config.baseBranch, base: config.baseBranch,
@ -436,7 +441,9 @@ async function mergeBranch(branchName, mergeType) {
async function getBranchLastCommitTime(branchName) { async function getBranchLastCommitTime(branchName) {
try { try {
const res = await get(`repos/${config.repoName}/commits?sha=${branchName}`); const res = await get(
`repos/${config.repository}/commits?sha=${branchName}`
);
return new Date(res.body[0].commit.committer.date); return new Date(res.body[0].commit.committer.date);
} catch (err) { } catch (err) {
logger.error({ err }, `getBranchLastCommitTime error`); logger.error({ err }, `getBranchLastCommitTime error`);
@ -450,7 +457,7 @@ async function getIssueList() {
if (!config.issueList) { if (!config.issueList) {
config.issueList = (await get( config.issueList = (await get(
`repos/${config.parentRepo || `repos/${config.parentRepo ||
config.repoName}/issues?filter=created&state=open` config.repository}/issues?filter=created&state=open`
)).body.map(i => ({ )).body.map(i => ({
number: i.number, number: i.number,
title: i.title, title: i.title,
@ -465,12 +472,14 @@ async function ensureIssue(title, body) {
const issue = issueList.find(i => i.title === title); const issue = issueList.find(i => i.title === title);
if (issue) { if (issue) {
const issueBody = (await get( const issueBody = (await get(
`repos/${config.parentRepo || config.repoName}/issues/${issue.number}` `repos/${config.parentRepo || config.repository}/issues/${issue.number}`
)).body.body; )).body.body;
if (issueBody !== body) { if (issueBody !== body) {
logger.debug('Updating issue body'); logger.debug('Updating issue body');
await get.patch( await get.patch(
`repos/${config.parentRepo || config.repoName}/issues/${issue.number}`, `repos/${config.parentRepo || config.repository}/issues/${
issue.number
}`,
{ {
body: { body }, body: { body },
} }
@ -478,7 +487,7 @@ async function ensureIssue(title, body) {
return 'updated'; return 'updated';
} }
} else { } else {
await get.post(`repos/${config.parentRepo || config.repoName}/issues`, { await get.post(`repos/${config.parentRepo || config.repository}/issues`, {
body: { body: {
title, title,
body, body,
@ -496,7 +505,9 @@ async function ensureIssueClosing(title) {
if (issue.title === title) { if (issue.title === title) {
logger.info({ issue }, 'Closing issue'); logger.info({ issue }, 'Closing issue');
await get.patch( await get.patch(
`repos/${config.parentRepo || config.repoName}/issues/${issue.number}`, `repos/${config.parentRepo || config.repository}/issues/${
issue.number
}`,
{ {
body: { state: 'closed' }, body: { state: 'closed' },
} }
@ -507,7 +518,7 @@ async function ensureIssueClosing(title) {
async function addAssignees(issueNo, assignees) { async function addAssignees(issueNo, assignees) {
logger.debug(`Adding assignees ${assignees} to #${issueNo}`); logger.debug(`Adding assignees ${assignees} to #${issueNo}`);
await get.post(`repos/${config.repoName}/issues/${issueNo}/assignees`, { await get.post(`repos/${config.repository}/issues/${issueNo}/assignees`, {
body: { body: {
assignees, assignees,
}, },
@ -518,7 +529,7 @@ async function addReviewers(prNo, reviewers) {
logger.debug(`Adding reviewers ${reviewers} to #${prNo}`); logger.debug(`Adding reviewers ${reviewers} to #${prNo}`);
const res = await get.post( const res = await get.post(
`repos/${config.parentRepo || `repos/${config.parentRepo ||
config.repoName}/pulls/${prNo}/requested_reviewers`, config.repository}/pulls/${prNo}/requested_reviewers`,
{ {
body: { body: {
reviewers, reviewers,
@ -531,7 +542,7 @@ async function addReviewers(prNo, reviewers) {
async function addLabels(issueNo, labels) { async function addLabels(issueNo, labels) {
logger.debug(`Adding labels ${labels} to #${issueNo}`); logger.debug(`Adding labels ${labels} to #${issueNo}`);
if (Array.isArray(labels) && labels.length) { if (Array.isArray(labels) && labels.length) {
await get.post(`repos/${config.repoName}/issues/${issueNo}/labels`, { await get.post(`repos/${config.repository}/issues/${issueNo}/labels`, {
body: labels, body: labels,
}); });
} }
@ -541,7 +552,7 @@ async function getComments(issueNo) {
// GET /repos/:owner/:repo/issues/:number/comments // GET /repos/:owner/:repo/issues/:number/comments
logger.debug(`Getting comments for #${issueNo}`); logger.debug(`Getting comments for #${issueNo}`);
const url = `repos/${config.parentRepo || const url = `repos/${config.parentRepo ||
config.repoName}/issues/${issueNo}/comments?per_page=100`; config.repository}/issues/${issueNo}/comments?per_page=100`;
const comments = (await get(url, { paginate: true })).body; const comments = (await get(url, { paginate: true })).body;
logger.debug(`Found ${comments.length} comments`); logger.debug(`Found ${comments.length} comments`);
return comments; return comments;
@ -550,7 +561,8 @@ async function getComments(issueNo) {
async function addComment(issueNo, body) { async function addComment(issueNo, body) {
// POST /repos/:owner/:repo/issues/:number/comments // POST /repos/:owner/:repo/issues/:number/comments
await get.post( await get.post(
`repos/${config.parentRepo || config.repoName}/issues/${issueNo}/comments`, `repos/${config.parentRepo ||
config.repository}/issues/${issueNo}/comments`,
{ {
body: { body }, body: { body },
} }
@ -561,7 +573,7 @@ async function editComment(commentId, body) {
// PATCH /repos/:owner/:repo/issues/comments/:id // PATCH /repos/:owner/:repo/issues/comments/:id
await get.patch( await get.patch(
`repos/${config.parentRepo || `repos/${config.parentRepo ||
config.repoName}/issues/comments/${commentId}`, config.repository}/issues/comments/${commentId}`,
{ {
body: { body }, body: { body },
} }
@ -571,7 +583,8 @@ async function editComment(commentId, body) {
async function deleteComment(commentId) { async function deleteComment(commentId) {
// DELETE /repos/:owner/:repo/issues/comments/:id // DELETE /repos/:owner/:repo/issues/comments/:id
await get.delete( await get.delete(
`repos/${config.parentRepo || config.repoName}/issues/comments/${commentId}` `repos/${config.parentRepo ||
config.repository}/issues/comments/${commentId}`
); );
} }
@ -589,10 +602,10 @@ async function ensureComment(issueNo, topic, content) {
}); });
if (!commentId) { if (!commentId) {
await addComment(issueNo, body); await addComment(issueNo, body);
logger.info({ repository: config.repoName, issueNo }, 'Added comment'); logger.info({ repository: config.repository, issueNo }, 'Added comment');
} else if (commentNeedsUpdating) { } else if (commentNeedsUpdating) {
await editComment(commentId, body); await editComment(commentId, body);
logger.info({ repository: config.repoName, issueNo }, 'Updated comment'); logger.info({ repository: config.repository, issueNo }, 'Updated comment');
} else { } else {
logger.debug('Comment is already update-to-date'); logger.debug('Comment is already update-to-date');
} }
@ -620,7 +633,7 @@ async function getPrList() {
logger.debug('Retrieving PR list'); logger.debug('Retrieving PR list');
const res = await get( const res = await get(
`repos/${config.parentRepo || `repos/${config.parentRepo ||
config.repoName}/pulls?per_page=100&state=all`, config.repository}/pulls?per_page=100&state=all`,
{ paginate: true } { paginate: true }
); );
config.prList = res.body.map(pr => ({ config.prList = res.body.map(pr => ({
@ -668,7 +681,7 @@ async function findPr(branchName, prTitle, state = 'all') {
async function createPr(branchName, title, body, labels, useDefaultBranch) { async function createPr(branchName, title, body, labels, useDefaultBranch) {
const base = useDefaultBranch ? config.defaultBranch : config.baseBranch; const base = useDefaultBranch ? config.defaultBranch : config.baseBranch;
// Include the repository owner to handle forkMode and regular mode // Include the repository owner to handle forkMode and regular mode
const head = `${config.repoName.split('/')[0]}:${branchName}`; const head = `${config.repository.split('/')[0]}:${branchName}`;
const options = { const options = {
body: { body: {
title, title,
@ -683,7 +696,7 @@ async function createPr(branchName, title, body, labels, useDefaultBranch) {
} }
logger.debug({ title, head, base }, 'Creating PR'); logger.debug({ title, head, base }, 'Creating PR');
const pr = (await get.post( const pr = (await get.post(
`repos/${config.parentRepo || config.repoName}/pulls`, `repos/${config.parentRepo || config.repository}/pulls`,
options options
)).body; )).body;
pr.displayNumber = `Pull Request #${pr.number}`; pr.displayNumber = `Pull Request #${pr.number}`;
@ -697,7 +710,7 @@ async function getPr(prNo) {
return null; return null;
} }
const pr = (await get( const pr = (await get(
`repos/${config.parentRepo || config.repoName}/pulls/${prNo}` `repos/${config.parentRepo || config.repository}/pulls/${prNo}`
)).body; )).body;
if (!pr) { if (!pr) {
return null; return null;
@ -717,7 +730,7 @@ async function getPr(prNo) {
// Check if only one author of all commits // Check if only one author of all commits
logger.debug('Checking all commits'); logger.debug('Checking all commits');
const prCommits = (await get( const prCommits = (await get(
`repos/${config.parentRepo || config.repoName}/pulls/${prNo}/commits` `repos/${config.parentRepo || config.repository}/pulls/${prNo}/commits`
)).body; )).body;
// Remove first commit - it should be Renovate // Remove first commit - it should be Renovate
prCommits.shift(); prCommits.shift();
@ -759,7 +772,7 @@ async function getPrFiles(prNo) {
return []; return [];
} }
const files = (await get( const files = (await get(
`repos/${config.parentRepo || config.repoName}/pulls/${prNo}/files` `repos/${config.parentRepo || config.repository}/pulls/${prNo}/files`
)).body; )).body;
return files.map(f => f.filename); return files.map(f => f.filename);
} }
@ -778,7 +791,7 @@ async function updatePr(prNo, title, body) {
options.token = config.forkToken; options.token = config.forkToken;
} }
await get.patch( await get.patch(
`repos/${config.parentRepo || config.repoName}/pulls/${prNo}`, `repos/${config.parentRepo || config.repository}/pulls/${prNo}`,
options options
); );
} }
@ -800,7 +813,7 @@ async function mergePr(prNo, branchName) {
); );
} }
const url = `repos/${config.parentRepo || const url = `repos/${config.parentRepo ||
config.repoName}/pulls/${prNo}/merge`; config.repository}/pulls/${prNo}/merge`;
const options = { const options = {
body: {}, body: {},
}; };
@ -871,7 +884,7 @@ async function getFile(filePath, branchName) {
let res; let res;
try { try {
res = await get( res = await get(
`repos/${config.repoName}/contents/${filePath}?ref=${branchName || `repos/${config.repository}/contents/${filePath}?ref=${branchName ||
config.baseBranch}` config.baseBranch}`
); );
} catch (error) { } catch (error) {
@ -885,7 +898,7 @@ async function getFile(filePath, branchName) {
error.message.startsWith('This API returns blobs up to 1 MB in size') error.message.startsWith('This API returns blobs up to 1 MB in size')
) { ) {
logger.info('Large file'); logger.info('Large file');
let treeUrl = `repos/${config.repoName}/git/trees/${config.baseBranch}`; let treeUrl = `repos/${config.repository}/git/trees/${config.baseBranch}`;
const parentPath = path.dirname(filePath); const parentPath = path.dirname(filePath);
if (parentPath !== '.') { if (parentPath !== '.') {
treeUrl += `.${parentPath}`; treeUrl += `.${parentPath}`;
@ -901,7 +914,7 @@ async function getFile(filePath, branchName) {
logger.warn('Could not locate file blob'); logger.warn('Could not locate file blob');
throw error; throw error;
} }
res = await get(`repos/${config.repoName}/git/blobs/${fileSha}`); res = await get(`repos/${config.repository}/git/blobs/${fileSha}`);
} else { } else {
// Propagate if it's any other error // Propagate if it's any other error
throw error; throw error;
@ -967,7 +980,7 @@ async function createBranch(branchName, sha) {
if (config.forkToken) { if (config.forkToken) {
options.token = config.forkToken; options.token = config.forkToken;
} }
await get.post(`repos/${config.repoName}/git/refs`, options); await get.post(`repos/${config.repository}/git/refs`, options);
} }
// Internal: Updates an existing branch to new commit sha // Internal: Updates an existing branch to new commit sha
@ -984,7 +997,7 @@ async function updateBranch(branchName, commit) {
options.token = config.forkToken; options.token = config.forkToken;
} }
await get.patch( await get.patch(
`repos/${config.repoName}/git/refs/heads/${branchName}`, `repos/${config.repository}/git/refs/heads/${branchName}`,
options options
); );
} }
@ -1004,29 +1017,29 @@ async function createBlob(fileContents) {
if (config.forkToken) { if (config.forkToken) {
options.token = config.forkToken; options.token = config.forkToken;
} }
return (await get.post(`repos/${config.repoName}/git/blobs`, options)).body return (await get.post(`repos/${config.repository}/git/blobs`, options)).body
.sha; .sha;
} }
// Return the commit SHA for a branch // Return the commit SHA for a branch
async function getBranchCommit(branchName) { async function getBranchCommit(branchName) {
const res = await get( const res = await get(
`repos/${config.repoName}/git/refs/heads/${branchName}` `repos/${config.repository}/git/refs/heads/${branchName}`
); );
return res.body.object.sha; return res.body.object.sha;
} }
async function getCommitDetails(commit) { async function getCommitDetails(commit) {
logger.debug(`getCommitDetails(${commit})`); logger.debug(`getCommitDetails(${commit})`);
const results = await get(`repos/${config.repoName}/git/commits/${commit}`); const results = await get(`repos/${config.repository}/git/commits/${commit}`);
return results.body; return results.body;
} }
// Return the tree SHA for a commit // Return the tree SHA for a commit
async function getCommitTree(commit) { async function getCommitTree(commit) {
logger.debug(`getCommitTree(${commit})`); logger.debug(`getCommitTree(${commit})`);
return (await get(`repos/${config.repoName}/git/commits/${commit}`)).body.tree return (await get(`repos/${config.repository}/git/commits/${commit}`)).body
.sha; .tree.sha;
} }
// Create a tree and return SHA // Create a tree and return SHA
@ -1050,7 +1063,7 @@ async function createTree(baseTree, files) {
if (config.forkToken) { if (config.forkToken) {
options.token = config.forkToken; options.token = config.forkToken;
} }
return (await get.post(`repos/${config.repoName}/git/trees`, options)).body return (await get.post(`repos/${config.repository}/git/trees`, options)).body
.sha; .sha;
} }
@ -1104,14 +1117,14 @@ async function createCommit(parent, tree, message, gitAuthor, gitPrivateKey) {
if (config.forkToken) { if (config.forkToken) {
options.token = config.forkToken; options.token = config.forkToken;
} }
return (await get.post(`repos/${config.repoName}/git/commits`, options)).body return (await get.post(`repos/${config.repository}/git/commits`, options))
.sha; .body.sha;
} }
async function getCommitMessages() { async function getCommitMessages() {
logger.debug('getCommitMessages'); logger.debug('getCommitMessages');
try { try {
const res = await get(`repos/${config.repoName}/commits`); const res = await get(`repos/${config.repository}/commits`);
return res.body.map(commit => commit.commit.message); return res.body.map(commit => commit.commit.message);
} catch (err) { } catch (err) {
logger.error({ err }, `getCommitMessages error`); logger.error({ err }, `getCommitMessages error`);

View file

@ -6,14 +6,14 @@ module.exports = {
}; };
async function createFile( async function createFile(
repoName, repository,
branchName, branchName,
filePath, filePath,
fileContents, fileContents,
message message
) { ) {
const opts = {}; const opts = {};
const url = `projects/${repoName}/repository/files/${filePath.replace( const url = `projects/${repository}/repository/files/${filePath.replace(
/\//g, /\//g,
'%2F' '%2F'
)}`; )}`;
@ -27,14 +27,14 @@ async function createFile(
} }
async function updateFile( async function updateFile(
repoName, repository,
branchName, branchName,
filePath, filePath,
fileContents, fileContents,
message message
) { ) {
const opts = {}; const opts = {};
const url = `projects/${repoName}/repository/files/${filePath.replace( const url = `projects/${repository}/repository/files/${filePath.replace(
/\//g, /\//g,
'%2F' '%2F'
)}`; )}`;

View file

@ -72,12 +72,11 @@ function urlEscape(str) {
} }
// Initialize GitLab by getting base branch // Initialize GitLab by getting base branch
async function initRepo(repoName, token, endpoint) { async function initRepo({ repository, token, endpoint }) {
logger.debug(`initRepo(${repoName})`);
if (token) { if (token) {
process.env.GITLAB_TOKEN = token; process.env.GITLAB_TOKEN = token;
} else if (!process.env.GITLAB_TOKEN) { } else if (!process.env.GITLAB_TOKEN) {
throw new Error(`No token found for GitLab repository ${repoName}`); throw new Error(`No token found for GitLab repository ${repository}`);
} }
if (token) { if (token) {
process.env.GITLAB_TOKEN = token; process.env.GITLAB_TOKEN = token;
@ -87,12 +86,12 @@ async function initRepo(repoName, token, endpoint) {
} }
config = {}; config = {};
get.reset(); get.reset();
config.repoName = urlEscape(repoName); config.repository = urlEscape(repository);
try { try {
const res = await get(`projects/${config.repoName}`); const res = await get(`projects/${config.repository}`);
config.defaultBranch = res.body.default_branch; config.defaultBranch = res.body.default_branch;
config.baseBranch = config.defaultBranch; config.baseBranch = config.defaultBranch;
logger.debug(`${repoName} default branch = ${config.baseBranch}`); logger.debug(`${repository} default branch = ${config.baseBranch}`);
// Discover our user email // Discover our user email
config.email = (await get(`user`)).body.email; config.email = (await get(`user`)).body.email;
delete config.prList; delete config.prList;
@ -125,7 +124,7 @@ async function getFileList(branchName = config.baseBranch) {
try { try {
const res = await get( const res = await get(
`projects/${ `projects/${
config.repoName config.repository
}/repository/tree?ref=${branchName}&recursive=true&per_page=100`, }/repository/tree?ref=${branchName}&recursive=true&per_page=100`,
{ paginate: true } { paginate: true }
); );
@ -146,7 +145,7 @@ async function getFileList(branchName = config.baseBranch) {
async function branchExists(branchName) { async function branchExists(branchName) {
logger.debug(`Checking if branch exists: ${branchName}`); logger.debug(`Checking if branch exists: ${branchName}`);
try { try {
const url = `projects/${config.repoName}/repository/branches/${urlEscape( const url = `projects/${config.repository}/repository/branches/${urlEscape(
branchName branchName
)}`; )}`;
const res = await get(url); const res = await get(url);
@ -182,7 +181,7 @@ function isBranchStale() {
async function getBranchPr(branchName) { async function getBranchPr(branchName) {
logger.debug(`getBranchPr(${branchName})`); logger.debug(`getBranchPr(${branchName})`);
const urlString = `projects/${ const urlString = `projects/${
config.repoName config.repository
}/merge_requests?state=opened&per_page=100`; }/merge_requests?state=opened&per_page=100`;
const res = await get(urlString, { paginate: true }); const res = await get(urlString, { paginate: true });
logger.debug(`Got res with ${res.body.length} results`); logger.debug(`Got res with ${res.body.length} results`);
@ -211,13 +210,15 @@ async function getBranchStatus(branchName, requiredStatusChecks) {
return 'failed'; return 'failed';
} }
// First, get the branch to find the commit SHA // First, get the branch to find the commit SHA
let url = `projects/${config.repoName}/repository/branches/${urlEscape( let url = `projects/${config.repository}/repository/branches/${urlEscape(
branchName branchName
)}`; )}`;
let res = await get(url); let res = await get(url);
const branchSha = res.body.commit.id; const branchSha = res.body.commit.id;
// Now, check the statuses for that commit // Now, check the statuses for that commit
url = `projects/${config.repoName}/repository/commits/${branchSha}/statuses`; url = `projects/${
config.repository
}/repository/commits/${branchSha}/statuses`;
res = await get(url); res = await get(url);
logger.debug(`Got res with ${res.body.length} results`); logger.debug(`Got res with ${res.body.length} results`);
if (res.body.length === 0) { if (res.body.length === 0) {
@ -241,13 +242,15 @@ async function getBranchStatus(branchName, requiredStatusChecks) {
async function getBranchStatusCheck(branchName, context) { async function getBranchStatusCheck(branchName, context) {
// First, get the branch to find the commit SHA // First, get the branch to find the commit SHA
let url = `projects/${config.repoName}/repository/branches/${urlEscape( let url = `projects/${config.repository}/repository/branches/${urlEscape(
branchName branchName
)}`; )}`;
let res = await get(url); let res = await get(url);
const branchSha = res.body.commit.id; const branchSha = res.body.commit.id;
// Now, check the statuses for that commit // Now, check the statuses for that commit
url = `projects/${config.repoName}/repository/commits/${branchSha}/statuses`; url = `projects/${
config.repository
}/repository/commits/${branchSha}/statuses`;
res = await get(url); res = await get(url);
logger.debug(`Got res with ${res.body.length} results`); logger.debug(`Got res with ${res.body.length} results`);
for (const check of res.body) { for (const check of res.body) {
@ -266,13 +269,13 @@ async function setBranchStatus(
targetUrl targetUrl
) { ) {
// First, get the branch to find the commit SHA // First, get the branch to find the commit SHA
let url = `projects/${config.repoName}/repository/branches/${urlEscape( let url = `projects/${config.repository}/repository/branches/${urlEscape(
branchName branchName
)}`; )}`;
const res = await get(url); const res = await get(url);
const branchSha = res.body.commit.id; const branchSha = res.body.commit.id;
// Now, check the statuses for that commit // Now, check the statuses for that commit
url = `projects/${config.repoName}/statuses/${branchSha}`; url = `projects/${config.repository}/statuses/${branchSha}`;
const options = { const options = {
state, state,
description, description,
@ -286,7 +289,7 @@ async function setBranchStatus(
async function deleteBranch(branchName) { async function deleteBranch(branchName) {
await get.delete( await get.delete(
`projects/${config.repoName}/repository/branches/${urlEscape(branchName)}` `projects/${config.repository}/repository/branches/${urlEscape(branchName)}`
); );
} }
@ -297,7 +300,7 @@ function mergeBranch() {
async function getBranchLastCommitTime(branchName) { async function getBranchLastCommitTime(branchName) {
try { try {
const res = await get( const res = await get(
`projects/${config.repoName}/repository/commits?ref_name=${urlEscape( `projects/${config.repository}/repository/commits?ref_name=${urlEscape(
branchName branchName
)}` )}`
); );
@ -324,7 +327,7 @@ async function addAssignees(iid, assignees) {
} }
try { try {
const assigneeId = (await get(`users?username=${assignees[0]}`)).body[0].id; const assigneeId = (await get(`users?username=${assignees[0]}`)).body[0].id;
let url = `projects/${config.repoName}/merge_requests/${iid}`; let url = `projects/${config.repository}/merge_requests/${iid}`;
url += `?assignee_id=${assigneeId}`; url += `?assignee_id=${assigneeId}`;
await get.put(url); await get.put(url);
} catch (err) { } catch (err) {
@ -347,7 +350,9 @@ async function ensureCommentRemoval() {
async function getPrList() { async function getPrList() {
if (!config.prList) { if (!config.prList) {
const urlString = `projects/${config.repoName}/merge_requests?per_page=100`; const urlString = `projects/${
config.repository
}/merge_requests?per_page=100`;
const res = await get(urlString, { paginate: true }); const res = await get(urlString, { paginate: true });
config.prList = res.body.map(pr => ({ config.prList = res.body.map(pr => ({
number: pr.iid, number: pr.iid,
@ -394,7 +399,7 @@ async function createPr(
? config.defaultBranch ? config.defaultBranch
: config.baseBranch; : config.baseBranch;
logger.debug(`Creating Merge Request: ${title}`); logger.debug(`Creating Merge Request: ${title}`);
const res = await get.post(`projects/${config.repoName}/merge_requests`, { const res = await get.post(`projects/${config.repository}/merge_requests`, {
body: { body: {
source_branch: branchName, source_branch: branchName,
target_branch: targetBranch, target_branch: targetBranch,
@ -412,7 +417,7 @@ async function createPr(
async function getPr(iid) { async function getPr(iid) {
logger.debug(`getPr(${iid})`); logger.debug(`getPr(${iid})`);
const url = `projects/${config.repoName}/merge_requests/${iid}`; const url = `projects/${config.repository}/merge_requests/${iid}`;
const pr = (await get(url)).body; const pr = (await get(url)).body;
// Harmonize fields with GitHub // Harmonize fields with GitHub
pr.number = pr.iid; pr.number = pr.iid;
@ -425,7 +430,7 @@ async function getPr(iid) {
// Check if the most recent branch commit is by us // Check if the most recent branch commit is by us
// If not then we don't allow it to be rebased, in case someone's changes would be lost // If not then we don't allow it to be rebased, in case someone's changes would be lost
const branchUrl = `projects/${ const branchUrl = `projects/${
config.repoName config.repository
}/repository/branches/${urlEscape(pr.source_branch)}`; }/repository/branches/${urlEscape(pr.source_branch)}`;
const branch = (await get(branchUrl)).body; const branch = (await get(branchUrl)).body;
if (branch && branch.commit && branch.commit.author_email === config.email) { if (branch && branch.commit && branch.commit.author_email === config.email) {
@ -440,7 +445,7 @@ function getPrFiles() {
} }
async function updatePr(iid, title, description) { async function updatePr(iid, title, description) {
await get.put(`projects/${config.repoName}/merge_requests/${iid}`, { await get.put(`projects/${config.repository}/merge_requests/${iid}`, {
body: { body: {
title, title,
description, description,
@ -449,7 +454,7 @@ async function updatePr(iid, title, description) {
} }
async function mergePr(iid) { async function mergePr(iid) {
await get.put(`projects/${config.repoName}/merge_requests/${iid}/merge`, { await get.put(`projects/${config.repository}/merge_requests/${iid}/merge`, {
body: { body: {
should_remove_source_branch: true, should_remove_source_branch: true,
}, },
@ -467,7 +472,7 @@ async function getFile(filePath, branchName) {
} }
} }
try { try {
const url = `projects/${config.repoName}/repository/files/${urlEscape( const url = `projects/${config.repository}/repository/files/${urlEscape(
filePath filePath
)}?ref=${branchName || config.baseBranch}`; )}?ref=${branchName || config.baseBranch}`;
const res = await get(url); const res = await get(url);
@ -504,7 +509,7 @@ async function commitFilesToBranch(
ref: config.baseBranch, ref: config.baseBranch,
}, },
}; };
await get.post(`projects/${config.repoName}/repository/branches`, opts); await get.post(`projects/${config.repository}/repository/branches`, opts);
} }
} }
for (const file of files) { for (const file of files) {
@ -512,7 +517,7 @@ async function commitFilesToBranch(
if (existingFile) { if (existingFile) {
logger.debug(`${file.name} exists - updating it`); logger.debug(`${file.name} exists - updating it`);
await updateFile( await updateFile(
config.repoName, config.repository,
branchName, branchName,
file.name, file.name,
file.contents, file.contents,
@ -521,7 +526,7 @@ async function commitFilesToBranch(
} else { } else {
logger.debug(`Creating file ${file.name}`); logger.debug(`Creating file ${file.name}`);
await createFile( await createFile(
config.repoName, config.repository,
branchName, branchName,
file.name, file.name,
file.contents, file.contents,
@ -535,7 +540,7 @@ async function commitFilesToBranch(
async function getCommitMessages() { async function getCommitMessages() {
logger.debug('getCommitMessages'); logger.debug('getCommitMessages');
try { try {
const res = await get(`projects/${config.repoName}/repository/commits`); const res = await get(`projects/${config.repository}/repository/commits`);
return res.body.map(commit => commit.title); return res.body.map(commit => commit.title);
} catch (err) { } catch (err) {
logger.error({ err }, `getCommitMessages error`); logger.error({ err }, `getCommitMessages error`);

View file

@ -53,14 +53,14 @@ async function getRepos(token, endpoint) {
return repos.map(repo => `${repo.project.name}/${repo.name}`); return repos.map(repo => `${repo.project.name}/${repo.name}`);
} }
async function initRepo(repoName, token, endpoint) { async function initRepo({ repository, token, endpoint }) {
logger.debug(`initRepo("${repoName}")`); logger.debug(`initRepo("${repository}")`);
vstsHelper.setTokenAndEndpoint(token, endpoint); vstsHelper.setTokenAndEndpoint(token, endpoint);
config.repoName = repoName; config.repository = repository;
config.fileList = null; config.fileList = null;
config.prList = null; config.prList = null;
const repos = await vstsApi.gitApi().getRepositories(); const repos = await vstsApi.gitApi().getRepositories();
const names = vstsHelper.getProjectAndRepo(repoName); const names = vstsHelper.getProjectAndRepo(repository);
const repo = repos.filter( const repo = repos.filter(
c => c =>
c.name.toLowerCase() === names.repo.toLowerCase() && c.name.toLowerCase() === names.repo.toLowerCase() &&
@ -71,11 +71,11 @@ async function initRepo(repoName, token, endpoint) {
config.privateRepo = true; config.privateRepo = true;
config.isFork = false; config.isFork = false;
config.owner = '?owner?'; config.owner = '?owner?';
logger.debug(`${repoName} owner = ${config.owner}`); logger.debug(`${repository} owner = ${config.owner}`);
// Use default branch as PR target unless later overridden // Use default branch as PR target unless later overridden
config.defaultBranch = repo.defaultBranch; config.defaultBranch = repo.defaultBranch;
config.baseBranch = config.defaultBranch; config.baseBranch = config.defaultBranch;
logger.debug(`${repoName} default branch = ${config.defaultBranch}`); logger.debug(`${repository} default branch = ${config.defaultBranch}`);
config.baseCommitSHA = await getBranchCommit(config.baseBranch); config.baseCommitSHA = await getBranchCommit(config.baseBranch);
// Todo VSTS: Get Merge method // Todo VSTS: Get Merge method

View file

@ -122,17 +122,17 @@ async function getVSTSBranchObj(repoId, branchName, from) {
* @param {string} filePath * @param {string} filePath
* @param {string} fileContent * @param {string} fileContent
* @param {string} repoId * @param {string} repoId
* @param {string} repoName * @param {string} repository
* @param {string} branchName * @param {string} branchName
*/ */
async function getChanges(files, repoId, repoName, branchName) { async function getChanges(files, repoId, repository, branchName) {
const changes = []; const changes = [];
for (const file of files) { for (const file of files) {
// Add or update // Add or update
let changeType = 1; let changeType = 1;
const fileAlreadyThere = await getFile( const fileAlreadyThere = await getFile(
repoId, repoId,
repoName, repository,
file.name, file.name,
branchName branchName
); );
@ -158,11 +158,11 @@ async function getChanges(files, repoId, repoName, branchName) {
/** /**
* if no branchName, look globaly * if no branchName, look globaly
* @param {string} repoId * @param {string} repoId
* @param {string} repoName * @param {string} repository
* @param {string} filePath * @param {string} filePath
* @param {string} branchName * @param {string} branchName
*/ */
async function getFile(repoId, repoName, filePath, branchName) { async function getFile(repoId, repository, filePath, branchName) {
logger.trace(`getFile(filePath=${filePath}, branchName=${branchName})`); logger.trace(`getFile(filePath=${filePath}, branchName=${branchName})`);
const item = await vstsApi.gitApi().getItemText( const item = await vstsApi.gitApi().getItemText(
repoId, repoId,
@ -288,7 +288,7 @@ function getProjectAndRepo(str) {
repo: strSplited[1], repo: strSplited[1],
}; };
} }
const msg = `${str} can be only structured this way : 'repoName' or 'projectName/repoName'!`; const msg = `${str} can be only structured this way : 'repository' or 'projectName/repository'!`;
logger.error(msg); logger.error(msg);
throw new Error(msg); throw new Error(msg);
} }

View file

@ -8,13 +8,7 @@ function assignPlatform(config) {
} }
async function getPlatformConfig(config) { async function getPlatformConfig(config) {
const platformConfig = await platform.initRepo( const platformConfig = await platform.initRepo(config);
config.repository,
config.token,
config.endpoint,
config.forkMode,
config.forkToken
);
return { return {
...config, ...config,
...platformConfig, ...platformConfig,

View file

@ -88,20 +88,19 @@ describe('platform/github', () => {
describe('initRepo', () => { describe('initRepo', () => {
[ [
[undefined, ['mytoken'], 'mytoken', undefined], [undefined, 'mytoken', undefined],
[ [undefined, 'mytoken', 'https://my.custom.endpoint/'],
undefined, ['myenvtoken', 'myenvtoken', undefined],
['mytoken', 'https://my.custom.endpoint/'], ].forEach(([envToken, token, endpoint], i) => {
'mytoken',
'https://my.custom.endpoint/',
],
['myenvtoken', [], 'myenvtoken', undefined],
].forEach(([envToken, args, token, endpoint], i) => {
it(`should initialise the config for the repo - ${i}`, async () => { it(`should initialise the config for the repo - ${i}`, async () => {
if (envToken !== undefined) { if (envToken !== undefined) {
process.env.GITHUB_TOKEN = envToken; process.env.GITHUB_TOKEN = envToken;
} }
const config = await initRepo('some/repo', ...args); const config = await initRepo({
repository: 'some/repo',
token,
endpoint,
});
expect(get.mock.calls).toMatchSnapshot(); expect(get.mock.calls).toMatchSnapshot();
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
expect(process.env.GITHUB_TOKEN).toBe(token); expect(process.env.GITHUB_TOKEN).toBe(token);
@ -111,7 +110,7 @@ describe('platform/github', () => {
it('should throw an error if no token is provided', async () => { it('should throw an error if no token is provided', async () => {
let err; let err;
try { try {
await github.initRepo('some/repo'); await github.initRepo({ repository: 'some/repo' });
} catch (e) { } catch (e) {
err = e; err = e;
} }
@ -143,7 +142,10 @@ describe('platform/github', () => {
})); }));
return github.initRepo(...args); return github.initRepo(...args);
} }
const config = await squashInitRepo('some/repo', 'token'); const config = await squashInitRepo({
repository: 'some/repo',
token: 'token',
});
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
}); });
it('should forks when forkMode', async () => { it('should forks when forkMode', async () => {
@ -186,12 +188,12 @@ describe('platform/github', () => {
})); }));
return github.initRepo(...args); return github.initRepo(...args);
} }
const config = await forkInitRepo( const config = await forkInitRepo({
'some/repo', repository: 'some/repo',
'token', token: 'token',
'some-endpoint', endpoint: 'some-endpoint',
true forkMode: true,
); });
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
}); });
it('should update fork when forkMode', async () => { it('should update fork when forkMode', async () => {
@ -238,12 +240,12 @@ describe('platform/github', () => {
})); }));
return github.initRepo(...args); return github.initRepo(...args);
} }
const config = await forkInitRepo( const config = await forkInitRepo({
'some/repo', repository: 'some/repo',
'token', token: 'token',
'some-endpoint', endpoint: 'some-endpoint',
true forkMode: true,
); });
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
}); });
it('should squash', async () => { it('should squash', async () => {
@ -270,7 +272,10 @@ describe('platform/github', () => {
})); }));
return github.initRepo(...args); return github.initRepo(...args);
} }
const config = await mergeInitRepo('some/repo', 'token'); const config = await mergeInitRepo({
repository: 'some/repo',
token: 'token',
});
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
}); });
it('should merge', async () => { it('should merge', async () => {
@ -297,7 +302,10 @@ describe('platform/github', () => {
})); }));
return github.initRepo(...args); return github.initRepo(...args);
} }
const config = await mergeInitRepo('some/repo', 'token'); const config = await mergeInitRepo({
repository: 'some/repo',
token: 'token',
});
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
}); });
it('should not guess at merge', async () => { it('should not guess at merge', async () => {
@ -321,7 +329,10 @@ describe('platform/github', () => {
})); }));
return github.initRepo(...args); return github.initRepo(...args);
} }
const config = await mergeInitRepo('some/repo', 'token'); const config = await mergeInitRepo({
repository: 'some/repo',
token: 'token',
});
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
}); });
it('should throw error if archived', async () => { it('should throw error if archived', async () => {
@ -333,7 +344,10 @@ describe('platform/github', () => {
}); });
let e; let e;
try { try {
await github.initRepo('some/repo', 'token'); await github.initRepo({
repository: 'some/repo',
token: 'token',
});
} catch (err) { } catch (err) {
e = err; e = err;
} }
@ -347,7 +361,10 @@ describe('platform/github', () => {
); );
let e; let e;
try { try {
await github.initRepo('some/repo', 'token'); await github.initRepo({
repository: 'some/repo',
token: 'token',
});
} catch (err) { } catch (err) {
e = err; e = err;
} }
@ -417,8 +434,10 @@ describe('platform/github', () => {
}); });
describe('setBaseBranch(branchName)', () => { describe('setBaseBranch(branchName)', () => {
it('sets the base branch', async () => { it('sets the base branch', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -481,7 +500,10 @@ describe('platform/github', () => {
}); });
describe('branchExists(branchName)', () => { describe('branchExists(branchName)', () => {
it('should return true if the branch exists (one result)', async () => { it('should return true if the branch exists (one result)', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: [ body: [
{ {
@ -495,7 +517,10 @@ describe('platform/github', () => {
}); });
describe('getAllRenovateBranches()', () => { describe('getAllRenovateBranches()', () => {
it('should return all renovate branches', async () => { it('should return all renovate branches', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: [ body: [
{ {
@ -515,8 +540,10 @@ describe('platform/github', () => {
}); });
describe('isBranchStale(branchName)', () => { describe('isBranchStale(branchName)', () => {
it('should return false if same SHA as master', async () => { it('should return false if same SHA as master', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -545,8 +572,10 @@ describe('platform/github', () => {
expect(await github.isBranchStale('thebranchname')).toBe(false); expect(await github.isBranchStale('thebranchname')).toBe(false);
}); });
it('should return true if SHA different from master', async () => { it('should return true if SHA different from master', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -577,7 +606,10 @@ describe('platform/github', () => {
}); });
describe('getBranchPr(branchName)', () => { describe('getBranchPr(branchName)', () => {
it('should return null if no PR exists', async () => { it('should return null if no PR exists', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: [], body: [],
})); }));
@ -585,7 +617,10 @@ describe('platform/github', () => {
expect(pr).toBe(null); expect(pr).toBe(null);
}); });
it('should return the PR object', async () => { it('should return the PR object', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: [{ number: 91, head: {} }], body: [{ number: 91, head: {} }],
})); }));
@ -607,17 +642,26 @@ describe('platform/github', () => {
}); });
describe('getBranchStatus(branchName, requiredStatusChecks)', () => { describe('getBranchStatus(branchName, requiredStatusChecks)', () => {
it('returne success if requiredStatusChecks null', async () => { it('returne success if requiredStatusChecks null', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
const res = await github.getBranchStatus('somebranch', null); const res = await github.getBranchStatus('somebranch', null);
expect(res).toEqual('success'); expect(res).toEqual('success');
}); });
it('return failed if unsupported requiredStatusChecks', async () => { it('return failed if unsupported requiredStatusChecks', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
const res = await github.getBranchStatus('somebranch', ['foo']); const res = await github.getBranchStatus('somebranch', ['foo']);
expect(res).toEqual('failed'); expect(res).toEqual('failed');
}); });
it('should pass through success', async () => { it('should pass through success', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
state: 'success', state: 'success',
@ -627,7 +671,10 @@ describe('platform/github', () => {
expect(res).toEqual('success'); expect(res).toEqual('success');
}); });
it('should pass through failed', async () => { it('should pass through failed', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
state: 'failed', state: 'failed',
@ -639,8 +686,10 @@ describe('platform/github', () => {
}); });
describe('getBranchStatusCheck', () => { describe('getBranchStatusCheck', () => {
it('returns state if found', async () => { it('returns state if found', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -668,8 +717,10 @@ describe('platform/github', () => {
expect(res).toEqual('state-2'); expect(res).toEqual('state-2');
}); });
it('returns null', async () => { it('returns null', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -699,8 +750,10 @@ describe('platform/github', () => {
}); });
describe('setBranchStatus', () => { describe('setBranchStatus', () => {
it('sets branch status', async () => { it('sets branch status', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -720,8 +773,10 @@ describe('platform/github', () => {
}); });
describe('mergeBranch(branchName, mergeType)', () => { describe('mergeBranch(branchName, mergeType)', () => {
it('should perform a branch-push merge', async () => { it('should perform a branch-push merge', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -748,8 +803,10 @@ describe('platform/github', () => {
expect(get.delete.mock.calls).toMatchSnapshot(); expect(get.delete.mock.calls).toMatchSnapshot();
}); });
it('should throw if branch-push merge throws', async () => { it('should throw if branch-push merge throws', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -774,8 +831,10 @@ describe('platform/github', () => {
expect(get.delete.mock.calls).toMatchSnapshot(); expect(get.delete.mock.calls).toMatchSnapshot();
}); });
it('should perform a branch-merge-commit merge', async () => { it('should perform a branch-merge-commit merge', async () => {
await initRepo('some/repo', 'token'); await initRepo({
// getBranchCommit repository: 'some/repo',
token: 'token',
}); // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
object: { object: {
@ -791,7 +850,10 @@ describe('platform/github', () => {
expect(get.delete.mock.calls).toMatchSnapshot(); expect(get.delete.mock.calls).toMatchSnapshot();
}); });
it('should throw if branch-merge-commit throws', async () => { it('should throw if branch-merge-commit throws', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.post.mockImplementationOnce(() => { get.post.mockImplementationOnce(() => {
throw new Error('branch-push failed'); throw new Error('branch-push failed');
}); });
@ -809,7 +871,10 @@ describe('platform/github', () => {
expect(get.delete.mock.calls).toMatchSnapshot(); expect(get.delete.mock.calls).toMatchSnapshot();
}); });
it('should throw if unknown merge type', async () => { it('should throw if unknown merge type', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
let e; let e;
try { try {
await github.mergeBranch('thebranchname', 'wrong-merge-type'); await github.mergeBranch('thebranchname', 'wrong-merge-type');
@ -826,7 +891,10 @@ describe('platform/github', () => {
}); });
describe('getBranchLastCommitTime', () => { describe('getBranchLastCommitTime', () => {
it('should return a Date', async () => { it('should return a Date', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockReturnValueOnce({ get.mockReturnValueOnce({
body: [ body: [
{ {
@ -842,7 +910,10 @@ describe('platform/github', () => {
expect(res).toMatchSnapshot(); expect(res).toMatchSnapshot();
}); });
it('handles error', async () => { it('handles error', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockReturnValueOnce({ get.mockReturnValueOnce({
body: [], body: [],
}); });
@ -921,14 +992,20 @@ describe('platform/github', () => {
}); });
describe('addAssignees(issueNo, assignees)', () => { describe('addAssignees(issueNo, assignees)', () => {
it('should add the given assignees to the issue', async () => { it('should add the given assignees to the issue', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
await github.addAssignees(42, ['someuser', 'someotheruser']); await github.addAssignees(42, ['someuser', 'someotheruser']);
expect(get.post.mock.calls).toMatchSnapshot(); expect(get.post.mock.calls).toMatchSnapshot();
}); });
}); });
describe('addReviewers(issueNo, reviewers)', () => { describe('addReviewers(issueNo, reviewers)', () => {
it('should add the given reviewers to the PR', async () => { it('should add the given reviewers to the PR', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.post.mockReturnValueOnce({}); get.post.mockReturnValueOnce({});
await github.addReviewers(42, ['someuser', 'someotheruser']); await github.addReviewers(42, ['someuser', 'someotheruser']);
expect(get.post.mock.calls).toMatchSnapshot(); expect(get.post.mock.calls).toMatchSnapshot();
@ -936,14 +1013,20 @@ describe('platform/github', () => {
}); });
describe('ensureComment', () => { describe('ensureComment', () => {
it('add comment if not found', async () => { it('add comment if not found', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockReturnValueOnce({ body: [] }); get.mockReturnValueOnce({ body: [] });
await github.ensureComment(42, 'some-subject', 'some\ncontent'); await github.ensureComment(42, 'some-subject', 'some\ncontent');
expect(get.post.mock.calls).toHaveLength(1); expect(get.post.mock.calls).toHaveLength(1);
expect(get.post.mock.calls).toMatchSnapshot(); expect(get.post.mock.calls).toMatchSnapshot();
}); });
it('add updates comment if necessary', async () => { it('add updates comment if necessary', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockReturnValueOnce({ get.mockReturnValueOnce({
body: [{ id: 1234, body: '### some-subject\n\nblablabla' }], body: [{ id: 1234, body: '### some-subject\n\nblablabla' }],
}); });
@ -953,7 +1036,10 @@ describe('platform/github', () => {
expect(get.patch.mock.calls).toMatchSnapshot(); expect(get.patch.mock.calls).toMatchSnapshot();
}); });
it('skips comment', async () => { it('skips comment', async () => {
await initRepo('some/repo', 'token'); await initRepo({
repository: 'some/repo',
token: 'token',
});
get.mockReturnValueOnce({ get.mockReturnValueOnce({
body: [{ id: 1234, body: '### some-subject\n\nsome\ncontent' }], body: [{ id: 1234, body: '### some-subject\n\nsome\ncontent' }],
}); });
@ -964,7 +1050,7 @@ describe('platform/github', () => {
}); });
describe('ensureCommentRemoval', () => { describe('ensureCommentRemoval', () => {
it('deletes comment if found', async () => { it('deletes comment if found', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockReturnValueOnce({ get.mockReturnValueOnce({
body: [{ id: 1234, body: '### some-subject\n\nblablabla' }], body: [{ id: 1234, body: '### some-subject\n\nblablabla' }],
}); });
@ -1024,7 +1110,7 @@ describe('platform/github', () => {
}); });
describe('createPr()', () => { describe('createPr()', () => {
it('should create and return a PR object', async () => { it('should create and return a PR object', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.post.mockImplementationOnce(() => ({ get.post.mockImplementationOnce(() => ({
body: { body: {
number: 123, number: 123,
@ -1040,7 +1126,7 @@ describe('platform/github', () => {
expect(get.post.mock.calls).toMatchSnapshot(); expect(get.post.mock.calls).toMatchSnapshot();
}); });
it('should use defaultBranch', async () => { it('should use defaultBranch', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.post.mockImplementationOnce(() => ({ get.post.mockImplementationOnce(() => ({
body: { body: {
number: 123, number: 123,
@ -1062,7 +1148,7 @@ describe('platform/github', () => {
expect(pr).toBe(null); expect(pr).toBe(null);
}); });
it('should return null if no PR is returned from GitHub', async () => { it('should return null if no PR is returned from GitHub', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: null, body: null,
})); }));
@ -1081,7 +1167,7 @@ describe('platform/github', () => {
{ number: 1, state: 'open', base: { sha: '5678' }, commits: 1 }, { number: 1, state: 'open', base: { sha: '5678' }, commits: 1 },
].forEach((body, i) => { ].forEach((body, i) => {
it(`should return a PR object - ${i}`, async () => { it(`should return a PR object - ${i}`, async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body, body,
})); }));
@ -1098,7 +1184,7 @@ describe('platform/github', () => {
}); });
}); });
it('should return a rebaseable PR despite multiple commits', async () => { it('should return a rebaseable PR despite multiple commits', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
number: 1, number: 1,
@ -1129,7 +1215,7 @@ describe('platform/github', () => {
expect(pr).toMatchSnapshot(); expect(pr).toMatchSnapshot();
}); });
it('should return an unrebaseable PR if multiple authors', async () => { it('should return an unrebaseable PR if multiple authors', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
number: 1, number: 1,
@ -1168,7 +1254,7 @@ describe('platform/github', () => {
expect(pr).toMatchSnapshot(); expect(pr).toMatchSnapshot();
}); });
it('should return a rebaseable PR if web-flow is second author', async () => { it('should return a rebaseable PR if web-flow is second author', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
number: 1, number: 1,
@ -1228,14 +1314,14 @@ describe('platform/github', () => {
}); });
describe('updatePr(prNo, title, body)', () => { describe('updatePr(prNo, title, body)', () => {
it('should update the PR', async () => { it('should update the PR', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
await github.updatePr(1234, 'The New Title', 'Hello world again'); await github.updatePr(1234, 'The New Title', 'Hello world again');
expect(get.patch.mock.calls).toMatchSnapshot(); expect(get.patch.mock.calls).toMatchSnapshot();
}); });
}); });
describe('mergePr(prNo)', () => { describe('mergePr(prNo)', () => {
it('should merge the PR', async () => { it('should merge the PR', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
// getBranchCommit // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
@ -1256,7 +1342,7 @@ describe('platform/github', () => {
expect(get.mock.calls).toHaveLength(3); expect(get.mock.calls).toHaveLength(3);
}); });
it('should handle merge error', async () => { it('should handle merge error', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
const pr = { const pr = {
number: 1234, number: 1234,
head: { head: {
@ -1318,7 +1404,7 @@ describe('platform/github', () => {
})); }));
return github.initRepo(...args); return github.initRepo(...args);
} }
await guessInitRepo('some/repo', 'token'); await guessInitRepo({ repository: 'some/repo', token: 'token' });
get.put = jest.fn(); get.put = jest.fn();
}); });
it('should try rebase first', async () => { it('should try rebase first', async () => {
@ -1386,7 +1472,7 @@ describe('platform/github', () => {
}); });
describe('getFile()', () => { describe('getFile()', () => {
it('should return the encoded file content', async () => { it('should return the encoded file content', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
content: Buffer.from('hello world').toString('base64'), content: Buffer.from('hello world').toString('base64'),
@ -1397,12 +1483,12 @@ describe('platform/github', () => {
expect(content).toBe('hello world'); expect(content).toBe('hello world');
}); });
it('should return null if not in file list', async () => { it('should return null if not in file list', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
const content = await github.getFile('.npmrc'); const content = await github.getFile('.npmrc');
expect(content).toBe(null); expect(content).toBe(null);
}); });
it('should return null if GitHub returns a 404', async () => { it('should return null if GitHub returns a 404', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => get.mockImplementationOnce(() =>
Promise.reject({ Promise.reject({
statusCode: 404, statusCode: 404,
@ -1413,7 +1499,7 @@ describe('platform/github', () => {
expect(content).toBe(null); expect(content).toBe(null);
}); });
it('should return large file via git API', async () => { it('should return large file via git API', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => get.mockImplementationOnce(() =>
Promise.reject({ Promise.reject({
statusCode: 403, statusCode: 403,
@ -1440,7 +1526,7 @@ describe('platform/github', () => {
expect(content).toMatchSnapshot(); expect(content).toMatchSnapshot();
}); });
it('should throw if cannot find large file via git API', async () => { it('should throw if cannot find large file via git API', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => get.mockImplementationOnce(() =>
Promise.reject({ Promise.reject({
statusCode: 403, statusCode: 403,
@ -1461,7 +1547,7 @@ describe('platform/github', () => {
expect(e).toBeDefined(); expect(e).toBeDefined();
}); });
it('should return null if getFile returns nothing', async () => { it('should return null if getFile returns nothing', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: {}, body: {},
})); }));
@ -1470,7 +1556,7 @@ describe('platform/github', () => {
expect(content).toBe(null); expect(content).toBe(null);
}); });
it('should return propagate unknown errors', async () => { it('should return propagate unknown errors', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
get.mockImplementationOnce(() => { get.mockImplementationOnce(() => {
throw new Error('Something went wrong'); throw new Error('Something went wrong');
}); });
@ -1485,7 +1571,7 @@ describe('platform/github', () => {
}); });
describe('commitFilesToBranch(branchName, files, message, parentBranch)', () => { describe('commitFilesToBranch(branchName, files, message, parentBranch)', () => {
beforeEach(async () => { beforeEach(async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
// getBranchCommit // getBranchCommit
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({

View file

@ -63,7 +63,7 @@ describe('platform/gitlab', () => {
}); });
function initRepo(...args) { function initRepo(...args) {
// projects/${config.repoName // projects/${config.repository
get.mockImplementationOnce(() => ({ get.mockImplementationOnce(() => ({
body: { body: {
default_branch: 'master', default_branch: 'master',
@ -80,21 +80,20 @@ describe('platform/gitlab', () => {
describe('initRepo', () => { describe('initRepo', () => {
[ [
[undefined, ['mytoken'], 'mytoken', undefined], [undefined, 'mytoken', undefined],
[ [undefined, 'mytoken', 'https://my.custom.endpoint/'],
undefined, ['myenvtoken', 'myenvtoken', undefined],
['mytoken', 'https://my.custom.endpoint/'], ].forEach(([envToken, token, endpoint], i) => {
'mytoken',
'https://my.custom.endpoint/',
],
['myenvtoken', [], 'myenvtoken', undefined],
].forEach(([envToken, args, token, endpoint], i) => {
it(`should initialise the config for the repo - ${i}`, async () => { it(`should initialise the config for the repo - ${i}`, async () => {
if (envToken !== undefined) { if (envToken !== undefined) {
process.env.GITLAB_TOKEN = envToken; process.env.GITLAB_TOKEN = envToken;
} }
get.mockReturnValue({ body: [] }); get.mockReturnValue({ body: [] });
const config = await initRepo('some/repo', ...args); const config = await initRepo({
repository: 'some/repo',
token,
endpoint,
});
expect(get.mock.calls).toMatchSnapshot(); expect(get.mock.calls).toMatchSnapshot();
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
expect(process.env.GITLAB_TOKEN).toBe(token); expect(process.env.GITLAB_TOKEN).toBe(token);
@ -103,13 +102,13 @@ describe('platform/gitlab', () => {
}); });
it(`should escape all forward slashes in project names`, async () => { it(`should escape all forward slashes in project names`, async () => {
get.mockReturnValue({ body: [] }); get.mockReturnValue({ body: [] });
await initRepo('some/repo/project', 'some-token'); await initRepo({ repository: 'some/repo/project', token: 'some-token' });
expect(get.mock.calls).toMatchSnapshot(); expect(get.mock.calls).toMatchSnapshot();
}); });
it('should throw an error if no token is provided', async () => { it('should throw an error if no token is provided', async () => {
let err; let err;
try { try {
await gitlab.initRepo('some/repo'); await gitlab.initRepo({ repository: 'some/repo' });
} catch (e) { } catch (e) {
err = e; err = e;
} }
@ -123,7 +122,7 @@ describe('platform/gitlab', () => {
}); });
let err; let err;
try { try {
await gitlab.initRepo('some/repo', 'sometoken'); await gitlab.initRepo({ repository: 'some/repo', token: 'sometoken' });
} catch (e) { } catch (e) {
err = e; err = e;
} }

View file

@ -147,7 +147,7 @@ Object {
"privateRepo": true, "privateRepo": true,
"repoForceRebase": false, "repoForceRebase": false,
"repoId": "1", "repoId": "1",
"repoName": "some-repo", "repository": "some-repo",
} }
`; `;

View file

@ -81,11 +81,11 @@ describe('platform/vsts', () => {
describe('initRepo', () => { describe('initRepo', () => {
it(`should initialise the config for a repo`, async () => { it(`should initialise the config for a repo`, async () => {
const config = await initRepo( const config = await initRepo({
'some-repo', repository: 'some-repo',
'token', token: 'token',
'https://my.custom.endpoint/' endpoint: 'https://my.custom.endpoint/',
); });
expect(vstsApi.gitApi.mock.calls).toMatchSnapshot(); expect(vstsApi.gitApi.mock.calls).toMatchSnapshot();
expect(config).toMatchSnapshot(); expect(config).toMatchSnapshot();
}); });
@ -141,7 +141,7 @@ describe('platform/vsts', () => {
expect(msg).toMatchSnapshot(); expect(msg).toMatchSnapshot();
}); });
it('returns empty array if error', async () => { it('returns empty array if error', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => { vstsApi.gitApi.mockImplementationOnce(() => {
throw new Error('some error'); throw new Error('some error');
}); });
@ -277,7 +277,7 @@ describe('platform/vsts', () => {
expect(res).toMatchSnapshot(); expect(res).toMatchSnapshot();
}); });
it('returns null if error', async () => { it('returns null if error', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => { vstsApi.gitApi.mockImplementationOnce(() => {
throw new Error('some error'); throw new Error('some error');
}); });
@ -293,7 +293,7 @@ describe('platform/vsts', () => {
}); });
describe('getFileList', () => { describe('getFileList', () => {
it('returns empty array if error', async () => { it('returns empty array if error', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => { vstsApi.gitApi.mockImplementationOnce(() => {
throw new Error('some error'); throw new Error('some error');
}); });
@ -301,7 +301,7 @@ describe('platform/vsts', () => {
expect(files).toEqual([]); expect(files).toEqual([]);
}); });
it('caches the result', async () => { it('caches the result', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getItems: jest.fn(() => [ getItems: jest.fn(() => [
{ path: '/symlinks/package.json' }, { path: '/symlinks/package.json' },
@ -317,7 +317,7 @@ describe('platform/vsts', () => {
expect(files.length).toBe(4); expect(files.length).toBe(4);
}); });
it('should return the files matching the fileName', async () => { it('should return the files matching the fileName', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getItems: jest.fn(() => [ getItems: jest.fn(() => [
{ path: '/symlinks/package.json' }, { path: '/symlinks/package.json' },
@ -334,7 +334,7 @@ describe('platform/vsts', () => {
describe('commitFilesToBranch(branchName, files, message, parentBranch)', () => { describe('commitFilesToBranch(branchName, files, message, parentBranch)', () => {
it('should add a new commit to the branch', async () => { it('should add a new commit to the branch', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
createPush: jest.fn(() => true), createPush: jest.fn(() => true),
})); }));
@ -355,7 +355,7 @@ describe('platform/vsts', () => {
expect(vstsApi.gitApi.mock.calls.length).toBe(3); expect(vstsApi.gitApi.mock.calls.length).toBe(3);
}); });
it('should add a new commit to an existing branch', async () => { it('should add a new commit to an existing branch', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
createPush: jest.fn(() => true), createPush: jest.fn(() => true),
})); }));
@ -388,7 +388,7 @@ describe('platform/vsts', () => {
describe('getBranchPr(branchName)', () => { describe('getBranchPr(branchName)', () => {
it('should return null if no PR exists', async () => { it('should return null if no PR exists', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
findPr: jest.fn(() => false), findPr: jest.fn(() => false),
getPr: jest.fn(() => { getPr: jest.fn(() => {
@ -399,7 +399,7 @@ describe('platform/vsts', () => {
expect(pr).toBe(null); expect(pr).toBe(null);
}); });
it('should return the pr', async () => { it('should return the pr', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementation(() => ({ vstsApi.gitApi.mockImplementation(() => ({
getPullRequests: jest.fn(() => [ getPullRequests: jest.fn(() => [
{ {
@ -437,7 +437,7 @@ describe('platform/vsts', () => {
expect(res).toEqual('failed'); expect(res).toEqual('failed');
}); });
it('should pass through success', async () => { it('should pass through success', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getBranch: jest.fn(() => ({ aheadCount: 0 })), getBranch: jest.fn(() => ({ aheadCount: 0 })),
})); }));
@ -445,7 +445,7 @@ describe('platform/vsts', () => {
expect(res).toEqual('success'); expect(res).toEqual('success');
}); });
it('should pass through failed', async () => { it('should pass through failed', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getBranch: jest.fn(() => ({ aheadCount: 123 })), getBranch: jest.fn(() => ({ aheadCount: 123 })),
})); }));
@ -460,7 +460,7 @@ describe('platform/vsts', () => {
expect(pr).toBe(null); expect(pr).toBe(null);
}); });
it('should return null if no PR is returned from vsts', async () => { it('should return null if no PR is returned from vsts', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getPullRequests: jest.fn(() => []), getPullRequests: jest.fn(() => []),
})); }));
@ -468,7 +468,7 @@ describe('platform/vsts', () => {
expect(pr).toBe(null); expect(pr).toBe(null);
}); });
it('should return a pr in the right format', async () => { it('should return a pr in the right format', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getPullRequests: jest.fn(() => [{ pullRequestId: 1234 }]), getPullRequests: jest.fn(() => [{ pullRequestId: 1234 }]),
})); }));
@ -482,7 +482,7 @@ describe('platform/vsts', () => {
describe('createPr()', () => { describe('createPr()', () => {
it('should create and return a PR object', async () => { it('should create and return a PR object', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
createPullRequest: jest.fn(() => ({ createPullRequest: jest.fn(() => ({
pullRequestId: 456, pullRequestId: 456,
@ -503,7 +503,7 @@ describe('platform/vsts', () => {
expect(pr).toMatchSnapshot(); expect(pr).toMatchSnapshot();
}); });
it('should create and return a PR object from base branch', async () => { it('should create and return a PR object from base branch', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
createPullRequest: jest.fn(() => ({ createPullRequest: jest.fn(() => ({
pullRequestId: 456, pullRequestId: 456,
@ -528,7 +528,7 @@ describe('platform/vsts', () => {
describe('updatePr(prNo, title, body)', () => { describe('updatePr(prNo, title, body)', () => {
it('should update the PR', async () => { it('should update the PR', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
updatePullRequest: jest.fn(), updatePullRequest: jest.fn(),
})); }));
@ -539,7 +539,7 @@ describe('platform/vsts', () => {
describe('ensureComment', () => { describe('ensureComment', () => {
it('add comment', async () => { it('add comment', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementation(() => ({ vstsApi.gitApi.mockImplementation(() => ({
createThread: jest.fn(() => [{ id: 123 }]), createThread: jest.fn(() => [{ id: 123 }]),
})); }));
@ -550,7 +550,7 @@ describe('platform/vsts', () => {
describe('isBranchStale', () => { describe('isBranchStale', () => {
it('should return true', async () => { it('should return true', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getBranch: jest.fn(() => ({ commit: { commitId: '123456' } })), getBranch: jest.fn(() => ({ commit: { commitId: '123456' } })),
})); }));
@ -561,7 +561,7 @@ describe('platform/vsts', () => {
expect(res).toBe(true); expect(res).toBe(true);
}); });
it('should return false', async () => { it('should return false', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getBranch: jest.fn(() => ({ commit: { commitId: '123457' } })), getBranch: jest.fn(() => ({ commit: { commitId: '123457' } })),
})); }));
@ -575,7 +575,7 @@ describe('platform/vsts', () => {
describe('getAllRenovateBranches()', () => { describe('getAllRenovateBranches()', () => {
it('should return all renovate branches', async () => { it('should return all renovate branches', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getBranches: jest.fn(() => [ getBranches: jest.fn(() => [
{ name: 'master' }, { name: 'master' },
@ -590,7 +590,7 @@ describe('platform/vsts', () => {
describe('ensureCommentRemoval', () => { describe('ensureCommentRemoval', () => {
it('deletes comment if found', async () => { it('deletes comment if found', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementation(() => ({ vstsApi.gitApi.mockImplementation(() => ({
getThreads: jest.fn(() => [ getThreads: jest.fn(() => [
{ comments: [{ content: '### some-subject\n\nblabla' }], id: 123 }, { comments: [{ content: '### some-subject\n\nblabla' }], id: 123 },
@ -605,7 +605,7 @@ describe('platform/vsts', () => {
expect(vstsApi.gitApi.mock.calls.length).toBe(0); expect(vstsApi.gitApi.mock.calls.length).toBe(0);
}); });
it('comment not found', async () => { it('comment not found', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementation(() => ({ vstsApi.gitApi.mockImplementation(() => ({
getThreads: jest.fn(() => [ getThreads: jest.fn(() => [
{ comments: [{ content: 'stupid comment' }], id: 123 }, { comments: [{ content: 'stupid comment' }], id: 123 },
@ -619,7 +619,7 @@ describe('platform/vsts', () => {
describe('getBranchLastCommitTime', () => { describe('getBranchLastCommitTime', () => {
it('should return a Date', async () => { it('should return a Date', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementationOnce(() => ({ vstsApi.gitApi.mockImplementationOnce(() => ({
getBranch: jest.fn(() => ({ getBranch: jest.fn(() => ({
commit: { committer: { date: '1986-11-07T00:00:00Z' } }, commit: { committer: { date: '1986-11-07T00:00:00Z' } },
@ -664,7 +664,7 @@ describe('platform/vsts', () => {
}); });
it('addAssignees', async () => { it('addAssignees', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementation(() => ({ vstsApi.gitApi.mockImplementation(() => ({
createThread: jest.fn(() => [{ id: 123 }]), createThread: jest.fn(() => [{ id: 123 }]),
})); }));
@ -673,7 +673,7 @@ describe('platform/vsts', () => {
}); });
it('addReviewers', async () => { it('addReviewers', async () => {
await initRepo('some/repo', 'token'); await initRepo({ repository: 'some/repo', token: 'token' });
vstsApi.gitApi.mockImplementation(() => ({ vstsApi.gitApi.mockImplementation(() => ({
getRepositories: jest.fn(() => [{ id: '1', project: { id: 2 } }]), getRepositories: jest.fn(() => [{ id: '1', project: { id: 2 } }]),
createPullRequestReviewer: jest.fn(), createPullRequestReviewer: jest.fn(),

View file

@ -157,7 +157,7 @@ describe('platform/vsts/helpers', () => {
}, },
], ],
'123', '123',
'repoName', 'repository',
'branchName' 'branchName'
); );
expect(res).toMatchSnapshot(); expect(res).toMatchSnapshot();
@ -175,7 +175,7 @@ describe('platform/vsts/helpers', () => {
}, },
], ],
'123', '123',
'repoName', 'repository',
'branchName' 'branchName'
); );
expect(res).toMatchSnapshot(); expect(res).toMatchSnapshot();
@ -204,7 +204,7 @@ describe('platform/vsts/helpers', () => {
const res = await vstsHelper.getFile( const res = await vstsHelper.getFile(
'123', '123',
'repoName', 'repository',
'./myFilePath/test', './myFilePath/test',
'branchName' 'branchName'
); );
@ -232,7 +232,7 @@ describe('platform/vsts/helpers', () => {
const res = await vstsHelper.getFile( const res = await vstsHelper.getFile(
'123', '123',
'repoName', 'repository',
'./myFilePath/test', './myFilePath/test',
'branchName' 'branchName'
); );
@ -260,7 +260,7 @@ describe('platform/vsts/helpers', () => {
const res = await vstsHelper.getFile( const res = await vstsHelper.getFile(
'123', '123',
'repoName', 'repository',
'./myFilePath/test', './myFilePath/test',
'branchName' 'branchName'
); );
@ -276,7 +276,7 @@ describe('platform/vsts/helpers', () => {
const res = await vstsHelper.getFile( const res = await vstsHelper.getFile(
'123', '123',
'repoName', 'repository',
'./myFilePath/test', './myFilePath/test',
'branchName' 'branchName'
); );
@ -350,7 +350,7 @@ describe('platform/vsts/helpers', () => {
err = error; err = error;
} }
expect(err.message).toBe( expect(err.message).toBe(
`prjName/myRepoName/blalba can be only structured this way : 'repoName' or 'projectName/repoName'!` `prjName/myRepoName/blalba can be only structured this way : 'repository' or 'projectName/repository'!`
); );
}); });
}); });