import type { GitProviderName, GitRemoteConfig } from './types' const DEFAULT_GIT_BRANCH = 'main' function getGitProviderOverride(): GitProviderName | undefined { const provider = process.env.GIT_PROVIDER?.trim().toLowerCase() if (!provider) return undefined if (provider !== 'github' && provider !== 'gitea') { throw new Error(`GIT_PROVIDER invalide: "${provider}"`) } return provider } function getGitToken() { const token = process.env.GIT_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim() if (!token) throw new Error('GIT_TOKEN non configure') return token } function cleanRepoName(repo: string) { return repo.replace(/\/+$/, '').replace(/\.git$/, '') } function resolveProvider(host: string): GitProviderName { const override = getGitProviderOverride() if (override) return override return host.toLowerCase() === 'github.com' ? 'github' : 'gitea' } function buildRemoteConfig(host: string, owner: string, repo: string, protocol = 'https:'): GitRemoteConfig { const provider = resolveProvider(host) const origin = `${protocol === 'http:' ? 'http' : 'https'}://${host}` return { apiBaseUrl: provider === 'github' ? 'https://api.github.com' : `${origin}/api/v1`, lfsBatchUrl: `${origin}/${owner}/${repo}.git/info/lfs/objects/batch`, owner, provider, repo, token: getGitToken(), username: process.env.GIT_USERNAME?.trim() || undefined, webUrl: `${origin}/${owner}/${repo}`, } } export function getGitBranch() { return process.env.GIT_BRANCH?.trim() || DEFAULT_GIT_BRANCH } export function readGitRemoteConfig(): GitRemoteConfig { const url = process.env.GIT_REPO_URL?.trim() if (!url) throw new Error('GIT_REPO_URL non configure') const shortMatch = url.match(/^([^/\s:]+)\/([^/\s]+)$/) if (shortMatch) { const providerOverride = getGitProviderOverride() if (providerOverride === 'gitea') { throw new Error('GIT_REPO_URL doit inclure le host pour Gitea') } return buildRemoteConfig('github.com', shortMatch[1], cleanRepoName(shortMatch[2])) } const scpLikeMatch = !url.includes('://') ? url.match(/^(?:[^@\s]+@)?([^:\s]+):([^/\s]+)\/([^/\s]+)$/) : null if (scpLikeMatch) { return buildRemoteConfig(scpLikeMatch[1], scpLikeMatch[2], cleanRepoName(scpLikeMatch[3])) } if (URL.canParse(url)) { const parsed = new URL(url) const pathParts = parsed.pathname .replace(/^\/+|\/+$/g, '') .split('/') .filter(Boolean) if ((parsed.protocol === 'https:' || parsed.protocol === 'http:' || parsed.protocol === 'ssh:') && pathParts.length >= 2) { return buildRemoteConfig(parsed.hostname, pathParts[0], cleanRepoName(pathParts[1]), parsed.protocol) } } throw new Error(`Format GIT_REPO_URL invalide: "${url}"`) }