Files
gitops/ts/providers/classes.gitlabprovider.ts
2026-02-24 12:29:58 +00:00

276 lines
9.4 KiB
TypeScript

import type * as interfaces from '../../ts_interfaces/index.ts';
import { BaseProvider, type ITestConnectionResult, type IListOptions } from './classes.baseprovider.ts';
/**
* GitLab API v4 provider implementation
*/
export class GitLabProvider extends BaseProvider {
protected setAuthHeader(headers: Headers): void {
headers.set('PRIVATE-TOKEN', this.token);
if (!headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
}
async testConnection(): Promise<ITestConnectionResult> {
try {
const resp = await this.apiFetch('/api/v4/user');
if (!resp.ok) {
return { ok: false, error: `HTTP ${resp.status}: ${resp.statusText}` };
}
return { ok: true };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
async getProjects(opts?: IListOptions): Promise<interfaces.data.IProject[]> {
const page = opts?.page || 1;
const perPage = opts?.perPage || 50;
let url = `/api/v4/projects?page=${page}&per_page=${perPage}&order_by=updated_at&sort=desc&membership=true`;
if (opts?.search) {
url += `&search=${encodeURIComponent(opts.search)}`;
}
const resp = await this.apiFetch(url);
if (!resp.ok) throw new Error(`GitLab getProjects failed: ${resp.status}`);
const projects = await resp.json() as any[];
return projects.map((p) => this.mapProject(p));
}
async getGroups(opts?: IListOptions): Promise<interfaces.data.IGroup[]> {
const page = opts?.page || 1;
const perPage = opts?.perPage || 50;
let url = `/api/v4/groups?page=${page}&per_page=${perPage}&order_by=name&sort=asc`;
if (opts?.search) {
url += `&search=${encodeURIComponent(opts.search)}`;
}
const resp = await this.apiFetch(url);
if (!resp.ok) throw new Error(`GitLab getGroups failed: ${resp.status}`);
const groups = await resp.json() as any[];
return groups.map((g) => this.mapGroup(g));
}
// --- Project Secrets (CI/CD Variables) ---
async getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]> {
const resp = await this.apiFetch(`/api/v4/projects/${encodeURIComponent(projectId)}/variables`);
if (!resp.ok) throw new Error(`GitLab getProjectSecrets failed: ${resp.status}`);
const vars = await resp.json() as any[];
return vars.map((v) => this.mapVariable(v, 'project', projectId));
}
async createProjectSecret(
projectId: string,
key: string,
value: string,
): Promise<interfaces.data.ISecret> {
const resp = await this.apiFetch(`/api/v4/projects/${encodeURIComponent(projectId)}/variables`, {
method: 'POST',
body: JSON.stringify({ key, value, protected: false, masked: false }),
});
if (!resp.ok) throw new Error(`GitLab createProjectSecret failed: ${resp.status}`);
const v = await resp.json();
return this.mapVariable(v, 'project', projectId);
}
async updateProjectSecret(
projectId: string,
key: string,
value: string,
): Promise<interfaces.data.ISecret> {
const resp = await this.apiFetch(
`/api/v4/projects/${encodeURIComponent(projectId)}/variables/${encodeURIComponent(key)}`,
{
method: 'PUT',
body: JSON.stringify({ value }),
},
);
if (!resp.ok) throw new Error(`GitLab updateProjectSecret failed: ${resp.status}`);
const v = await resp.json();
return this.mapVariable(v, 'project', projectId);
}
async deleteProjectSecret(projectId: string, key: string): Promise<void> {
const resp = await this.apiFetch(
`/api/v4/projects/${encodeURIComponent(projectId)}/variables/${encodeURIComponent(key)}`,
{ method: 'DELETE' },
);
if (!resp.ok) throw new Error(`GitLab deleteProjectSecret failed: ${resp.status}`);
}
// --- Group Secrets (CI/CD Variables) ---
async getGroupSecrets(groupId: string): Promise<interfaces.data.ISecret[]> {
const resp = await this.apiFetch(`/api/v4/groups/${encodeURIComponent(groupId)}/variables`);
if (!resp.ok) throw new Error(`GitLab getGroupSecrets failed: ${resp.status}`);
const vars = await resp.json() as any[];
return vars.map((v) => this.mapVariable(v, 'group', groupId));
}
async createGroupSecret(
groupId: string,
key: string,
value: string,
): Promise<interfaces.data.ISecret> {
const resp = await this.apiFetch(`/api/v4/groups/${encodeURIComponent(groupId)}/variables`, {
method: 'POST',
body: JSON.stringify({ key, value, protected: false, masked: false }),
});
if (!resp.ok) throw new Error(`GitLab createGroupSecret failed: ${resp.status}`);
const v = await resp.json();
return this.mapVariable(v, 'group', groupId);
}
async updateGroupSecret(
groupId: string,
key: string,
value: string,
): Promise<interfaces.data.ISecret> {
const resp = await this.apiFetch(
`/api/v4/groups/${encodeURIComponent(groupId)}/variables/${encodeURIComponent(key)}`,
{
method: 'PUT',
body: JSON.stringify({ value }),
},
);
if (!resp.ok) throw new Error(`GitLab updateGroupSecret failed: ${resp.status}`);
const v = await resp.json();
return this.mapVariable(v, 'group', groupId);
}
async deleteGroupSecret(groupId: string, key: string): Promise<void> {
const resp = await this.apiFetch(
`/api/v4/groups/${encodeURIComponent(groupId)}/variables/${encodeURIComponent(key)}`,
{ method: 'DELETE' },
);
if (!resp.ok) throw new Error(`GitLab deleteGroupSecret failed: ${resp.status}`);
}
// --- Pipelines ---
async getPipelines(
projectId: string,
opts?: IListOptions,
): Promise<interfaces.data.IPipeline[]> {
const page = opts?.page || 1;
const perPage = opts?.perPage || 30;
const resp = await this.apiFetch(
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines?page=${page}&per_page=${perPage}&order_by=updated_at&sort=desc`,
);
if (!resp.ok) throw new Error(`GitLab getPipelines failed: ${resp.status}`);
const pipelines = await resp.json() as any[];
return pipelines.map((p) => this.mapPipeline(p, projectId));
}
async getPipelineJobs(
projectId: string,
pipelineId: string,
): Promise<interfaces.data.IPipelineJob[]> {
const resp = await this.apiFetch(
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/jobs`,
);
if (!resp.ok) throw new Error(`GitLab getPipelineJobs failed: ${resp.status}`);
const jobs = await resp.json() as any[];
return jobs.map((j) => this.mapJob(j, pipelineId));
}
async getJobLog(projectId: string, jobId: string): Promise<string> {
const resp = await this.apiFetch(
`/api/v4/projects/${encodeURIComponent(projectId)}/jobs/${jobId}/trace`,
{ headers: { Accept: 'text/plain' } },
);
if (!resp.ok) throw new Error(`GitLab getJobLog failed: ${resp.status}`);
return resp.text();
}
async retryPipeline(projectId: string, pipelineId: string): Promise<void> {
const resp = await this.apiFetch(
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/retry`,
{ method: 'POST' },
);
if (!resp.ok) throw new Error(`GitLab retryPipeline failed: ${resp.status}`);
}
async cancelPipeline(projectId: string, pipelineId: string): Promise<void> {
const resp = await this.apiFetch(
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/cancel`,
{ method: 'POST' },
);
if (!resp.ok) throw new Error(`GitLab cancelPipeline failed: ${resp.status}`);
}
// --- Mappers ---
private mapProject(p: any): interfaces.data.IProject {
return {
id: String(p.id),
name: p.name || '',
fullPath: p.path_with_namespace || '',
description: p.description || '',
defaultBranch: p.default_branch || 'main',
webUrl: p.web_url || '',
connectionId: this.connectionId,
visibility: p.visibility || 'private',
topics: p.topics || p.tag_list || [],
lastActivity: p.last_activity_at || '',
};
}
private mapGroup(g: any): interfaces.data.IGroup {
return {
id: String(g.id),
name: g.name || '',
fullPath: g.full_path || '',
description: g.description || '',
webUrl: g.web_url || '',
connectionId: this.connectionId,
visibility: g.visibility || 'private',
projectCount: g.projects?.length || 0,
};
}
private mapVariable(
v: any,
scope: 'project' | 'group',
scopeId: string,
): interfaces.data.ISecret {
return {
key: v.key || '',
value: v.value || '***',
protected: v.protected || false,
masked: v.masked || false,
scope,
scopeId,
connectionId: this.connectionId,
environment: v.environment_scope || '*',
};
}
private mapPipeline(p: any, projectId: string): interfaces.data.IPipeline {
return {
id: String(p.id),
projectId,
projectName: projectId,
connectionId: this.connectionId,
status: (p.status || 'pending') as interfaces.data.TPipelineStatus,
ref: p.ref || '',
sha: p.sha || '',
webUrl: p.web_url || '',
duration: p.duration || 0,
createdAt: p.created_at || '',
source: p.source || 'push',
};
}
private mapJob(j: any, pipelineId: string): interfaces.data.IPipelineJob {
return {
id: String(j.id),
pipelineId: String(pipelineId),
name: j.name || '',
stage: j.stage || '',
status: (j.status || 'pending') as interfaces.data.TPipelineStatus,
duration: j.duration || 0,
};
}
}