From 0fefd1dc699331d839c0376e2b2c3824cb2ff666 Mon Sep 17 00:00:00 2001 From: Munif Tanjim Date: Wed, 22 Mar 2023 21:38:13 +0600 Subject: [PATCH] update git-mirror --- git-mirror | 190 ++++++++++++++++++++++++++++++++--------- zx/gitlab.mjs | 10 +-- zx/jetbrains-space.mjs | 119 ++++++++++++++++++++++++++ 3 files changed, 276 insertions(+), 43 deletions(-) create mode 100644 zx/jetbrains-space.mjs diff --git a/git-mirror b/git-mirror index 40f848b..75c0ffe 100755 --- a/git-mirror +++ b/git-mirror @@ -3,16 +3,17 @@ import { URL } from "url"; import { GitLab } from "./zx/gitlab.mjs"; +import { JetBrainsSpace } from "./zx/jetbrains-space.mjs"; $.verbose = false; -const askBool = async (prompt) => { +const ask_bool = async (prompt) => { return await question(`${prompt} [y/N] `).then((answer) => { - return answer.toLowerCase() == 'y'; - }) -} + return answer.toLowerCase() == "y"; + }); +}; -async function getRepoInfo() { +async function get_repo_info() { let ret; ret = await $`git branch --show-current`; @@ -59,26 +60,29 @@ async function getRepoInfo() { }; } -async function refreshRepoInfo(repo) { - Object.assign(repo, await getRepoInfo()); +async function refresh_repo_info(repo) { + Object.assign(repo, await get_repo_info()); } -async function ensureGitMirrorRemote(repo, name) { +async function ensure_git_mirror_remote(repo, name, remote_url) { + const url = new URL(remote_url); + if ( - repo.remote.origin.url.host === "gitlab.com" || - repo.remote["origin-gitlab"] + repo.remote.origin.url.host === url.host || + repo.remote[`origin-${name}`] ) { return; } - await $`git remote add origin-${name} https://gitlab.com/${repo.project}.git`; - await refreshRepoInfo(repo); + await $`git remote add origin-${name} ${url.href}`; + + await refresh_repo_info(repo); } -async function init(repo) { - const gitlab = await new GitLab({ name: "create-git-mirror" }).init(); +async function init_gitlab(repo) { + const gitlab = await new GitLab({ id: "git-mirror" }).init(); - const getGitlabMirrorProjectSettings = (repo) => ({ + const get_mirror_project_settings = () => ({ description: `Mirroring: ${repo.remote.origin.url.href}`, analytics_access_level: "disabled", @@ -96,17 +100,17 @@ async function init(repo) { wiki_access_level: "disabled", }); - async function createGitlabMirror(repo) { + async function create_mirror() { gitlab.log.info(`Creating project: ${repo.project}...`); - const isPublic = await askBool("Make project public?"); + const isPublic = await ask_bool("Make project public?"); const res = await gitlab.api("POST /projects", { body: { name: repo.name, import_url: repo.remote.origin.url.href, - visibility: isPublic ? 'public' : 'private', - ...getGitlabMirrorProjectSettings(repo), + visibility: isPublic ? "public" : "private", + ...get_mirror_project_settings(repo), }, }); @@ -118,11 +122,9 @@ async function init(repo) { } } - async function updateGitlabMirror(project) { + async function update_mirror(project) { const res = await gitlab.api(`PUT /projects/${project.id}`, { - body: { - ...getGitlabMirrorProjectSettings(repo), - }, + body: get_mirror_project_settings(), }); if (!res.ok) { @@ -130,21 +132,21 @@ async function init(repo) { } } - async function ensureGitlabMirror(repo) { + async function ensure_mirror() { const res = await gitlab.api( `/projects/${encodeURIComponent(repo.project)}` ); if (res.ok) { - await updateGitlabMirror(res.data); + await update_mirror(res.data); gitlab.log.info(`Project Found: ${repo.project}`); return; } - await createGitlabMirror(repo); + await create_mirror(); } - async function removeGitlabMirrorBranchProtection(repo) { + async function remove_mirror_branch_protection() { const res = await gitlab.api( `/projects/${encodeURIComponent(repo.project)}/protected_branches` ); @@ -159,28 +161,140 @@ async function init(repo) { } } - await ensureGitlabMirror(repo); + await ensure_mirror(); + + await remove_mirror_branch_protection(); + + const remote_url = `https://gitlab.com/${repo.project}.git`; + await ensure_git_mirror_remote(repo, "gitlab", remote_url); +} + +async function init_jetbrains_space(repo) { + const space = await new JetBrainsSpace({ + id: "git-mirror", + site: "muniftanjim", + }).init(); + + const project_key = "key:PERSONAL"; + const base_url = `/projects/${project_key}/repositories/${repo.name}`; + + const repo_description = `Mirroring: ${repo.remote.origin.url.href}`; + const get_mirror_repository_settings = () => ({ + settings: { + mirror: { + version: "", + url: `https://github.com/${repo.project}.git`, + detachHEAD: false, + fetchPeriodically: true, + fetchBeforeGitCall: true, + }, + }, + }); + + async function create_mirror() { + space.log.info(`Creating project: ${repo.name}...`); + + const { settings } = get_mirror_repository_settings(repo); + const res = await space.api(`POST ${base_url}/migrate`, { + body: { + description: repo_description, + remote: { + url: settings.mirror.url, + }, + mirror: { + syncPeriodically: settings.mirror.fetchPeriodically, + syncOnFetch: settings.mirror.fetchBeforeGitCall, + }, + }, + }); + + if (res.ok) { + space.log.info(`Created project: ${repo.name}...`); + } else { + space.log.info(`Failed to create project: ${repo.name}...`); + throw res; + } + } + + async function update_mirror() { + let res = await space.api(`POST ${base_url}/settings`, { + body: get_mirror_repository_settings(repo), + }); + + if (!res.ok) { + throw res; + } + + res = await space.api(`POST ${base_url}/description`, { + body: { description: repo_description }, + }); + + if (!res.ok) { + throw res; + } + } + + async function ensure_mirror() { + const res = await space.api(base_url); + + if (res.ok) { + await update_mirror(); + space.log.info(`Repository Found: ${res.data.name}`); + return; + } + + await create_mirror(); + } + + async function get_remote_url() { + const res = await space.api(`${base_url}/url`); + if (!res.ok) { + throw res; + } + return res.data.httpUrl; + } + + await ensure_mirror(); + + const remote_url = await get_remote_url(); + await ensure_git_mirror_remote(repo, "jetbrains-space", remote_url); +} - await removeGitlabMirrorBranchProtection(repo); +const REMOTE_SERVICE = { + gitlab: { + init: init_gitlab, + has_auto_sync: false, + }, + ["jetbrains-space"]: { + init: init_jetbrains_space, + has_auto_sync: true, + }, +}; - await ensureGitMirrorRemote(repo, "gitlab"); +async function init(repo) { + for (const remote of Object.values(REMOTE_SERVICE)) { + await remote.init(repo); + } } async function sync(repo) { $.verbose = true; - for (const remote of Object.keys(repo.remote)) { - if (!/^origin-[a-z]+$/.test(remote)) { + for (const remote of Object.keys(REMOTE_SERVICE)) { + if ( + !repo.remote[`origin-${remote}`] || + REMOTE_SERVICE[remote].has_auto_sync + ) { continue; } - await $`git push ${remote} --force --all --follow-tags`; + await $`git push origin-${remote} --force --all --follow-tags`; // push non-annotated tags - await $`git push ${remote} --force --tags`; + await $`git push origin-${remote} --force --tags`; } $.verbose = false; } -const repo = await getRepoInfo(); +const repo = await get_repo_info(); switch (argv._[0]) { case "init": { @@ -193,9 +307,9 @@ switch (argv._[0]) { } default: { if ( - !Object.keys(repo.remote).filter((remote) => - /^origin-[a-z]+$/.test(remote) - ).length + Object.keys(REMOTE_SERVICE).some( + (remote) => !repo.remote[`origin-${remote}`] + ) ) { await init(repo); } diff --git a/zx/gitlab.mjs b/zx/gitlab.mjs index 283d697..830a8f0 100644 --- a/zx/gitlab.mjs +++ b/zx/gitlab.mjs @@ -6,11 +6,11 @@ export class GitLab { #baseUrl = "https://gitlab.com/api/v4"; #cache; - constructor({ name }) { - this.name = name.trim(); - assert(Boolean(this.name), "missing name"); + constructor({ id }) { + this.id = id.trim(); + assert(Boolean(this.id), "missing id"); - this.#cache = new CacheFile(`gitlab/${this.name}`); + this.#cache = new CacheFile(`gitlab/${this.id}`); } log = new Logger(chalk.bgYellowBright.black.bold.dim(" gitlab ")); @@ -42,7 +42,7 @@ export class GitLab { this.log.log("For creating Personal Access Token, visit:"); this.log.log( ` https://gitlab.com/-/profile/personal_access_tokens?name=${os.hostname()}:cli:${ - this.name + this.id }&scopes=api,read_user` ); diff --git a/zx/jetbrains-space.mjs b/zx/jetbrains-space.mjs new file mode 100644 index 0000000..7dae34b --- /dev/null +++ b/zx/jetbrains-space.mjs @@ -0,0 +1,119 @@ +import assert from "assert"; +import { CacheFile } from "./cache.mjs"; +import { Logger } from "./logger.mjs"; + +export class JetBrainsSpace { + #baseUrl; + #cache; + #site; + + #is_initialized; + + /** + * @param {{ id: string, site: string }} + */ + constructor({ id, site }) { + this.id = id.trim(); + assert(Boolean(this.id), "missing id"); + + this.#site = site.trim(); + if (!this.#site.includes(".")) { + this.#site = `${this.#site}.jetbrains.space`; + } + this.#baseUrl = `https://${this.#site}/api/http`; + + this.#cache = new CacheFile(`jetbrains-space/${site}---${this.id}`); + } + + log = new Logger(chalk.bgBlueBright.black.bold.dim(" space ")); + + #verifyToken = async () => { + this.log.info("Checking Token validity..."); + + const { ok, data } = await this.api( + "/team-directory/profiles/me?$fields=id,username" + ); + + if (ok) { + this.log.info(`Authenticated as: ${data.username}`); + } else { + this.log.error(data.error_description || data.error); + } + + 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 Token, visit:"); + this.log.log( + ` https://${this.#site}/m/me/authentication?tab=PermanentTokens` + ); + this.log.log(`Name: ${os.hostname()}:cli:${this.id}`); + this.log.log(`Permissions: Manage Git repositories, View project details`); + + cache.content.token = await question( + this.log.fmt("input", "Enter Token: ") + ); + + const valid = await this.#verifyToken(); + if (valid) { + return await this.#cache.write(); + } + + cache.content.token = null; + return await this.#ensureToken(); + }; + + init = async () => { + if (!this.#is_initialized) { + await this.#ensureToken(); + } + + this.#is_initialized = true; + return this; + }; + + /** + * @param {RequestInfo} endpoint + * @param {RequestInit=} options + */ + api = async (endpoint, options = {}) => { + const [, method, path] = endpoint.match(/^(?:([A-Z]+) )?(\/.+)$/); + /** @type RequestInfo */ + const request = { + url: `${this.#baseUrl}${path}`, + method, + headers: { + Authorization: `Bearer ${this.#cache.content.token}`, + Accept: "application/json", + "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 || response.headers.get("content-length") === "0" + ? null + : /application\/json/.test(response.headers.get("content-type")) + ? await response.json() + : await response.text(); + + return { ok, status, data }; + }; +} -- knotmirror 0.0.1