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

View file

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

View file

@ -72,12 +72,11 @@ function urlEscape(str) {
}
// Initialize GitLab by getting base branch
async function initRepo(repoName, token, endpoint) {
logger.debug(`initRepo(${repoName})`);
async function initRepo({ repository, token, endpoint }) {
if (token) {
process.env.GITLAB_TOKEN = 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) {
process.env.GITLAB_TOKEN = token;
@ -87,12 +86,12 @@ async function initRepo(repoName, token, endpoint) {
}
config = {};
get.reset();
config.repoName = urlEscape(repoName);
config.repository = urlEscape(repository);
try {
const res = await get(`projects/${config.repoName}`);
const res = await get(`projects/${config.repository}`);
config.defaultBranch = res.body.default_branch;
config.baseBranch = config.defaultBranch;
logger.debug(`${repoName} default branch = ${config.baseBranch}`);
logger.debug(`${repository} default branch = ${config.baseBranch}`);
// Discover our user email
config.email = (await get(`user`)).body.email;
delete config.prList;
@ -125,7 +124,7 @@ async function getFileList(branchName = config.baseBranch) {
try {
const res = await get(
`projects/${
config.repoName
config.repository
}/repository/tree?ref=${branchName}&recursive=true&per_page=100`,
{ paginate: true }
);
@ -146,7 +145,7 @@ async function getFileList(branchName = config.baseBranch) {
async function branchExists(branchName) {
logger.debug(`Checking if branch exists: ${branchName}`);
try {
const url = `projects/${config.repoName}/repository/branches/${urlEscape(
const url = `projects/${config.repository}/repository/branches/${urlEscape(
branchName
)}`;
const res = await get(url);
@ -182,7 +181,7 @@ function isBranchStale() {
async function getBranchPr(branchName) {
logger.debug(`getBranchPr(${branchName})`);
const urlString = `projects/${
config.repoName
config.repository
}/merge_requests?state=opened&per_page=100`;
const res = await get(urlString, { paginate: true });
logger.debug(`Got res with ${res.body.length} results`);
@ -211,13 +210,15 @@ async function getBranchStatus(branchName, requiredStatusChecks) {
return 'failed';
}
// 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
)}`;
let res = await get(url);
const branchSha = res.body.commit.id;
// 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);
logger.debug(`Got res with ${res.body.length} results`);
if (res.body.length === 0) {
@ -241,13 +242,15 @@ async function getBranchStatus(branchName, requiredStatusChecks) {
async function getBranchStatusCheck(branchName, context) {
// 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
)}`;
let res = await get(url);
const branchSha = res.body.commit.id;
// 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);
logger.debug(`Got res with ${res.body.length} results`);
for (const check of res.body) {
@ -266,13 +269,13 @@ async function setBranchStatus(
targetUrl
) {
// 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
)}`;
const res = await get(url);
const branchSha = res.body.commit.id;
// Now, check the statuses for that commit
url = `projects/${config.repoName}/statuses/${branchSha}`;
url = `projects/${config.repository}/statuses/${branchSha}`;
const options = {
state,
description,
@ -286,7 +289,7 @@ async function setBranchStatus(
async function deleteBranch(branchName) {
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) {
try {
const res = await get(
`projects/${config.repoName}/repository/commits?ref_name=${urlEscape(
`projects/${config.repository}/repository/commits?ref_name=${urlEscape(
branchName
)}`
);
@ -324,7 +327,7 @@ async function addAssignees(iid, assignees) {
}
try {
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}`;
await get.put(url);
} catch (err) {
@ -347,7 +350,9 @@ async function ensureCommentRemoval() {
async function getPrList() {
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 });
config.prList = res.body.map(pr => ({
number: pr.iid,
@ -394,7 +399,7 @@ async function createPr(
? config.defaultBranch
: config.baseBranch;
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: {
source_branch: branchName,
target_branch: targetBranch,
@ -412,7 +417,7 @@ async function createPr(
async function 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;
// Harmonize fields with GitHub
pr.number = pr.iid;
@ -425,7 +430,7 @@ async function getPr(iid) {
// 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
const branchUrl = `projects/${
config.repoName
config.repository
}/repository/branches/${urlEscape(pr.source_branch)}`;
const branch = (await get(branchUrl)).body;
if (branch && branch.commit && branch.commit.author_email === config.email) {
@ -440,7 +445,7 @@ function getPrFiles() {
}
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: {
title,
description,
@ -449,7 +454,7 @@ async function updatePr(iid, title, description) {
}
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: {
should_remove_source_branch: true,
},
@ -467,7 +472,7 @@ async function getFile(filePath, branchName) {
}
}
try {
const url = `projects/${config.repoName}/repository/files/${urlEscape(
const url = `projects/${config.repository}/repository/files/${urlEscape(
filePath
)}?ref=${branchName || config.baseBranch}`;
const res = await get(url);
@ -504,7 +509,7 @@ async function commitFilesToBranch(
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) {
@ -512,7 +517,7 @@ async function commitFilesToBranch(
if (existingFile) {
logger.debug(`${file.name} exists - updating it`);
await updateFile(
config.repoName,
config.repository,
branchName,
file.name,
file.contents,
@ -521,7 +526,7 @@ async function commitFilesToBranch(
} else {
logger.debug(`Creating file ${file.name}`);
await createFile(
config.repoName,
config.repository,
branchName,
file.name,
file.contents,
@ -535,7 +540,7 @@ async function commitFilesToBranch(
async function getCommitMessages() {
logger.debug('getCommitMessages');
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);
} catch (err) {
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}`);
}
async function initRepo(repoName, token, endpoint) {
logger.debug(`initRepo("${repoName}")`);
async function initRepo({ repository, token, endpoint }) {
logger.debug(`initRepo("${repository}")`);
vstsHelper.setTokenAndEndpoint(token, endpoint);
config.repoName = repoName;
config.repository = repository;
config.fileList = null;
config.prList = null;
const repos = await vstsApi.gitApi().getRepositories();
const names = vstsHelper.getProjectAndRepo(repoName);
const names = vstsHelper.getProjectAndRepo(repository);
const repo = repos.filter(
c =>
c.name.toLowerCase() === names.repo.toLowerCase() &&
@ -71,11 +71,11 @@ async function initRepo(repoName, token, endpoint) {
config.privateRepo = true;
config.isFork = false;
config.owner = '?owner?';
logger.debug(`${repoName} owner = ${config.owner}`);
logger.debug(`${repository} owner = ${config.owner}`);
// Use default branch as PR target unless later overridden
config.defaultBranch = repo.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);
// Todo VSTS: Get Merge method

View file

@ -122,17 +122,17 @@ async function getVSTSBranchObj(repoId, branchName, from) {
* @param {string} filePath
* @param {string} fileContent
* @param {string} repoId
* @param {string} repoName
* @param {string} repository
* @param {string} branchName
*/
async function getChanges(files, repoId, repoName, branchName) {
async function getChanges(files, repoId, repository, branchName) {
const changes = [];
for (const file of files) {
// Add or update
let changeType = 1;
const fileAlreadyThere = await getFile(
repoId,
repoName,
repository,
file.name,
branchName
);
@ -158,11 +158,11 @@ async function getChanges(files, repoId, repoName, branchName) {
/**
* if no branchName, look globaly
* @param {string} repoId
* @param {string} repoName
* @param {string} repository
* @param {string} filePath
* @param {string} branchName
*/
async function getFile(repoId, repoName, filePath, branchName) {
async function getFile(repoId, repository, filePath, branchName) {
logger.trace(`getFile(filePath=${filePath}, branchName=${branchName})`);
const item = await vstsApi.gitApi().getItemText(
repoId,
@ -288,7 +288,7 @@ function getProjectAndRepo(str) {
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);
throw new Error(msg);
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -157,7 +157,7 @@ describe('platform/vsts/helpers', () => {
},
],
'123',
'repoName',
'repository',
'branchName'
);
expect(res).toMatchSnapshot();
@ -175,7 +175,7 @@ describe('platform/vsts/helpers', () => {
},
],
'123',
'repoName',
'repository',
'branchName'
);
expect(res).toMatchSnapshot();
@ -204,7 +204,7 @@ describe('platform/vsts/helpers', () => {
const res = await vstsHelper.getFile(
'123',
'repoName',
'repository',
'./myFilePath/test',
'branchName'
);
@ -232,7 +232,7 @@ describe('platform/vsts/helpers', () => {
const res = await vstsHelper.getFile(
'123',
'repoName',
'repository',
'./myFilePath/test',
'branchName'
);
@ -260,7 +260,7 @@ describe('platform/vsts/helpers', () => {
const res = await vstsHelper.getFile(
'123',
'repoName',
'repository',
'./myFilePath/test',
'branchName'
);
@ -276,7 +276,7 @@ describe('platform/vsts/helpers', () => {
const res = await vstsHelper.getFile(
'123',
'repoName',
'repository',
'./myFilePath/test',
'branchName'
);
@ -350,7 +350,7 @@ describe('platform/vsts/helpers', () => {
err = error;
}
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'!`
);
});
});