Skip to content

Commit

Permalink
refactor(azure): Extract more utils from platform helper (#9443)
Browse files Browse the repository at this point in the history
  • Loading branch information
zharinov committed Apr 8, 2021
1 parent 4262d40 commit e6537da
Show file tree
Hide file tree
Showing 9 changed files with 162 additions and 163 deletions.
34 changes: 0 additions & 34 deletions lib/platform/azure/__snapshots__/azure-helper.spec.ts.snap
Expand Up @@ -24,20 +24,6 @@ Object {

exports[`platform/azure/helpers getFile should return the file content because it is not a json 1`] = `"{\\"hello\\"= \\"test\\"}"`;

exports[`platform/azure/helpers getProjectAndRepo should return the object with project and repo 1`] = `
Object {
"project": "prjName",
"repo": "myRepoName",
}
`;

exports[`platform/azure/helpers getProjectAndRepo should return the object with same strings 1`] = `
Object {
"project": "myRepoName",
"repo": "myRepoName",
}
`;

exports[`platform/azure/helpers getRef should get the ref with full ref name 1`] = `
Array [
Object {
Expand All @@ -53,23 +39,3 @@ Array [
},
]
`;

exports[`platform/azure/helpers getStorageExtraCloneOpts should configure basic auth 1`] = `
Object {
"-c": "http.extraheader=AUTHORIZATION: basic dXNlcjpwYXNz",
}
`;

exports[`platform/azure/helpers getStorageExtraCloneOpts should configure bearer token 1`] = `
Object {
"-c": "http.extraheader=AUTHORIZATION: bearer token",
}
`;

exports[`platform/azure/helpers getStorageExtraCloneOpts should configure personal access token 1`] = `
Object {
"-c": "http.extraheader=AUTHORIZATION: basic OjEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=",
}
`;

exports[`platform/azure/helpers max4000Chars should be the same 1`] = `"Hello"`;
10 changes: 5 additions & 5 deletions lib/platform/azure/__snapshots__/index.spec.ts.snap
Expand Up @@ -199,8 +199,6 @@ Object {
}
`;

exports[`platform/azure massageMarkdown(input) returns updated pr body 1`] = `"https://github.com/foo/bar/issues/5 plus also [a link](https://github.com/foo/bar/issues/5)"`;

exports[`platform/azure getRepos() should return an array of repos 1`] = `
Array [
Array [],
Expand Down Expand Up @@ -233,11 +231,13 @@ Object {
}
`;

exports[`platform/azure massageMarkdown(input) returns updated pr body 1`] = `"https://github.com/foo/bar/issues/5 plus also [a link](https://github.com/foo/bar/issues/5)"`;

exports[`platform/azure updatePr(prNo, title, body) should close the PR 1`] = `
Array [
Array [
Object {
"description": undefined,
"description": "Hello world again",
"status": 2,
"title": "The New Title",
},
Expand All @@ -258,7 +258,7 @@ Array [
],
Array [
Object {
"description": undefined,
"description": "Hello world again",
"title": "The New Title",
},
"1",
Expand All @@ -271,7 +271,7 @@ exports[`platform/azure updatePr(prNo, title, body) should update the PR 1`] = `
Array [
Array [
Object {
"description": undefined,
"description": "Hello world again",
"title": "The New Title",
},
"1",
Expand Down
34 changes: 34 additions & 0 deletions lib/platform/azure/__snapshots__/util.spec.ts.snap
@@ -1,5 +1,19 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`platform/azure/helpers getProjectAndRepo should return the object with project and repo 1`] = `
Object {
"project": "prjName",
"repo": "myRepoName",
}
`;

exports[`platform/azure/helpers getProjectAndRepo should return the object with same strings 1`] = `
Object {
"project": "myRepoName",
"repo": "myRepoName",
}
`;

exports[`platform/azure/helpers getRenovatePRFormat should be formated (closed v2) 1`] = `
Object {
"body": undefined,
Expand Down Expand Up @@ -56,3 +70,23 @@ Object {
"targetBranch": undefined,
}
`;

exports[`platform/azure/helpers getStorageExtraCloneOpts should configure basic auth 1`] = `
Object {
"-c": "http.extraheader=AUTHORIZATION: basic dXNlcjpwYXNz",
}
`;

exports[`platform/azure/helpers getStorageExtraCloneOpts should configure bearer token 1`] = `
Object {
"-c": "http.extraheader=AUTHORIZATION: bearer token",
}
`;

exports[`platform/azure/helpers getStorageExtraCloneOpts should configure personal access token 1`] = `
Object {
"-c": "http.extraheader=AUTHORIZATION: basic OjEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=",
}
`;

exports[`platform/azure/helpers max4000Chars should be the same 1`] = `"Hello"`;
55 changes: 0 additions & 55 deletions lib/platform/azure/azure-helper.spec.ts
Expand Up @@ -13,26 +13,6 @@ describe('platform/azure/helpers', () => {
azureApi = require('./azure-got-wrapper');
});

describe('getStorageExtraCloneOpts', () => {
it('should configure basic auth', () => {
const res = azureHelper.getStorageExtraCloneOpts({
username: 'user',
password: 'pass',
});
expect(res).toMatchSnapshot();
});
it('should configure personal access token', () => {
const res = azureHelper.getStorageExtraCloneOpts({
token: '1234567890123456789012345678901234567890123456789012',
});
expect(res).toMatchSnapshot();
});
it('should configure bearer token', () => {
const res = azureHelper.getStorageExtraCloneOpts({ token: 'token' });
expect(res).toMatchSnapshot();
});
});

describe('getRef', () => {
it('should get the ref with short ref name', async () => {
azureApi.gitApi.mockImplementationOnce(
Expand Down Expand Up @@ -203,21 +183,6 @@ describe('platform/azure/helpers', () => {
});
});

describe('max4000Chars', () => {
it('should be the same', () => {
const res = azureHelper.max4000Chars('Hello');
expect(res).toMatchSnapshot();
});
it('should be truncated', () => {
let str = '';
for (let i = 0; i < 5000; i += 1) {
str += 'a';
}
const res = azureHelper.max4000Chars(str);
expect(res).toHaveLength(3999);
});
});

describe('getCommitDetails', () => {
it('should get commit details', async () => {
azureApi.gitApi.mockImplementationOnce(
Expand All @@ -233,26 +198,6 @@ describe('platform/azure/helpers', () => {
});
});

describe('getProjectAndRepo', () => {
it('should return the object with same strings', () => {
const res = azureHelper.getProjectAndRepo('myRepoName');
expect(res).toMatchSnapshot();
});
it('should return the object with project and repo', () => {
const res = azureHelper.getProjectAndRepo('prjName/myRepoName');
expect(res).toMatchSnapshot();
});
it('should return an error', () => {
expect(() =>
azureHelper.getProjectAndRepo('prjName/myRepoName/blalba')
).toThrow(
Error(
`prjName/myRepoName/blalba can be only structured this way : 'repository' or 'projectName/repository'!`
)
);
});
});

describe('getMergeMethod', () => {
it('should default to NoFastForward', async () => {
azureApi.policyApi.mockImplementationOnce(
Expand Down
55 changes: 0 additions & 55 deletions lib/platform/azure/azure-helper.ts
Expand Up @@ -4,9 +4,6 @@ import {
GitRef,
} from 'azure-devops-node-api/interfaces/GitInterfaces';
import { logger } from '../../logger';
import { HostRule } from '../../types';
import { GitOptions } from '../../types/git';
import { add } from '../../util/sanitize';
import * as azureApi from './azure-got-wrapper';
import {
getBranchNameWithoutRefsPrefix,
Expand All @@ -17,29 +14,6 @@ import {

const mergePolicyGuid = 'fa4e907d-c16b-4a4c-9dfa-4916e5d171ab'; // Magic GUID for merge strategy policy configurations

function toBase64(from: string): string {
return Buffer.from(from).toString('base64');
}

export function getStorageExtraCloneOpts(config: HostRule): GitOptions {
let authType: string;
let authValue: string;
if (!config.token && config.username && config.password) {
authType = 'basic';
authValue = toBase64(`${config.username}:${config.password}`);
} else if (config.token.length === 52) {
authType = 'basic';
authValue = toBase64(`:${config.token}`);
} else {
authType = 'bearer';
authValue = config.token;
}
add(authValue);
return {
'-c': `http.extraheader=AUTHORIZATION: ${authType} ${authValue}`,
};
}

export async function getRefs(
repoId: string,
branchName?: string
Expand Down Expand Up @@ -123,13 +97,6 @@ export async function getFile(
return null; // no file found
}

export function max4000Chars(str: string): string {
if (str && str.length >= 4000) {
return str.substring(0, 3999);
}
return str;
}

export async function getCommitDetails(
commit: string,
repoId: string
Expand All @@ -140,28 +107,6 @@ export async function getCommitDetails(
return results;
}

export function getProjectAndRepo(
str: string
): { project: string; repo: string } {
logger.trace(`getProjectAndRepo(${str})`);
const strSplit = str.split(`/`);
if (strSplit.length === 1) {
return {
project: str,
repo: str,
};
}
if (strSplit.length === 2) {
return {
project: strSplit[0],
repo: strSplit[1],
};
}
const msg = `${str} can be only structured this way : 'repository' or 'projectName/repository'!`;
logger.error(msg);
throw new Error(msg);
}

export async function getMergeMethod(
repoId: string,
project: string,
Expand Down
14 changes: 5 additions & 9 deletions lib/platform/azure/index.spec.ts
Expand Up @@ -128,13 +128,13 @@ describe('platform/azure', () => {
({
getRepositories: jest.fn(() => [
{
name: 'some-repo',
name: 'repo',
id: '1',
privateRepo: true,
isFork: false,
defaultBranch: 'defBr',
project: {
name: 'some-repo',
name: 'some',
},
},
{
Expand All @@ -146,10 +146,6 @@ describe('platform/azure', () => {
]),
} as any)
);
azureHelper.getProjectAndRepo.mockImplementationOnce(() => ({
project: 'some-repo',
repo: 'some-repo',
}));

if (is.string(args)) {
return azure.initRepo({
Expand All @@ -166,7 +162,7 @@ describe('platform/azure', () => {
describe('initRepo', () => {
it(`should initialise the config for a repo`, async () => {
const config = await initRepo({
repository: 'some-repo',
repository: 'some/repo',
});
expect(azureApi.gitApi.mock.calls).toMatchSnapshot();
expect(config).toMatchSnapshot();
Expand Down Expand Up @@ -479,12 +475,12 @@ describe('platform/azure', () => {
});
describe('getBranchStatus(branchName, requiredStatusChecks)', () => {
it('return success if requiredStatusChecks null', async () => {
await initRepo('some-repo');
await initRepo('some/repo');
const res = await azure.getBranchStatus('somebranch', null);
expect(res).toEqual(BranchStatus.green);
});
it('return failed if unsupported requiredStatusChecks', async () => {
await initRepo('some-repo');
await initRepo('some/repo');
const res = await azure.getBranchStatus('somebranch', ['foo']);
expect(res).toEqual(BranchStatus.red);
});
Expand Down
11 changes: 7 additions & 4 deletions lib/platform/azure/index.ts
Expand Up @@ -40,7 +40,10 @@ import {
getGitStatusContextCombinedName,
getGitStatusContextFromCombinedName,
getNewBranchName,
getProjectAndRepo,
getRenovatePRFormat,
getStorageExtraCloneOpts,
max4000Chars,
streamToString,
} from './util';

Expand Down Expand Up @@ -131,7 +134,7 @@ export async function initRepo({
config = { repository } as Config;
const azureApiGit = await azureApi.gitApi();
const repos = await azureApiGit.getRepositories();
const names = azureHelper.getProjectAndRepo(repository);
const names = getProjectAndRepo(repository);
const repo = repos.filter(
(c) =>
c.name.toLowerCase() === names.repo.toLowerCase() &&
Expand Down Expand Up @@ -170,7 +173,7 @@ export async function initRepo({
...config,
localDir,
url,
extraCloneOpts: azureHelper.getStorageExtraCloneOpts(opts),
extraCloneOpts: getStorageExtraCloneOpts(opts),
gitAuthorName: global.gitAuthor?.name,
gitAuthorEmail: global.gitAuthor?.email,
cloneSubmodules,
Expand Down Expand Up @@ -373,7 +376,7 @@ export async function createPr({
}: CreatePRConfig): Promise<Pr> {
const sourceRefName = getNewBranchName(sourceBranch);
const targetRefName = getNewBranchName(targetBranch);
const description = azureHelper.max4000Chars(sanitize(body));
const description = max4000Chars(sanitize(body));
const azureApiGit = await azureApi.gitApi();
const workItemRefs = [
{
Expand Down Expand Up @@ -434,7 +437,7 @@ export async function updatePr({
};

if (body) {
objToUpdate.description = azureHelper.max4000Chars(sanitize(body));
objToUpdate.description = max4000Chars(sanitize(body));
}

if (state === PrState.Open) {
Expand Down

0 comments on commit e6537da

Please sign in to comment.