Something went wrong. Try again.
Mirroring: https://github.com/MunifTanjim/scripts.sh
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import assert from "assert";import { CacheFile } from "./cache.mjs";import { Logger } from "./logger.mjs";
export class GitLab { #baseUrl = "https://gitlab.com/api/v4"; #cache;
constructor({ id }) { this.id = id.trim(); assert(Boolean(this.id), "missing id");
this.#cache = new CacheFile(`gitlab/${this.id}`); }
log = new Logger(chalk.bgYellowBright.black.bold(" gitlab "));
#verifyToken = async () => { this.log.info("Checking Token validity...");
const { ok, data } = await this.api("/user");
if (ok) { this.log.info(`Authenticated as: ${data.username}`); } else { this.log.error(data.message); }
return ok; };
#ensureToken = async () => { const cache = await this.#cache.read();
if (cache.content.token) { const valid = await this.#verifyToken(); if (valid) { return; } }
this.log.log("For creating Personal Access Token, visit:"); this.log.log( ` https://gitlab.com/-/user_settings/personal_access_tokens/legacy/new?name=${os.hostname()}:cli:${ this.id }&scopes=api,read_user` );
cache.content.token = await question( this.log.fmt("input", "Enter API Token: ") );
const valid = await this.#verifyToken(); if (valid) { return await this.#cache.write(); }
cache.content.token = null; return await this.#ensureToken(); };
init = async () => { await this.#ensureToken(); return this; };
api = async (endpoint, options = {}) => { const [, method, path] = endpoint.match(/^(?:([A-Z]+) )?(\/.+)$/); /** @type RequestInfo */ const request = { url: `${this.#baseUrl}${path}`, method, headers: { "private-token": `${this.#cache.content.token}`, "content-type": "application/json", }, ...options, };
if (request.body) { request.body = JSON.stringify(request.body); }
const response = await fetch(request.url, request);
const { ok, status } = response; const data = status === 204 ? null : /application\/json/.test(response.headers.get("content-type")) ? await response.json() : await response.text();
return { ok, status, data }; };}