refactor: adjust code to match eslint rules

This commit is contained in:
Rainer Killinger
2022-11-21 10:48:58 +01:00
parent 30492c03ca
commit 69fd8ff701
3 changed files with 181 additions and 182 deletions

View File

@@ -41,7 +41,7 @@ import {
* @param ms Number of milliseconds to wait
*/
export async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
@@ -120,20 +120,19 @@ export class Api {
* @param userId ID of the user
* @param accessLevel Access level for the new member in the scope
*/
public async addMember(scope: MembershipScope,
id: number,
userId: number,
accessLevel: AccessLevel): Promise<Member> {
return this.makeGitLabAPIRequest(
`${scope}/${id}/members`,
{
data: {
access_level: accessLevel,
user_id: userId,
},
method: 'POST',
public async addMember(
scope: MembershipScope,
id: number,
userId: number,
accessLevel: AccessLevel,
): Promise<Member> {
return this.makeGitLabAPIRequest(`${scope}/${id}/members`, {
data: {
access_level: accessLevel,
user_id: userId,
},
) as Promise<Member>;
method: 'POST',
}) as Promise<Member>;
}
/**
@@ -144,16 +143,13 @@ export class Api {
* @param description Description of the issue (can contain slash commands)
*/
public async createIssue(projectId: number, title: string, description: string): Promise<Issue> {
return this.makeGitLabAPIRequest(
`projects/${projectId}/issues`,
{
data: {
description: description,
title: title,
},
method: 'POST',
return this.makeGitLabAPIRequest(`projects/${projectId}/issues`, {
data: {
description: description,
title: title,
},
) as Promise<Issue>;
method: 'POST',
}) as Promise<Issue>;
}
/**
@@ -164,23 +160,25 @@ export class Api {
* @param description Description of the label to create
* @param color Color of the label to create
*/
public async createLabel(projectId: number, name: string, description?: string, color?: string): Promise<Label> {
public async createLabel(
projectId: number,
name: string,
description?: string,
color?: string,
): Promise<Label> {
let _color = '#000000';
if (typeof color !== 'string' || !/^#[0-9a-fA-F]{3,6}$/.test(color)) {
_color = '#000000';
}
return this.makeGitLabAPIRequest(
`projects/${projectId}/labels`,
{
data: {
color: _color,
description,
name,
},
method: 'POST',
return this.makeGitLabAPIRequest(`projects/${projectId}/labels`, {
data: {
color: _color,
description,
name,
},
) as Promise<Label>;
method: 'POST',
}) as Promise<Label>;
}
/**
@@ -204,15 +202,12 @@ export class Api {
* @param body Body of the note to create
*/
public async createNote(projectId: number, scope: Scope, iid: number, body: string): Promise<void> {
return this.makeGitLabAPIRequest(
`projects/${projectId}/${scope}/${iid}/notes`,
{
data: {
body,
},
method: 'POST',
return this.makeGitLabAPIRequest(`projects/${projectId}/${scope}/${iid}/notes`, {
data: {
body,
},
) as Promise<void>;
method: 'POST',
}) as Promise<void>;
}
/**
@@ -222,12 +217,9 @@ export class Api {
* @param name Name of the label to delete
*/
public async deleteLabel(projectId: number, name: string): Promise<void> {
return this.makeGitLabAPIRequest(
`projects/${projectId}/labels?name=${name}`,
{
method: 'DELETE',
},
) as Promise<void>;
return this.makeGitLabAPIRequest(`projects/${projectId}/labels?name=${name}`, {
method: 'DELETE',
}) as Promise<void>;
}
/**
@@ -253,18 +245,15 @@ export class Api {
newValues.color = undefined;
}
return this.makeGitLabAPIRequest(
`projects/${projectId}/labels`,
{
data: {
color: newValues.color,
description: newValues.description,
name: name,
new_name: newValues.name,
},
method: 'POST',
return this.makeGitLabAPIRequest(`projects/${projectId}/labels`, {
data: {
color: newValues.color,
description: newValues.description,
name: name,
new_name: newValues.name,
},
) as Promise<Label>;
method: 'POST',
}) as Promise<Label>;
}
/**
@@ -275,20 +264,19 @@ export class Api {
* @param userId ID of the user
* @param accessLevel Access level for the member in the scope
*/
public async editMember(scope: MembershipScope,
id: number,
userId: number,
accessLevel: AccessLevel): Promise<Member> {
return this.makeGitLabAPIRequest(
`${scope}/${id}/members`,
{
data: {
access_level: accessLevel,
user_id: userId,
},
method: 'PUT',
public async editMember(
scope: MembershipScope,
id: number,
userId: number,
accessLevel: AccessLevel,
): Promise<Member> {
return this.makeGitLabAPIRequest(`${scope}/${id}/members`, {
data: {
access_level: accessLevel,
user_id: userId,
},
) as Promise<Member>;
method: 'PUT',
}) as Promise<Member>;
}
/**
@@ -308,10 +296,13 @@ export class Api {
* @param commitish Commitish of the file
*/
public async getFile(projectId: number, filePath: string, commitish: string): Promise<unknown> {
const fileIdentifier = `${encodeURIComponent(filePath)
.replace('.', '%2E')}/raw?ref=${encodeURIComponent(commitish)}`;
const fileIdentifier = `${encodeURIComponent(filePath).replace('.', '%2E')}/raw?ref=${encodeURIComponent(
commitish,
)}`;
return this.makeGitLabAPIRequest(`projects/${projectId}/repository/files/${fileIdentifier}`) as Promise<unknown>;
return this.makeGitLabAPIRequest(
`projects/${projectId}/repository/files/${fileIdentifier}`,
) as Promise<unknown>;
}
/**
@@ -380,9 +371,13 @@ export class Api {
* @param projectId ID of the project the merge request belongs to
* @param mergeRequestIid IID of the merge request
*/
public async getMergeRequestApproval(projectId: number, mergeRequestIid: number): Promise<MergeRequestApproval> {
return this.makeGitLabAPIRequest(`/projects/${projectId}/merge_requests/${mergeRequestIid}/approvals`) as
Promise<MergeRequestApproval>;
public async getMergeRequestApproval(
projectId: number,
mergeRequestIid: number,
): Promise<MergeRequestApproval> {
return this.makeGitLabAPIRequest(
`/projects/${projectId}/merge_requests/${mergeRequestIid}/approvals`,
) as Promise<MergeRequestApproval>;
}
/**
@@ -404,9 +399,11 @@ export class Api {
* @param id ID of the group or project
* @param state State to filter the merge requests by
*/
public async getMergeRequests(scope: MembershipScope,
id: number,
state: MergeRequestState | MergeRequestState[]): Promise<MergeRequest[]> {
public async getMergeRequests(
scope: MembershipScope,
id: number,
state: MergeRequestState | MergeRequestState[],
): Promise<MergeRequest[]> {
let _state = state;
// join a list of states with commas
@@ -414,7 +411,9 @@ export class Api {
_state = state.join(',') as MergeRequestState;
}
return this.makeGitLabAPIRequest(`${scope}/${id}/merge_requests?state=${_state}`) as Promise<MergeRequest[]>;
return this.makeGitLabAPIRequest(`${scope}/${id}/merge_requests?state=${_state}`) as Promise<
MergeRequest[]
>;
}
/**
@@ -433,7 +432,9 @@ export class Api {
* @param issue Issue to get notes for
*/
public async getNotes(projectId: number, issue: Issue) {
return this.makeGitLabAPIRequest(`/projects/${projectId}/issues/${issue.iid}/notes?sort=asc`) as Promise<Note[]>;
return this.makeGitLabAPIRequest(`/projects/${projectId}/issues/${issue.iid}/notes?sort=asc`) as Promise<
Note[]
>;
}
/**
@@ -460,9 +461,7 @@ export class Api {
* @param projectId ID of the project to get the tags for
*/
public async getTags(projectId: number): Promise<Tag[]> {
return this.makeGitLabAPIRequest(
`projects/${projectId}/repository/tags`,
) as Promise<Tag[]>;
return this.makeGitLabAPIRequest(`projects/${projectId}/repository/tags`) as Promise<Tag[]>;
}
/**
@@ -476,6 +475,7 @@ export class Api {
const _url = url.replace(/^\/+/g, '');
const _options: Required<ApiRequestOptions> = {
// eslint-disable-next-line unicorn/no-null
data: null,
method: 'GET',
retryOnAnyError: false,
@@ -488,7 +488,7 @@ export class Api {
}
let concatenator = '&';
if (_url.indexOf('?') === -1) {
if (!_url.includes('?')) {
concatenator = '?';
}
@@ -498,35 +498,37 @@ export class Api {
while (++currentPage <= totalPages) {
if (currentPage > 1) {
Logger.info(`Automatically paging call to '${_url}'... Getting page ${currentPage} of ${totalPages}.`);
Logger.info(
`Automatically paging call to '${_url}'... Getting page ${currentPage} of ${totalPages}.`,
);
}
let body;
let tries = 0;
while (typeof body === 'undefined' && tries++ < _options.tries) {
while (body === undefined && tries++ < _options.tries) {
try {
const requestUrl = `${_url}${concatenator}page=${currentPage}&per_page=100`;
body = await request(`${this.rootUrl}${requestUrl}`, {
form: _options.data !== null ? _options.data : undefined,
form: _options.data === null ? undefined : _options.data,
headers: {'PRIVATE-TOKEN': this.privateToken},
json: true,
method: _options.method,
timeout: 60000,
timeout: 60_000,
followAllRedirects: true,
transform: (bodyToTransform, response) => {
const xTotalPages = response.headers['x-total-pages'];
if (typeof xTotalPages === 'string') {
totalPages = parseInt(xTotalPages, 10);
totalPages = Number.parseInt(xTotalPages, 10);
}
return bodyToTransform;
},
});
} catch (error) {
if (error.message.includes('not responding') || _options.retryOnAnyError) {
if ((error as Error).message.includes('not responding') || _options.retryOnAnyError) {
const seconds = 5;
Logger.warn(`GitLab was not responding. Waiting ${seconds}s and retrying...`);
@@ -548,13 +550,10 @@ export class Api {
return;
}
if (typeof apiResult !== 'undefined' && Array.isArray(apiResult) && currentPage > 1) {
// add items to previously fetched items
apiResult = apiResult.concat(body);
} else {
// set (initial) result
apiResult = body;
}
apiResult =
apiResult !== undefined && Array.isArray(apiResult) && currentPage > 1
? (apiResult = [...apiResult, ...body])
: (apiResult = body);
}
return apiResult;
@@ -614,12 +613,9 @@ export class Api {
*/
public async setMilestoneForIssue(issue: Issue, milestoneId: number): Promise<Issue> {
if (milestoneId === null) {
return this.makeGitLabAPIRequest(
`projects/${issue.project_id}/issues/${issue.iid}?milestone_id=`,
{
method: 'PUT',
},
) as Promise<Issue>;
return this.makeGitLabAPIRequest(`projects/${issue.project_id}/issues/${issue.iid}?milestone_id=`, {
method: 'PUT',
}) as Promise<Issue>;
}
return this.makeGitLabAPIRequest(

View File

@@ -18,84 +18,75 @@ import {AddLogLevel} from '@openstapps/logger/lib/transformations/add-log-level'
import {Colorize} from '@openstapps/logger/lib/transformations/colorize';
import {Command} from 'commander';
import {readFileSync} from 'fs';
import {join} from 'path';
import path from 'path';
import {Api, ApiRequestOptions} from './api';
import {Issue, IssueState, MembershipScope, Scope} from './types';
Logger.setTransformations([
new AddLogLevel(),
new Colorize(),
]);
Logger.setTransformations([new AddLogLevel(), new Colorize()]);
const pkgJson = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'))
.toString());
// eslint-disable-next-line unicorn/prefer-module
const packageJson = JSON.parse(readFileSync(path.join(__dirname, '..', 'package.json')).toString());
const commander = new Command('openstapps-gitlab-api');
commander
.version(pkgJson.version);
commander.version(packageJson.version);
commander
.option('-t, --token [token]', 'GitLab API token', process.env.GITLAB_PRIVATE_TOKEN)
.option('-u, --url [url]', 'GitLab API URL', 'https://gitlab.com/api/v4/');
commander
.command('request <call> [method] [data]')
.action(async (call, method, data) => {
const options: ApiRequestOptions = {};
commander.command('request <call> [method] [data]').action(async (call, method, data) => {
const options: ApiRequestOptions = {};
if (method !== 'GET') {
options.method = method;
if (method !== 'GET') {
options.method = method;
}
if (data !== undefined) {
options.data = JSON.parse(data);
}
const api = new Api(commander.url, commander.token);
const result = await api.makeGitLabAPIRequest(call, options);
// eslint-disable-next-line no-console
console.log(result);
});
commander.command('batch-process <projectId> <action>').action(async (projectId, action) => {
if (!['close'].includes(action)) {
await Logger.error('Only "close" is supported as action.');
}
const api = new Api(commander.url, commander.token);
const issues = (await api.makeGitLabAPIRequest(`/projects/${projectId}/issues?state=opened`, {
retryOnAnyError: true,
tries: 10,
})) as Issue[];
Logger.log(`Fetched ${issues.length} issue(s).`);
await asyncPool(5, issues, async issue => {
if (action === 'close') {
Logger.info(`Closing issue #${issue.iid} of project '${projectId}': ${issue.title}.`);
await api.makeGitLabAPIRequest(`/projects/${projectId}/issues/${issue.iid}`, {
data: {
state_event: 'close',
},
method: 'PUT',
retryOnAnyError: true,
tries: 10,
});
}
if (typeof data !== 'undefined') {
options.data = JSON.parse(data);
}
const api = new Api(commander.url, commander.token);
const result = await api.makeGitLabAPIRequest(call, options);
// tslint:disable-next-line:no-console
console.log(result);
Logger.info(`Processed issue #${issue.iid} of project '${projectId}': ${issue.title}`);
});
commander
.command('batch-process <projectId> <action>')
.action(async (projectId, action) => {
if (!['close'].includes(action)) {
await Logger.error('Only "close" is supported as action.');
}
const api = new Api(commander.url, commander.token);
const issues = await api.makeGitLabAPIRequest(`/projects/${projectId}/issues?state=opened`, {
retryOnAnyError: true,
tries: 10,
}) as Issue[];
Logger.log(`Fetched ${issues.length} issue(s).`);
// tslint:disable-next-line:no-magic-numbers
await asyncPool(5, issues, async (issue) => {
if (action === 'close') {
Logger.info(`Closing issue #${issue.iid} of project '${projectId}': ${issue.title}.`);
await api.makeGitLabAPIRequest(`/projects/${projectId}/issues/${issue.iid}`, {
data: {
state_event: 'close',
},
method: 'PUT',
retryOnAnyError: true,
tries: 10,
});
}
// tslint:disable-next-line:no-console
Logger.info(`Processed issue #${issue.iid} of project '${projectId}': ${issue.title}`);
});
Logger.ok('Processed all issues.');
});
Logger.ok('Processed all issues.');
});
commander
.command('copy <projectId> <targetUrl> <targetToken> <targetProjectId>')
@@ -104,10 +95,10 @@ commander
const targetApi = new Api(targetUrl, targetToken);
// get all issues from project
const issues = await api.makeGitLabAPIRequest(`/projects/${projectId}/issues`, {
const issues = (await api.makeGitLabAPIRequest(`/projects/${projectId}/issues`, {
retryOnAnyError: true,
tries: 10,
}) as Issue[];
})) as Issue[];
// sort issues by their project specific ids
issues.sort((a, b) => {
@@ -117,17 +108,23 @@ commander
// get members of target project
const members = await targetApi.getMembers(MembershipScope.PROJECTS, targetProjectId);
let idx = 0;
let index = 0;
// tslint:disable-next-line:no-magic-numbers
await asyncPool(2, issues, async (issue) => {
await asyncPool(2, issues, async issue => {
// get notes of old issue
const notes = await api.getNotes(projectId, issue);
// create new issue
const newIssue = await targetApi.createIssue(targetProjectId, issue.title, issue.description === null ? '---' : `${issue.web_url}
const newIssue = await targetApi.createIssue(
targetProjectId,
issue.title,
issue.description === null
? '---'
: `${issue.web_url}
${issue.description}`);
${issue.description}`,
);
for (const note of notes) {
// skip system notes
@@ -136,9 +133,14 @@ ${issue.description}`);
}
// create new note in new issue for every note in issue
await targetApi.createNote(targetProjectId, Scope.ISSUES, newIssue.iid, `**${note.author.name} (@${note.author.username}):**
await targetApi.createNote(
targetProjectId,
Scope.ISSUES,
newIssue.iid,
`**${note.author.name} (@${note.author.username}):**
${note.body}`);
${note.body}`,
);
}
// close newly created issue if original is closed to
@@ -154,7 +156,7 @@ ${note.body}`);
}
// search for member in target group with same username
const assignee = members.find((member) => {
const assignee = members.find(member => {
if (issue.assignee === null) {
return false;
}
@@ -163,17 +165,18 @@ ${note.body}`);
});
// set assignee if usernames match
if (typeof assignee !== 'undefined') {
if (assignee !== undefined) {
await targetApi.setAssigneeForIssue(newIssue, assignee.id);
}
Logger.log(`Finished issue ${++idx} of ${issues.length}.`);
Logger.log(`Finished issue ${++index} of ${issues.length}.`);
});
});
commander
.parse(process.argv);
commander.parse(process.argv);
if (typeof commander.token !== 'string' || commander.token.length === 0) {
Logger.warn('You probably want to supply a GitLab token either via option or environment variable (GITLAB_PRIVATE_TOKEN).');
Logger.warn(
'You probably want to supply a GitLab token either via option or environment variable (GITLAB_PRIVATE_TOKEN).',
);
}

View File

@@ -309,7 +309,7 @@ export interface MergeRequest extends ThingWithTimeStats {
export interface MergeRequestApproval {
approvals_left: number;
approvals_required: number;
approved_by: Array<{ user: User; }>;
approved_by: Array<{user: User}>;
approver_groups: Group[];
approvers: User[];
created_at: string;