From c4d9b2dea4a019cc1fd7efad97a111d70020bfb7 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 18:18:45 +0100 Subject: [PATCH 1/3] fix(core): parse local diffs and repository URLs independently of git config and host - Local git diffs run with fixed prefixes, no color, no external diff, core.quotePath=false and LC_ALL=C; file list and stats come from --name-status -z and --numstat -z - One shared repo locator replaces six parsers for remotes, model links, model repos and PR/MR URLs, including ssh with port, git://, scp form, GitLab nested groups, Azure DevOps and Bitbucket Server paths - Self-hosted GitHub, GitLab and Bitbucket base URLs (with context paths) are honoured; GitHub Enterprise passes its base URL to Octokit - Model repo tokens are only sent over https - ADR-013 --- packages/cli/src/commands/check.ts | 2 +- packages/cli/src/commands/connections.ts | 2 +- packages/cli/src/utils/command-schemas.ts | 22 +- packages/core/src/adapters/likec4/adapter.ts | 2 +- .../core/src/adapters/structurizr/adapter.ts | 2 +- packages/core/src/adapters/url-utils.ts | 101 ----- packages/core/src/index.ts | 4 + packages/core/src/pipelines/validate.ts | 2 +- .../__tests__/change-request-url.test.ts | 118 ++++++ .../__tests__/platform-factory.test.ts | 15 + .../bitbucket/__tests__/reader.test.ts | 13 + .../core/src/platforms/bitbucket/reader.ts | 30 +- .../core/src/platforms/change-request-url.ts | 51 +++ .../platforms/github/__tests__/reader.test.ts | 15 +- packages/core/src/platforms/github/reader.ts | 42 +-- packages/core/src/platforms/github/writer.ts | 2 +- .../platforms/gitlab/__tests__/reader.test.ts | 13 + packages/core/src/platforms/gitlab/reader.ts | 34 +- .../core/src/platforms/platform-factory.ts | 32 +- .../src/utils/__tests__/diff-sections.test.ts | 84 +++++ .../src/utils/__tests__/git-diff-repo.test.ts | 118 ++++++ .../core/src/utils/__tests__/git-diff.test.ts | 87 +++-- .../src/utils/__tests__/model-source.test.ts | 95 +++++ .../src/utils/__tests__/repo-locator.test.ts | 354 ++++++++++++++++++ .../__tests__/repo-matching.test.ts} | 2 +- packages/core/src/utils/diff-sections.ts | 142 +++++++ packages/core/src/utils/git-diff.ts | 191 +++++----- packages/core/src/utils/model-source.ts | 143 ++++--- packages/core/src/utils/repo-locator.ts | 354 ++++++++++++++++++ .../adrs/013-single-repository-locator.md | 40 ++ .../docs/docs/contributing/adrs/index.md | 1 + .../docs/integrations/bitbucket-pipelines.md | 2 +- .../docs/docs/integrations/gitlab-ci.md | 2 +- .../content/docs/docs/integrations/index.md | 2 +- .../docs/docs/reference/cli-commands.md | 10 +- .../docs/docs/reference/configuration.md | 2 + 36 files changed, 1695 insertions(+), 436 deletions(-) delete mode 100644 packages/core/src/adapters/url-utils.ts create mode 100644 packages/core/src/platforms/__tests__/change-request-url.test.ts create mode 100644 packages/core/src/platforms/change-request-url.ts create mode 100644 packages/core/src/utils/__tests__/diff-sections.test.ts create mode 100644 packages/core/src/utils/__tests__/git-diff-repo.test.ts create mode 100644 packages/core/src/utils/__tests__/repo-locator.test.ts rename packages/core/src/{adapters/__tests__/url-utils.test.ts => utils/__tests__/repo-matching.test.ts} (99%) create mode 100644 packages/core/src/utils/diff-sections.ts create mode 100644 packages/core/src/utils/repo-locator.ts create mode 100644 packages/web/src/content/docs/docs/contributing/adrs/013-single-repository-locator.md diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index dcd4f900..63c6f52b 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -36,7 +36,7 @@ export function createCheckCommand(): Command { const validated = validate(CheckOptionsSchema, options, 'command options'); const progress = validated.format === 'json' ? undefined : new ConsoleProgress(); // ── Resolve repository URL ─────────────────────────────────────── - let repoUrl = validated.repo; + let repoUrl = validated.repo ? normalizeToHttps(validated.repo) : undefined; if (!repoUrl) { let remote: string; try { diff --git a/packages/cli/src/commands/connections.ts b/packages/cli/src/commands/connections.ts index 7ea3ea4d..8ce973c2 100644 --- a/packages/cli/src/commands/connections.ts +++ b/packages/cli/src/commands/connections.ts @@ -10,7 +10,7 @@ export function createConnectionsCommand(): Command { .description('Display component relationships from the architecture model') .argument('[model-path]', 'Directory containing architecture model files') .option('--model-format ', 'Format of the architecture model', 'likec4') - .requiredOption('--repo ', 'GitHub or GitLab repository URL') + .requiredOption('--repo ', 'Repository URL') .option('--output ', 'Result format (console, json)', 'console') .action(async (modelPath: string | undefined, options: unknown) => { try { diff --git a/packages/cli/src/utils/command-schemas.ts b/packages/cli/src/utils/command-schemas.ts index 60cf8953..5d1468b4 100644 --- a/packages/cli/src/utils/command-schemas.ts +++ b/packages/cli/src/utils/command-schemas.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { stripUrlUserinfo } from '@erode-app/core'; +import { isRepositoryHostUrl, parseRepoLocator, stripUrlUserinfo } from '@erode-app/core'; const RepositoryUrlSchema = z .string() @@ -7,9 +7,21 @@ const RepositoryUrlSchema = z .pipe( z .string() - .regex( - /^https?:\/\/(github\.com\/[^/]+\/[^/]+|gitlab\.com\/.+\/[^/]+)\/?$/, - 'Provide a valid GitHub or GitLab repository URL' + .refine( + isRepositoryHostUrl, + 'Provide a repository URL on GitHub, GitLab, Bitbucket, Azure DevOps, or a configured self-hosted host' + ) + ); + +const RepositoryLocationSchema = z + .string() + .transform(stripUrlUserinfo) + .pipe( + z + .string() + .refine( + (value) => parseRepoLocator(value) !== null, + 'Provide a repository URL or git remote (https://host/owner/repo or git@host:owner/repo.git)' ) ); @@ -60,7 +72,7 @@ export const ConnectionsOptionsSchema = z.object({ }); export const CheckOptionsSchema = z.object({ - repo: z.url().transform(stripUrlUserinfo).optional(), + repo: RepositoryLocationSchema.optional(), modelFormat: z.string().default('likec4'), staged: z.boolean().optional().default(false), branch: z diff --git a/packages/core/src/adapters/likec4/adapter.ts b/packages/core/src/adapters/likec4/adapter.ts index 6f97ba22..6c390330 100644 --- a/packages/core/src/adapters/likec4/adapter.ts +++ b/packages/core/src/adapters/likec4/adapter.ts @@ -5,7 +5,7 @@ import { resolve } from 'path'; import { fileURLToPath } from 'url'; import { CONFIG } from '../../utils/config.js'; import { validate } from '../../utils/validation.js'; -import { isRepositoryHostUrl, normalizeRepositoryUrl } from '../url-utils.js'; +import { isRepositoryHostUrl, normalizeRepositoryUrl } from '../../utils/repo-locator.js'; import { ErodeError, AdapterError, ConfigurationError, ErrorCode } from '../../errors.js'; import type { ArchitectureModelAdapter, diff --git a/packages/core/src/adapters/structurizr/adapter.ts b/packages/core/src/adapters/structurizr/adapter.ts index 416ecba8..7d23ba0f 100644 --- a/packages/core/src/adapters/structurizr/adapter.ts +++ b/packages/core/src/adapters/structurizr/adapter.ts @@ -2,7 +2,7 @@ import { readFile } from 'fs/promises'; import { existsSync, statSync } from 'fs'; import { join, resolve } from 'path'; import { validate, validatePath } from '../../utils/validation.js'; -import { isRepositoryHostUrl, normalizeRepositoryUrl } from '../url-utils.js'; +import { isRepositoryHostUrl, normalizeRepositoryUrl } from '../../utils/repo-locator.js'; import { AdapterError, ErrorCode } from '../../errors.js'; import { STRUCTURIZR_METADATA } from './metadata.js'; import { exportDslToJson } from './structurizr-cli.js'; diff --git a/packages/core/src/adapters/url-utils.ts b/packages/core/src/adapters/url-utils.ts deleted file mode 100644 index 3b648efd..00000000 --- a/packages/core/src/adapters/url-utils.ts +++ /dev/null @@ -1,101 +0,0 @@ -const REPO_HOSTNAMES: Record = { - 'github.com': 'https://github.com', - 'www.github.com': 'https://github.com', - 'gitlab.com': 'https://gitlab.com', - 'www.gitlab.com': 'https://gitlab.com', - 'bitbucket.org': 'https://bitbucket.org', - 'www.bitbucket.org': 'https://bitbucket.org', - 'dev.azure.com': 'https://dev.azure.com', - 'ssh.dev.azure.com': 'https://dev.azure.com', -}; - -const AZURE_BASE = 'https://dev.azure.com'; - -/** - * Canonical `{org}/…/_git/{repo}` path for an Azure DevOps repository URL, or - * undefined when the URL is not a repository (e.g. a bare project page). - * Handles the web layout `/{org}/{project}/_git/{repo}` and the SSH-derived - * layout `/v3/{org}/{project}/{repo}`. - */ -function azureRepoPath(pathname: string): string | undefined { - const parts = pathname.split('/').filter(Boolean); - const gitIdx = parts.indexOf('_git'); - const webRepo = gitIdx > 0 ? parts[gitIdx + 1] : undefined; - let segments: string[] | undefined; - if (webRepo) { - // web: [org, project, _git, repo] -> [org, project, repo] - segments = [...parts.slice(0, gitIdx), webRepo]; - } else if (parts[0] === 'v3' && parts.length >= 4) { - // ssh: [v3, org, project, repo] -> [org, project, repo] - segments = parts.slice(1); - } - const repoSegment = segments?.at(-1); - if (!segments || segments.length < 2 || !repoSegment) return undefined; - const repo = repoSegment.replace(/\.git$/, '').toLowerCase(); - const namespace = segments - .slice(0, -1) - .map((p) => p.toLowerCase()) - .join('/'); - return `${namespace}/_git/${repo}`; -} - -export function isRepositoryHostUrl(url: string): boolean { - try { - const parsed = new URL(url); - if (!Object.hasOwn(REPO_HOSTNAMES, parsed.hostname)) return false; - // Azure URLs are repositories only when they carry a repo path; a bare - // project page (dev.azure.com/{org}/{project}) is not a repository, and - // would pass validation while being unmatchable by check. - if (REPO_HOSTNAMES[parsed.hostname] === AZURE_BASE) { - return azureRepoPath(parsed.pathname) !== undefined; - } - return true; - } catch { - return false; - } -} - -export function normalizeRepositoryUrl(url: string): string { - try { - const parsed = new URL(url); - const base = REPO_HOSTNAMES[parsed.hostname]; - if (!base) return url; - - // GitLab supports nested groups (e.g. gitlab.com/group/subgroup/project), - // so preserve all path segments instead of just two. - if (base === 'https://gitlab.com') { - const gitlabPath = parsed.pathname.split('/-/')[0] ?? parsed.pathname; - const parts = gitlabPath.split('/').filter(Boolean); - if (parts.length >= 2) { - const last = parts.at(-1); - if (!last) return url; - const repo = last.replace(/\.git$/, '').toLowerCase(); - const namespace = parts - .slice(0, -1) - .map((p) => p.toLowerCase()) - .join('/'); - return `${base}/${namespace}/${repo}`; - } - return url; - } - - // Azure DevOps: canonicalize both the web layout - // (dev.azure.com/{org}/{project}/_git/{repo}) and the SSH-derived layout - // (ssh.dev.azure.com/v3/{org}/{project}/{repo}) to the same URL, so an SSH - // remote matches a web link. Non-repository URLs are left unchanged. - if (base === AZURE_BASE) { - const path = azureRepoPath(parsed.pathname); - return path ? `${base}/${path}` : url; - } - - const match = /^\/([^/]+)\/([^/]+)/.exec(parsed.pathname); - if (match?.[1] && match[2]) { - const owner = match[1].toLowerCase(); - const repo = match[2].replace(/\.git$/, '').toLowerCase(); - return `${base}/${owner}/${repo}`; - } - return url; - } catch { - return url; - } -} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index bbcb8d72..89e23256 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -112,6 +112,10 @@ export type { ModelPatcher, PatchResult, DslValidationResult } from './adapters/ export { resolveModelSource } from './utils/model-source.js'; export type { ResolvedModelSource } from './utils/model-source.js'; +// Repository identity +export { parseRepoLocator, isRepositoryHostUrl } from './utils/repo-locator.js'; +export type { RepoLocator, RepoPlatform } from './utils/repo-locator.js'; + // Git diff (local check) export { generateGitDiff, diff --git a/packages/core/src/pipelines/validate.ts b/packages/core/src/pipelines/validate.ts index 159a30b4..a2790588 100644 --- a/packages/core/src/pipelines/validate.ts +++ b/packages/core/src/pipelines/validate.ts @@ -2,7 +2,7 @@ import type { ProgressReporter } from './progress.js'; import { SilentProgress } from './progress.js'; import { createAdapter } from '../adapters/adapter-factory.js'; import { validatePath } from '../utils/validation.js'; -import { isRepositoryHostUrl } from '../adapters/url-utils.js'; +import { isRepositoryHostUrl } from '../utils/repo-locator.js'; export interface ValidateOptions { modelPath: string; diff --git a/packages/core/src/platforms/__tests__/change-request-url.test.ts b/packages/core/src/platforms/__tests__/change-request-url.test.ts new file mode 100644 index 00000000..122d5511 --- /dev/null +++ b/packages/core/src/platforms/__tests__/change-request-url.test.ts @@ -0,0 +1,118 @@ +import { describe, it, expect, vi } from 'vitest'; +import { ErodeError } from '../../errors.js'; + +vi.mock('../../utils/config.js', () => ({ + CONFIG: { + github: { baseUrl: 'https://ghe.example.com/api/v3' }, + gitlab: { baseUrl: 'https://gitlab.example.com' }, + bitbucket: { baseUrl: 'https://api.bitbucket.org/2.0' }, + }, +})); + +import { CONFIG } from '../../utils/config.js'; +import { parseChangeRequestRef } from '../change-request-url.js'; + +type Platform = 'github' | 'gitlab' | 'bitbucket'; + +const cases: [Platform, string, number, string, string, string][] = [ + ['github', 'https://github.com/o/r/pull/42', 42, 'https://github.com/o/r', 'o', 'r'], + ['github', 'https://www.github.com/o/r/pull/42', 42, 'https://github.com/o/r', 'o', 'r'], + ['github', 'https://github.com/o/r/pull/42/files', 42, 'https://github.com/o/r', 'o', 'r'], + ['github', 'https://github.com/o/r/pull/42/', 42, 'https://github.com/o/r', 'o', 'r'], + ['github', 'https://github.com/o/r/pull/42?tab=files#r1', 42, 'https://github.com/o/r', 'o', 'r'], + ['github', 'https://ghe.example.com/o/r/pull/7', 7, 'https://ghe.example.com/o/r', 'o', 'r'], + [ + 'gitlab', + 'https://gitlab.com/g/s/p/-/merge_requests/5/diffs', + 5, + 'https://gitlab.com/g/s/p', + 'g/s', + 'p', + ], + [ + 'gitlab', + 'https://www.gitlab.com/g/p/-/merge_requests/5/', + 5, + 'https://gitlab.com/g/p', + 'g', + 'p', + ], + [ + 'gitlab', + 'https://gitlab.com/g/p/-/merge_requests/5#note_1', + 5, + 'https://gitlab.com/g/p', + 'g', + 'p', + ], + [ + 'gitlab', + 'https://gitlab.example.com/g/p/-/merge_requests/9', + 9, + 'https://gitlab.example.com/g/p', + 'g', + 'p', + ], + + [ + 'bitbucket', + 'https://bitbucket.org/w/r/pull-requests/3/overview', + 3, + 'https://bitbucket.org/w/r', + 'w', + 'r', + ], + [ + 'bitbucket', + 'https://bitbucket.org/w/r/pull-requests/3?tab=diff', + 3, + 'https://bitbucket.org/w/r', + 'w', + 'r', + ], +]; + +describe('parseChangeRequestRef', () => { + it.each(cases)('%s: %s', (platform, url, number, repositoryUrl, owner, repo) => { + expect(parseChangeRequestRef(url, platform, 'bad')).toEqual({ + number, + url, + repositoryUrl, + platformId: { owner, repo }, + }); + }); + + it.each([ + ['github', 'https://gitlab.com/g/p/-/merge_requests/1'], + ['github', 'https://github.com/o/r/pull/abc'], + ['github', 'https://github.com/o/r/pull'], + ['github', 'https://github.com/o/r/issues/1'], + ['github', 'https://code.example.org/o/r/pull/1'], + ['github', 'git@github.com:o/r.git'], + ['gitlab', 'https://gitlab.com/g/p/merge_requests/1'], + ['bitbucket', 'https://bitbucket.org/w/r/pull-requests/'], + ['bitbucket', ''], + ['github', 'https://github.com/o/r/tree/pull/12'], + ['bitbucket', 'https://bitbucket.org/w/r/src/pull-requests/3'], + ['gitlab', 'https://gitlab.com/g/p/-/tree/x/-/merge_requests/5'], + ] as [Platform, string][])('%s rejects %s', (platform, url) => { + expect(() => parseChangeRequestRef(url, platform, 'bad')).toThrow(ErodeError); + }); + + it('parses an MR on a GitLab instance under a context path', () => { + const gitlab = CONFIG.gitlab as { baseUrl: string }; + const saved = gitlab.baseUrl; + gitlab.baseUrl = 'https://example.com/gitlab'; + try { + const url = 'https://example.com/gitlab/g/s/p/-/merge_requests/4'; + expect(parseChangeRequestRef(url, 'gitlab', 'bad')).toEqual({ + number: 4, + url, + repositoryUrl: 'https://example.com/gitlab/g/s/p', + platformId: { owner: 'g/s', repo: 'p' }, + }); + } finally { + gitlab.baseUrl = saved; + } + }); +}); diff --git a/packages/core/src/platforms/__tests__/platform-factory.test.ts b/packages/core/src/platforms/__tests__/platform-factory.test.ts index 60149215..cd881e1b 100644 --- a/packages/core/src/platforms/__tests__/platform-factory.test.ts +++ b/packages/core/src/platforms/__tests__/platform-factory.test.ts @@ -64,6 +64,21 @@ describe('detectPlatform', () => { it('should throw for unsupported platforms', () => { expect(() => detectPlatform('https://sourcehut.org/org/repo/pull/1')).toThrow(ErodeError); expect(() => detectPlatform('https://sourcehut.org/org/repo/pull/1')).toThrow( + /Unrecognized repository host.*ERODE_GITLAB_BASE_URL/ + ); + }); + + it('should detect platforms from SSH remotes', () => { + expect(detectPlatform('git@github.com:org/repo.git')).toBe('github'); + expect(detectPlatform('ssh://git@gitlab.com:2222/group/repo.git')).toBe('gitlab'); + }); + + it('should detect a host without a repository path', () => { + expect(detectPlatform('https://bitbucket.org/')).toBe('bitbucket'); + }); + + it('should throw for repository hosts without PR support', () => { + expect(() => detectPlatform('https://dev.azure.com/org/project/_git/repo')).toThrow( 'Unsupported platform' ); }); diff --git a/packages/core/src/platforms/bitbucket/__tests__/reader.test.ts b/packages/core/src/platforms/bitbucket/__tests__/reader.test.ts index 5c651472..79577d8c 100644 --- a/packages/core/src/platforms/bitbucket/__tests__/reader.test.ts +++ b/packages/core/src/platforms/bitbucket/__tests__/reader.test.ts @@ -20,6 +20,8 @@ vi.mock('../api-client.js', () => ({ vi.mock('../../../utils/config.js', () => ({ CONFIG: { bitbucket: { token: 'test-token', baseUrl: 'https://api.bitbucket.org/2.0' }, + github: { baseUrl: 'https://api.github.com' }, + gitlab: { baseUrl: 'https://gitlab.com' }, constraints: { maxFilesPerDiff: 50, maxLinesPerDiff: 5000 }, }, })); @@ -97,6 +99,17 @@ describe('BitbucketReader', () => { expect(result.platformId).toEqual({ owner: 'myteam', repo: 'myrepo' }); }); + it.each([ + 'https://www.bitbucket.org/workspace/repo/pull-requests/42', + 'https://bitbucket.org/workspace/repo/pull-requests/42/overview', + 'https://bitbucket.org/workspace/repo/pull-requests/42/', + 'https://bitbucket.org/workspace/repo/pull-requests/42?tab=diff', + ])('should accept %s', (url) => { + const result = reader.parseChangeRequestUrl(url); + expect(result.number).toBe(42); + expect(result.repositoryUrl).toBe('https://bitbucket.org/workspace/repo'); + }); + it('should be case-insensitive', () => { const result = reader.parseChangeRequestUrl( 'HTTPS://BITBUCKET.ORG/workspace/repo/pull-requests/10' diff --git a/packages/core/src/platforms/bitbucket/reader.ts b/packages/core/src/platforms/bitbucket/reader.ts index 9a10c511..e400944b 100644 --- a/packages/core/src/platforms/bitbucket/reader.ts +++ b/packages/core/src/platforms/bitbucket/reader.ts @@ -5,7 +5,6 @@ import type { ChangeRequestData, ChangeRequestCommit, } from '../source-platform.js'; -import { ErodeError, ErrorCode } from '../../errors.js'; import { validate } from '../../utils/validation.js'; import { ChangeRequestDataSchema, @@ -18,9 +17,7 @@ import { } from '../../schemas/bitbucket-api.schema.js'; import { BitbucketApiClient } from './api-client.js'; import { applyDiffTruncation, wrapPlatformError } from '../platform-utils.js'; - -const BITBUCKET_PR_URL_PATTERN = - /^https?:\/\/bitbucket\.org\/([^/]+)\/([^/]+)\/pull-requests\/(\d+)$/i; +import { parseChangeRequestRef } from '../change-request-url.js'; /** Parse "Name " format used by Bitbucket commit authors. */ function parseAuthorRaw(raw: string): { name: string; email: string } { @@ -39,28 +36,11 @@ export class BitbucketReader implements SourcePlatformReader { } parseChangeRequestUrl(url: string): ChangeRequestRef { - const match = BITBUCKET_PR_URL_PATTERN.exec(url); - if (!match) { - throw new ErodeError( - 'Unrecognized Bitbucket pull request URL. Expected: https://bitbucket.org/{workspace}/{repo}/pull-requests/{number}', - ErrorCode.PLATFORM_INVALID_URL, - 'Unrecognized Bitbucket pull request URL. Expected: https://bitbucket.org/{workspace}/{repo}/pull-requests/{number}' - ); - } - const [, workspace, repoSlug, prNumber] = match; - if (!workspace || !repoSlug || !prNumber) { - throw new ErodeError( - 'Incomplete Bitbucket PR URL: workspace, repo, or pull request number is missing', - ErrorCode.PLATFORM_INVALID_URL, - 'Incomplete Bitbucket PR URL: workspace, repo, or pull request number is missing' - ); - } - return { - number: parseInt(prNumber, 10), + return parseChangeRequestRef( url, - repositoryUrl: `https://bitbucket.org/${workspace}/${repoSlug}`, - platformId: { owner: workspace, repo: repoSlug }, - }; + 'bitbucket', + 'Unrecognized Bitbucket pull request URL. Expected: https://bitbucket.org/{workspace}/{repo}/pull-requests/{number}' + ); } async fetchChangeRequest(ref: ChangeRequestRef): Promise { diff --git a/packages/core/src/platforms/change-request-url.ts b/packages/core/src/platforms/change-request-url.ts new file mode 100644 index 00000000..adcdfe24 --- /dev/null +++ b/packages/core/src/platforms/change-request-url.ts @@ -0,0 +1,51 @@ +import { ErodeError, ErrorCode } from '../errors.js'; +import { parseRepoLocator } from '../utils/repo-locator.js'; +import type { ChangeRequestRef } from './source-platform.js'; + +/** + * Path segments that introduce the change request number, directly after the + * repository path (and any self-hosted base path). Bitbucket Data Center/Server + * PR URLs are not accepted: they parse as `bitbucket-server`, which has no reader. + */ +const MARKERS: Record<'github' | 'gitlab' | 'bitbucket', readonly string[]> = { + github: ['pull'], + gitlab: ['-', 'merge_requests'], + bitbucket: ['pull-requests'], +}; + +/** + * Parse a PR or MR URL for `platform`. Anything after the number (`/files`, + * `/diffs`, a trailing slash, query or fragment) is ignored. + */ +export function parseChangeRequestRef( + url: string, + platform: 'github' | 'gitlab' | 'bitbucket', + errorMessage: string +): ChangeRequestRef { + const invalid = new ErodeError(errorMessage, ErrorCode.PLATFORM_INVALID_URL, errorMessage); + let parsed: URL; + try { + parsed = new URL(url); + } catch { + throw invalid; + } + if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') throw invalid; + + const locator = parseRepoLocator(url); + if (locator?.platform !== platform) throw invalid; + + // The marker must follow the repository path, so `/o/r/tree/pull/1` is not PR 1. + const segments = parsed.pathname.split('/').filter(Boolean); + const repoDepth = new URL(locator.canonicalUrl).pathname.split('/').filter(Boolean).length; + const marker = MARKERS[platform]; + if (!marker.every((m, i) => segments[repoDepth + i] === m)) throw invalid; + const number = segments[repoDepth + marker.length]; + if (!number || !/^\d+$/.test(number)) throw invalid; + + return { + number: parseInt(number, 10), + url, + repositoryUrl: locator.canonicalUrl, + platformId: { owner: locator.owner, repo: locator.repo }, + }; +} diff --git a/packages/core/src/platforms/github/__tests__/reader.test.ts b/packages/core/src/platforms/github/__tests__/reader.test.ts index 28d8530c..cb024208 100644 --- a/packages/core/src/platforms/github/__tests__/reader.test.ts +++ b/packages/core/src/platforms/github/__tests__/reader.test.ts @@ -27,7 +27,9 @@ vi.mock('@octokit/rest', () => ({ // Mock config vi.mock('../../../utils/config.js', () => ({ CONFIG: { - github: { token: 'test-token' }, + github: { token: 'test-token', baseUrl: 'https://api.github.com' }, + gitlab: { baseUrl: 'https://gitlab.com' }, + bitbucket: { baseUrl: 'https://api.bitbucket.org/2.0' }, constraints: { maxFilesPerDiff: 50, maxLinesPerDiff: 5000 }, }, })); @@ -128,6 +130,17 @@ describe('GitHubReader', () => { expect(() => reader.parseChangeRequestUrl('')).toThrow(ErodeError); }); + it.each([ + 'https://www.github.com/org/repo/pull/42', + 'https://github.com/org/repo/pull/42/files', + 'https://github.com/org/repo/pull/42/', + 'https://github.com/org/repo/pull/42?diff=split#discussion_r1', + ])('should accept %s', (url) => { + const result = reader.parseChangeRequestUrl(url); + expect(result.number).toBe(42); + expect(result.repositoryUrl).toBe('https://github.com/org/repo'); + }); + it('should populate repositoryUrl correctly', () => { const result = reader.parseChangeRequestUrl('https://github.com/my-org/my-repo/pull/123'); expect(result.repositoryUrl).toBe('https://github.com/my-org/my-repo'); diff --git a/packages/core/src/platforms/github/reader.ts b/packages/core/src/platforms/github/reader.ts index 013d1dd1..1e9f6e19 100644 --- a/packages/core/src/platforms/github/reader.ts +++ b/packages/core/src/platforms/github/reader.ts @@ -1,7 +1,6 @@ import { z } from 'zod'; import { Octokit } from '@octokit/rest'; import { CONFIG } from '../../utils/config.js'; -import { ErodeError, ErrorCode } from '../../errors.js'; import type { SourcePlatformReader, ChangeRequestRef, @@ -14,6 +13,7 @@ import { ChangeRequestCommitSchema, } from '../../schemas/source-platform.schema.js'; import { applyDiffTruncation, wrapPlatformError } from '../platform-utils.js'; +import { parseChangeRequestRef } from '../change-request-url.js'; export class GitHubReader implements SourcePlatformReader { private octokit: Octokit; @@ -22,46 +22,16 @@ export class GitHubReader implements SourcePlatformReader { const authToken = token ?? CONFIG.github.token; this.octokit = new Octokit({ ...(authToken ? { auth: authToken } : {}), + baseUrl: CONFIG.github.baseUrl, }); } parseChangeRequestUrl(url: string): ChangeRequestRef { - let owner: string; - let repo: string; - let prNumber: string; - - try { - const parsed = new URL(url); - if (parsed.hostname !== 'github.com') { - throw new Error('Not a GitHub URL'); - } - const segments = parsed.pathname.split('/').filter(Boolean); - if (segments.length < 4 || segments[2] !== 'pull' || !segments[3]) { - throw new Error('Invalid path structure'); - } - [owner, repo, , prNumber] = segments as [string, string, string, string]; - } catch { - throw new ErodeError( - 'Cannot parse GitHub pull request URL. Expected format: https://github.com/{owner}/{repo}/pull/{number}', - ErrorCode.PLATFORM_INVALID_URL, - 'Cannot parse GitHub pull request URL. Expected format: https://github.com/{owner}/{repo}/pull/{number}' - ); - } - - if (!owner || !repo || !prNumber || isNaN(Number(prNumber))) { - throw new ErodeError( - 'GitHub PR URL is missing required segments: owner, repo, or PR number', - ErrorCode.PLATFORM_INVALID_URL, - 'GitHub PR URL is missing required segments: owner, repo, or PR number' - ); - } - - return { - number: parseInt(prNumber, 10), + return parseChangeRequestRef( url, - repositoryUrl: `https://github.com/${owner}/${repo}`, - platformId: { owner, repo }, - }; + 'github', + 'Cannot parse GitHub pull request URL. Expected format: https://github.com/{owner}/{repo}/pull/{number}' + ); } async fetchChangeRequest(ref: ChangeRequestRef): Promise { diff --git a/packages/core/src/platforms/github/writer.ts b/packages/core/src/platforms/github/writer.ts index be9dfe19..e5194c37 100644 --- a/packages/core/src/platforms/github/writer.ts +++ b/packages/core/src/platforms/github/writer.ts @@ -36,7 +36,7 @@ export class GitHubWriter implements SourcePlatformWriter { `Provide ${ENV_VAR_NAMES.modelRepoPrToken} or ${ENV_VAR_NAMES.githubToken} in your environment or ${RC_FILENAME} to create PRs.` ); } - this.octokit = new Octokit({ auth: token }); + this.octokit = new Octokit({ auth: token, baseUrl: CONFIG.github.baseUrl }); this.targetOwner = targetOwner; this.targetRepo = targetRepo; } diff --git a/packages/core/src/platforms/gitlab/__tests__/reader.test.ts b/packages/core/src/platforms/gitlab/__tests__/reader.test.ts index 29dd5b9c..364b4931 100644 --- a/packages/core/src/platforms/gitlab/__tests__/reader.test.ts +++ b/packages/core/src/platforms/gitlab/__tests__/reader.test.ts @@ -22,6 +22,8 @@ vi.mock('@gitbeaker/rest', () => ({ vi.mock('../../../utils/config.js', () => ({ CONFIG: { gitlab: { token: 'test-token', baseUrl: 'https://gitlab.com' }, + github: { baseUrl: 'https://api.github.com' }, + bitbucket: { baseUrl: 'https://api.bitbucket.org/2.0' }, constraints: { maxFilesPerDiff: 50, maxLinesPerDiff: 5000 }, }, })); @@ -114,6 +116,17 @@ describe('GitLabReader', () => { expect(result.repositoryUrl).toBe('https://gitlab.com/a/b/c/d/repo'); }); + it.each([ + 'https://www.gitlab.com/org/repo/-/merge_requests/42', + 'https://gitlab.com/org/repo/-/merge_requests/42/diffs', + 'https://gitlab.com/org/repo/-/merge_requests/42/', + 'https://gitlab.com/org/repo/-/merge_requests/42#note_1', + ])('should accept %s', (url) => { + const result = reader.parseChangeRequestUrl(url); + expect(result.number).toBe(42); + expect(result.repositoryUrl).toBe('https://gitlab.com/org/repo'); + }); + it('should parse URL with http scheme', () => { const result = reader.parseChangeRequestUrl('http://gitlab.com/org/repo/-/merge_requests/1'); expect(result.number).toBe(1); diff --git a/packages/core/src/platforms/gitlab/reader.ts b/packages/core/src/platforms/gitlab/reader.ts index f686e365..c5150e7e 100644 --- a/packages/core/src/platforms/gitlab/reader.ts +++ b/packages/core/src/platforms/gitlab/reader.ts @@ -1,7 +1,6 @@ import { z } from 'zod'; import { Gitlab } from '@gitbeaker/rest'; import { CONFIG } from '../../utils/config.js'; -import { ErodeError, ErrorCode } from '../../errors.js'; import type { SourcePlatformReader, ChangeRequestRef, @@ -19,8 +18,7 @@ import { ChangeRequestCommitSchema, } from '../../schemas/source-platform.schema.js'; import { applyDiffTruncation, wrapPlatformError } from '../platform-utils.js'; - -const GITLAB_MR_URL_PATTERN = /^https?:\/\/gitlab\.com\/(.+)\/-\/merge_requests\/(\d+)$/i; +import { parseChangeRequestRef } from '../change-request-url.js'; export class GitLabReader implements SourcePlatformReader { private api: InstanceType; @@ -34,33 +32,11 @@ export class GitLabReader implements SourcePlatformReader { } parseChangeRequestUrl(url: string): ChangeRequestRef { - const match = GITLAB_MR_URL_PATTERN.exec(url); - if (!match) { - throw new ErodeError( - 'Unrecognized GitLab merge request URL. Expected: https://gitlab.com/{namespace}/{project}/-/merge_requests/{number}', - ErrorCode.PLATFORM_INVALID_URL, - 'Unrecognized GitLab merge request URL. Expected: https://gitlab.com/{namespace}/{project}/-/merge_requests/{number}' - ); - } - const [, fullProjectPath, mrNumber] = match; - if (!fullProjectPath || !mrNumber) { - throw new ErodeError( - 'Incomplete GitLab MR URL: project path or merge request number is missing', - ErrorCode.PLATFORM_INVALID_URL, - 'Incomplete GitLab MR URL: project path or merge request number is missing' - ); - } - - const lastSlashIndex = fullProjectPath.lastIndexOf('/'); - const owner = fullProjectPath.substring(0, lastSlashIndex); - const repo = fullProjectPath.substring(lastSlashIndex + 1); - - return { - number: parseInt(mrNumber, 10), + return parseChangeRequestRef( url, - repositoryUrl: `https://gitlab.com/${fullProjectPath}`, - platformId: { owner, repo }, - }; + 'gitlab', + 'Unrecognized GitLab merge request URL. Expected: https://gitlab.com/{namespace}/{project}/-/merge_requests/{number}' + ); } async fetchChangeRequest(ref: ChangeRequestRef): Promise { diff --git a/packages/core/src/platforms/platform-factory.ts b/packages/core/src/platforms/platform-factory.ts index 87792bc1..f0e4eb14 100644 --- a/packages/core/src/platforms/platform-factory.ts +++ b/packages/core/src/platforms/platform-factory.ts @@ -3,28 +3,38 @@ import type { SourcePlatformReader, SourcePlatformWriter } from './source-platfo import { GitHubReader, GitHubWriter } from './github/index.js'; import { GitLabReader, GitLabWriter } from './gitlab/index.js'; import { BitbucketReader, BitbucketWriter } from './bitbucket/index.js'; +import { parseRepoLocator, platformForHost, type RepoPlatform } from '../utils/repo-locator.js'; type Platform = 'github' | 'gitlab' | 'bitbucket'; -export function detectPlatform(url: string): Platform { +function hostPlatform(url: string): RepoPlatform | undefined { + const locator = parseRepoLocator(url); + if (locator) return locator.platform; try { - const parsed = new URL(url); - if (parsed.hostname === 'github.com' || parsed.hostname === 'www.github.com') { - return 'github'; - } - if (parsed.hostname === 'gitlab.com' || parsed.hostname === 'www.gitlab.com') { - return 'gitlab'; - } - if (parsed.hostname === 'bitbucket.org' || parsed.hostname === 'www.bitbucket.org') { - return 'bitbucket'; - } + return platformForHost(new URL(url).hostname); } catch { + return undefined; + } +} + +export function detectPlatform(url: string): Platform { + const platform = hostPlatform(url); + if (platform === undefined) { throw new ErodeError( `Unrecognized URL: ${url}`, ErrorCode.PLATFORM_INVALID_URL, `Unrecognized URL: ${url}` ); } + if (platform === 'github' || platform === 'gitlab' || platform === 'bitbucket') { + return platform; + } + if (platform === 'unknown') { + const message = + `Unrecognized repository host in URL: ${url}. For a self-hosted instance, set ` + + 'ERODE_GITHUB_BASE_URL, ERODE_GITLAB_BASE_URL or ERODE_BITBUCKET_BASE_URL.'; + throw new ErodeError(message, ErrorCode.PLATFORM_INVALID_URL, message); + } throw new ErodeError( `Unsupported platform for URL: ${url}. Only GitHub, GitLab, and Bitbucket are supported.`, diff --git a/packages/core/src/utils/__tests__/diff-sections.test.ts b/packages/core/src/utils/__tests__/diff-sections.test.ts new file mode 100644 index 00000000..295814ff --- /dev/null +++ b/packages/core/src/utils/__tests__/diff-sections.test.ts @@ -0,0 +1,84 @@ +import { describe, it, expect } from 'vitest'; +import { splitDiffSections, unquoteGitPath } from '../diff-sections.js'; +import { filterDiffByFiles, parseFilesFromDiff } from '../git-diff.js'; + +function paths(diff: string): (string | undefined)[] { + return splitDiffSections(diff).map((s) => s.path); +} + +describe('unquoteGitPath', () => { + it.each([ + ['plain/path.ts', 'plain/path.ts'], + ['"src/caf\\303\\251.ts"', 'src/café.ts'], + ['"a\\tb\\"c\\\\d.ts"', 'a\tb"c\\d.ts'], + ])('decodes %s', (input, expected) => { + expect(unquoteGitPath(input)).toBe(expected); + }); +}); + +describe('splitDiffSections', () => { + it.each([ + ['default prefixes', 'diff --git a/src/x.ts b/src/x.ts', 'src/x.ts'], + ['no prefix', 'diff --git src/x.ts src/x.ts', 'src/x.ts'], + ['mnemonic prefixes', 'diff --git i/src/x.ts w/src/x.ts', 'src/x.ts'], + ['path containing " b/"', 'diff --git a/docs/a b/c.md b/docs/a b/c.md', 'docs/a b/c.md'], + ['no prefix with " b/"', 'diff --git docs/a b/c.md docs/a b/c.md', 'docs/a b/c.md'], + ['quoted paths', 'diff --git "a/caf\\303\\251.ts" "b/caf\\303\\251.ts"', 'café.ts'], + ['combined diff', 'diff --cc src/conflict.ts', 'src/conflict.ts'], + ['unmerged marker', '* Unmerged path src/conflict.ts', 'src/conflict.ts'], + ])('resolves the path for %s', (_name, header, expected) => { + expect(paths(`${header}\n@@ -1 +1 @@\n-a\n+b`)).toEqual([expected]); + }); + + it('uses the rename target, even without prefixes', () => { + const diff = + 'diff --git old dir/x.ts new dir/x.ts\nsimilarity index 100%\nrename from old dir/x.ts\nrename to new dir/x.ts'; + expect(paths(diff)).toEqual(['new dir/x.ts']); + }); + + it('falls back to the +++ line for an asymmetric header', () => { + const diff = 'diff --git a/old.ts b/new.ts\n--- a/old.ts\n+++ b/new.ts\n@@ -1 +1 @@'; + expect(paths(diff)).toEqual(['new.ts']); + }); + + it('ignores "rename to" text inside hunks', () => { + const diff = 'diff --git a/x.md b/x.md\n@@ -1 +1 @@\nrename to y.md'; + expect(paths(diff)).toEqual(['x.md']); + }); +}); + +describe('parseFilesFromDiff and filterDiffByFiles with git config variants', () => { + const diff = [ + 'diff --git docs/a b/c.md docs/a b/c.md', + '--- docs/a b/c.md\t', + '+++ docs/a b/c.md\t', + '@@ -1 +1,2 @@', + '+keep', + 'diff --git c/src/drop.ts w/src/drop.ts', + '@@ -1 +1,2 @@', + '+drop', + ].join('\n'); + + it('finds files in no-prefix and mnemonic-prefix diffs', () => { + expect(parseFilesFromDiff(diff).map((f) => f.filename)).toEqual([ + 'docs/a b/c.md', + 'src/drop.ts', + ]); + }); + + it('keeps only the requested sections', () => { + const result = filterDiffByFiles(diff, [{ filename: 'docs/a b/c.md' }]); + expect(result).toContain('+keep'); + expect(result).not.toContain('+drop'); + }); + + it('keeps both sections of a type change', () => { + const typeChange = [ + 'diff --git a/link b/link', + 'deleted file mode 100644', + 'diff --git a/link b/link', + 'new file mode 120000', + ].join('\n'); + expect(filterDiffByFiles(typeChange, [{ filename: 'link' }])).toBe(typeChange); + }); +}); diff --git a/packages/core/src/utils/__tests__/git-diff-repo.test.ts b/packages/core/src/utils/__tests__/git-diff-repo.test.ts new file mode 100644 index 00000000..3cbd0ffc --- /dev/null +++ b/packages/core/src/utils/__tests__/git-diff-repo.test.ts @@ -0,0 +1,118 @@ +import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { generateGitDiff, filterDiffByFiles, parseFilesFromDiff } from '../git-diff.js'; + +// Exercises real git against a repo whose config breaks naive diff parsing. +let dir: string; + +function git(...args: string[]): string { + return execFileSync( + 'git', + ['-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', ...args], + { cwd: dir, encoding: 'utf-8' } + ); +} + +function write(path: string, content: string | Buffer): void { + writeFileSync(join(dir, path), content); +} + +beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), 'erode-git-diff-')); + git('init', '-q', '-b', 'main', '.'); + git('config', 'user.email', 'test@example.invalid'); + git('config', 'user.name', 'Test'); + mkdirSync(join(dir, 'docs/a b'), { recursive: true }); + mkdirSync(join(dir, 'src')); + write('docs/a b/c.md', 'one\n'); + write('src/café.ts', 'export const a = 1;\n'); + write('link.txt', 'target\n'); + write('old.ts', 'export const moved = 1;\nexport const kept = 2;\n'); + write('image.bin', Buffer.from([0, 1, 2, 3])); + write('unchanged.ts', 'same\n'); + git('add', '-A'); + git('commit', '-q', '-m', 'init'); + + write('docs/a b/c.md', 'one\ntwo\n'); + write('src/café.ts', 'export const a = 2;\n'); + rmSync(join(dir, 'link.txt')); + symlinkSync('old.ts', join(dir, 'link.txt')); + git('mv', 'old.ts', 'new.ts'); + write('image.bin', Buffer.from([0, 9, 9])); + git('add', '-A'); + + // Config that changes porcelain output; generateGitDiff must not depend on it. + git('config', 'diff.noprefix', 'true'); + git('config', 'diff.mnemonicPrefix', 'true'); + git('config', 'color.diff', 'always'); + git('config', 'diff.external', 'false'); + git('config', 'diff.relative', 'true'); +}); + +afterAll(() => { + rmSync(dir, { recursive: true, force: true }); +}); + +const expectedFiles = [ + { filename: 'docs/a b/c.md', status: 'modified' }, + { filename: 'image.bin', status: 'modified' }, + { filename: 'link.txt', status: 'changed' }, + { filename: 'new.ts', status: 'renamed' }, + { filename: 'src/café.ts', status: 'modified' }, +]; + +describe('generateGitDiff against a real repository', () => { + const originalLang = process.env['LANG']; + afterEach(() => { + if (originalLang === undefined) delete process.env['LANG']; + else process.env['LANG'] = originalLang; + }); + + it('returns every file with its status despite noprefix, mnemonic prefixes and non-ASCII paths', () => { + const result = generateGitDiff({ cwd: dir, staged: true }); + expect(result.files).toEqual(expectedFiles); + }); + + it('computes stats from numstat, counting binary files without lines', () => { + const result = generateGitDiff({ cwd: dir, staged: true }); + // c.md +1, café.ts +1 -1, link.txt +1 -1, image.bin binary, rename 0/0. + expect(result.stats).toEqual({ additions: 3, deletions: 2, filesChanged: 5 }); + }); + + it('emits a parseable diff with a/ and b/ prefixes and no colour', () => { + const { diff } = generateGitDiff({ cwd: dir, staged: true }); + expect(diff).not.toContain('\x1b['); + expect(diff).toContain('diff --git a/docs/a b/c.md b/docs/a b/c.md'); + expect(diff).toContain('diff --git a/src/café.ts b/src/café.ts'); + expect(parseFilesFromDiff(diff).map((f) => f.filename)).toEqual( + expectedFiles.map((f) => f.filename) + ); + }); + + it('filters the diff by file, keeping both sections of a type change', () => { + const { diff } = generateGitDiff({ cwd: dir, staged: true }); + const filtered = filterDiffByFiles(diff, [ + { filename: 'docs/a b/c.md' }, + { filename: 'link.txt' }, + ]); + expect(filtered).toContain('+two'); + expect(filtered.match(/^diff --git a\/link\.txt b\/link\.txt$/gm)).toHaveLength(2); + expect(filtered).not.toContain('café'); + expect(filtered).not.toContain('image.bin'); + expect(filtered).not.toContain('new.ts'); + }); + + it('keeps the same result under a German locale', () => { + const baseline = generateGitDiff({ cwd: dir, staged: true }); + process.env['LANG'] = 'de_DE.UTF-8'; + expect(generateGitDiff({ cwd: dir, staged: true })).toEqual(baseline); + }); + + it('runs from a subdirectory with diff.relative set and still reports repo-root paths', () => { + const result = generateGitDiff({ cwd: join(dir, 'src'), staged: true }); + expect(result.files).toEqual(expectedFiles); + }); +}); diff --git a/packages/core/src/utils/__tests__/git-diff.test.ts b/packages/core/src/utils/__tests__/git-diff.test.ts index 44a5b4a7..33b16a30 100644 --- a/packages/core/src/utils/__tests__/git-diff.test.ts +++ b/packages/core/src/utils/__tests__/git-diff.test.ts @@ -109,6 +109,16 @@ describe('normalizeToHttps', () => { 'https://github.com/owner/repo' ); }); + + it.each([ + ['ssh://git@gitlab.example.com:2222/g/p.git', 'https://gitlab.example.com/g/p'], + ['alice@github.com:owner/repo', 'https://github.com/owner/repo'], + ['git@github.com-work:owner/repo.git', 'https://github.com/owner/repo'], + ['git+ssh://git@github.com/owner/repo.git', 'https://github.com/owner/repo'], + ['git@ssh.dev.azure.com:v3/org/proj/repo', 'https://dev.azure.com/org/proj/_git/repo'], + ])('normalises %s', (input, expected) => { + expect(normalizeToHttps(input)).toBe(expected); + }); }); describe('generateGitDiff', () => { @@ -126,15 +136,17 @@ describe('generateGitDiff', () => { expect(result.stats).toEqual({ additions: 0, deletions: 0, filesChanged: 0 }); }); - it('parses name-status output for all statuses', () => { + it('parses NUL-separated name-status output for all statuses', () => { mockExecFileSync.mockImplementation((_bin: string, args: string[]) => { if (args.includes('--name-status')) { - return 'A\tsrc/new.ts\nM\tsrc/modified.ts\nD\tsrc/deleted.ts\nR100\tsrc/old-name.ts\tsrc/renamed.ts\nC100\tsrc/source.ts\tsrc/copied.ts\n'; - } - if (args.includes('--shortstat')) { - return ' 5 files changed, 20 insertions(+), 3 deletions(-)'; + return [ + ...['A', 'src/new.ts', 'M', 'src/modified.ts', 'D', 'src/deleted.ts'], + ...['R100', 'src/old-name.ts', 'src/renamed.ts'], + ...['C100', 'src/source.ts', 'src/copied.ts'], + ...['T', 'src/link.ts', 'U', 'src/conflict.ts', ''], + ].join('\0'); } - return 'diff content'; + return ''; }); const result = generateGitDiff(); @@ -145,13 +157,15 @@ describe('generateGitDiff', () => { { filename: 'src/deleted.ts', status: 'removed' }, { filename: 'src/renamed.ts', status: 'renamed' }, { filename: 'src/copied.ts', status: 'copied' }, + { filename: 'src/link.ts', status: 'changed' }, + { filename: 'src/conflict.ts', status: 'unmerged' }, ]); }); - it('parses shortstat output', () => { + it('sums numstat output, counting binary files without lines', () => { mockExecFileSync.mockImplementation((_bin: string, args: string[]) => { - if (args.includes('--shortstat')) { - return ' 3 files changed, 12 insertions(+), 5 deletions(-)'; + if (args.includes('--numstat')) { + return ['10\t5\ta.ts', '-\t-\timage.png', '2\t0\t', 'old.ts', 'new.ts', ''].join('\0'); } return ''; }); @@ -161,41 +175,48 @@ describe('generateGitDiff', () => { expect(result.stats).toEqual({ additions: 12, deletions: 5, filesChanged: 3 }); }); - it('handles shortstat with only insertions', () => { - mockExecFileSync.mockImplementation((_bin: string, args: string[]) => { - if (args.includes('--shortstat')) { - return ' 1 file changed, 7 insertions(+)'; - } - return ''; - }); + it('runs git with stable options and the C locale', () => { + mockExecFileSync.mockReturnValue(''); - const result = generateGitDiff(); + generateGitDiff(); - expect(result.stats).toEqual({ additions: 7, deletions: 0, filesChanged: 1 }); + expect(mockExecFileSync).toHaveBeenCalledWith( + 'git', + [ + ...['-c', 'core.quotePath=false', '-c', 'diff.relative=false', 'diff'], + ...[ + '--no-color', + '--no-ext-diff', + '--src-prefix=a/', + '--dst-prefix=b/', + '--submodule=short', + ], + ], + expect.objectContaining({ + encoding: 'utf-8', + env: expect.objectContaining({ LC_ALL: 'C' }) as unknown, + }) + ); }); - it('passes --staged flag to git diff', () => { + it('passes --staged flag to every git diff call', () => { mockExecFileSync.mockReturnValue(''); generateGitDiff({ staged: true }); - expect(mockExecFileSync).toHaveBeenCalledWith( - 'git', - ['diff', '--staged'], - expect.objectContaining({ encoding: 'utf-8' }) - ); + const calls = mockExecFileSync.mock.calls as [string, string[]][]; + expect(calls).toHaveLength(3); + expect(calls.every(([, args]) => args.includes('--staged'))).toBe(true); }); - it('passes branch arg as three-dot diff', () => { + it('passes branch arg as three-dot diff to every git diff call', () => { mockExecFileSync.mockReturnValue(''); generateGitDiff({ branch: 'main' }); - expect(mockExecFileSync).toHaveBeenCalledWith( - 'git', - ['diff', 'main...HEAD'], - expect.objectContaining({ encoding: 'utf-8' }) - ); + const calls = mockExecFileSync.mock.calls as [string, string[]][]; + expect(calls).toHaveLength(3); + expect(calls.every(([, args]) => args.includes('main...HEAD'))).toBe(true); }); it('throws when both branch and staged are set', () => { @@ -270,7 +291,7 @@ describe('getRemoteUrl', () => { expect(getRemoteUrl()).toBe('https://github.com/org/repo.git'); expect(mockExecFileSync).toHaveBeenCalledWith( 'git', - ['remote', 'get-url', 'origin'], + ['-c', 'core.quotePath=false', 'remote', 'get-url', 'origin'], expect.objectContaining({ encoding: 'utf-8' }) ); }); @@ -281,7 +302,7 @@ describe('getRemoteUrl', () => { expect(getRemoteUrl('upstream')).toBe('https://github.com/org/repo.git'); expect(mockExecFileSync).toHaveBeenCalledWith( 'git', - ['remote', 'get-url', 'upstream'], + ['-c', 'core.quotePath=false', 'remote', 'get-url', 'upstream'], expect.objectContaining({ encoding: 'utf-8' }) ); }); @@ -293,7 +314,7 @@ describe('getRemoteUrl', () => { expect(mockExecFileSync).toHaveBeenCalledWith( 'git', - ['remote', 'get-url', 'origin'], + ['-c', 'core.quotePath=false', 'remote', 'get-url', 'origin'], expect.objectContaining({ cwd: '/custom/path' }) ); }); diff --git a/packages/core/src/utils/__tests__/model-source.test.ts b/packages/core/src/utils/__tests__/model-source.test.ts index 406e0bc1..45deb2e0 100644 --- a/packages/core/src/utils/__tests__/model-source.test.ts +++ b/packages/core/src/utils/__tests__/model-source.test.ts @@ -108,6 +108,52 @@ describe('parseModelRepo', () => { slug: 'owner/repo', }); }); + + it('does not double the .git suffix on a bare slug', () => { + expect(parseModelRepo('owner/repo.git')).toEqual({ + cloneUrl: 'https://github.com/owner/repo.git', + slug: 'owner/repo', + }); + }); + + it('keeps an SSH remote as the clone URL and derives the slug', () => { + expect(parseModelRepo('git@github.com:org/models.git')).toEqual({ + cloneUrl: 'git@github.com:org/models.git', + slug: 'org/models', + }); + expect(parseModelRepo('ssh://git@gitlab.com:2222/group/sub/models.git')).toEqual({ + cloneUrl: 'ssh://git@gitlab.com:2222/group/sub/models.git', + slug: 'group/sub/models', + }); + }); + + it('keeps a git:// URL as the clone URL', () => { + expect(parseModelRepo('git://git.example.com/group/models.git')).toEqual({ + cloneUrl: 'git://git.example.com/group/models.git', + slug: 'group/models', + }); + }); + + it('drops GitLab and GitHub web suffixes from the slug', () => { + expect(parseModelRepo('https://gitlab.com/group/models/-/tree/main')).toEqual({ + cloneUrl: 'https://gitlab.com/group/models.git', + slug: 'group/models', + }); + expect(parseModelRepo('https://github.com/org/models/tree/main/docs')).toEqual({ + cloneUrl: 'https://github.com/org/models.git', + slug: 'org/models', + }); + }); + + it('strips credentials from HTTPS URLs', () => { + expect(parseModelRepo('https://user:secret@github.com/org/models').cloneUrl).toBe( + 'https://github.com/org/models.git' + ); + }); + + it('rejects input that is not a repository', () => { + expect(() => parseModelRepo('not-a-repo')).toThrow('Invalid model repository'); + }); }); describe('resolveModelSource', () => { @@ -355,4 +401,53 @@ describe('resolveModelSource', () => { expect(message).toContain('https://github.com/bad/repo.git'); } }); + + it('clones http URLs without a token and warns', async () => { + const { mkdtemp, writeFile } = await import('node:fs/promises'); + const { execFile } = await import('child_process'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + vi.mocked(writeFile).mockClear(); + vi.mocked(mkdtemp).mockResolvedValue('/tmp/erode-model-http'); + vi.mocked(execFile).mockImplementation((...args: unknown[]) => { + const cb = args[args.length - 1] as ExecFileCallback | undefined; + if (cb) cb(null, '', ''); + return undefined as never; + }); + + await resolveModelSource('.', 'http://github.com/owner/repo'); + + const [, gitArgs, opts] = vi.mocked(execFile).mock.calls[0] as unknown as [ + string, + string[], + { env: Record }, + ]; + expect(gitArgs).toContain('http://github.com/owner/repo.git'); + expect(gitArgs.join(' ')).not.toContain('@'); + expect(opts.env['GIT_ASKPASS']).toBeUndefined(); + expect(writeFile).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledTimes(1); + warn.mockRestore(); + }); + + it('strips credentials from any scheme in clone error messages', async () => { + const { mkdtemp } = await import('node:fs/promises'); + const { execFile } = await import('child_process'); + vi.mocked(mkdtemp).mockResolvedValue('/tmp/erode-model-err2'); + const raw = + 'fatal: http://u:tok1@h.example/a ssh://git:tok2@h.example/b git+https://u:tok3@h.example/c'; + vi.mocked(execFile).mockImplementation((...args: unknown[]) => { + const cb = args[args.length - 1] as ExecFileCallback | undefined; + if (cb) cb(Object.assign(new Error(raw), { cmd: 'git clone' }), '', ''); + return undefined as never; + }); + + const { message } = (await resolveModelSource('.', 'bad/repo').then( + () => expect.fail('Expected error'), + (e: unknown) => e + )) as Error; + expect(message).not.toMatch(/tok[123]/); + expect(message).toContain('http://h.example/a'); + expect(message).toContain('ssh://h.example/b'); + expect(message).toContain('git+https://h.example/c'); + }); }); diff --git a/packages/core/src/utils/__tests__/repo-locator.test.ts b/packages/core/src/utils/__tests__/repo-locator.test.ts new file mode 100644 index 00000000..8b3bc031 --- /dev/null +++ b/packages/core/src/utils/__tests__/repo-locator.test.ts @@ -0,0 +1,354 @@ +import { afterEach, describe, it, expect, vi } from 'vitest'; + +vi.mock('../config.js', () => ({ + CONFIG: { + github: { baseUrl: 'https://ghe.example.com/api/v3' }, + gitlab: { baseUrl: 'https://gitlab.example.com' }, + bitbucket: { baseUrl: 'https://bitbucket.example.com/rest/api/1.0' }, + }, +})); + +import { CONFIG } from '../config.js'; +import { + parseRepoLocator, + isRepositoryHostUrl, + normalizeRepositoryUrl, + platformForHost, + type RepoLocator, +} from '../repo-locator.js'; + +type Expected = Pick & + Partial>; + +const gh = (owner: string, repo: string, extra: Partial = {}): Expected => ({ + platform: 'github', + host: 'github.com', + owner, + repo, + canonicalUrl: `https://github.com/${owner}/${repo}`, + ...extra, +}); + +const cases: [string, Expected][] = [ + // HTTPS and HTTP + ['https://github.com/Owner/Repo', gh('Owner', 'Repo', { protocol: 'https' })], + ['https://github.com/owner/repo.git', gh('owner', 'repo')], + ['https://github.com/owner/repo/', gh('owner', 'repo')], + ['http://github.com/owner/repo', gh('owner', 'repo', { protocol: 'http' })], + ['https://user:token@github.com/owner/repo.git', gh('owner', 'repo')], + ['https://www.github.com/owner/repo', gh('owner', 'repo')], + ['https://GitHub.com/owner/repo', gh('owner', 'repo')], + // Platform suffixes + ['https://github.com/owner/repo/tree/main/docs', gh('owner', 'repo')], + ['https://github.com/owner/repo/blob/main/src/x.ts', gh('owner', 'repo')], + ['https://github.com/owner/repo/pull/42/files', gh('owner', 'repo')], + // SSH + ['git@github.com:owner/repo.git', gh('owner', 'repo', { protocol: 'ssh' })], + ['alice@github.com:owner/repo', gh('owner', 'repo', { protocol: 'ssh' })], + ['git@github.com-work:owner/repo.git', gh('owner', 'repo')], + ['ssh://git@github.com/owner/repo.git', gh('owner', 'repo', { protocol: 'ssh' })], + ['git+ssh://git@github.com/owner/repo.git', gh('owner', 'repo', { protocol: 'ssh' })], + [ + 'ssh://git@gitlab.example.com:2222/g/p.git', + { + platform: 'gitlab', + host: 'gitlab.example.com', + port: 2222, + owner: 'g', + repo: 'p', + canonicalUrl: 'https://gitlab.example.com/g/p', + }, + ], + // GitLab nested groups and /-/ suffixes + [ + 'https://gitlab.com/group/sub/project/-/tree/main', + { + platform: 'gitlab', + host: 'gitlab.com', + owner: 'group/sub', + repo: 'project', + canonicalUrl: 'https://gitlab.com/group/sub/project', + }, + ], + [ + 'https://www.gitlab.com/group/project/-/merge_requests/3', + { + platform: 'gitlab', + host: 'gitlab.com', + owner: 'group', + repo: 'project', + canonicalUrl: 'https://gitlab.com/group/project', + }, + ], + [ + 'git@gitlab.com:group/sub/project.git', + { + platform: 'gitlab', + host: 'gitlab.com', + owner: 'group/sub', + repo: 'project', + canonicalUrl: 'https://gitlab.com/group/sub/project', + }, + ], + // Bitbucket Cloud + [ + 'https://bitbucket.org/ws/repo/pull-requests/1', + { + platform: 'bitbucket', + host: 'bitbucket.org', + owner: 'ws', + repo: 'repo', + canonicalUrl: 'https://bitbucket.org/ws/repo', + }, + ], + [ + 'git@bitbucket.org:ws/repo.git', + { + platform: 'bitbucket', + host: 'bitbucket.org', + owner: 'ws', + repo: 'repo', + canonicalUrl: 'https://bitbucket.org/ws/repo', + }, + ], + // Bitbucket Server and Data Center + [ + 'https://bitbucket.example.com/projects/KEY/repos/repo/browse', + { + platform: 'bitbucket-server', + host: 'bitbucket.example.com', + owner: 'KEY', + repo: 'repo', + canonicalUrl: 'https://bitbucket.example.com/projects/KEY/repos/repo', + }, + ], + [ + 'https://bitbucket.example.com/scm/key/repo.git', + { + platform: 'bitbucket-server', + host: 'bitbucket.example.com', + owner: 'key', + repo: 'repo', + canonicalUrl: 'https://bitbucket.example.com/projects/key/repos/repo', + }, + ], + [ + 'ssh://git@bitbucket.example.com:7999/key/repo.git', + { + platform: 'bitbucket-server', + host: 'bitbucket.example.com', + port: 7999, + owner: 'key', + repo: 'repo', + canonicalUrl: 'https://bitbucket.example.com/projects/key/repos/repo', + }, + ], + // Azure DevOps + [ + 'https://dev.azure.com/Org/Project/_git/Repo', + { + platform: 'azure-devops', + host: 'dev.azure.com', + owner: 'Org/Project', + repo: 'Repo', + canonicalUrl: 'https://dev.azure.com/Org/Project/_git/Repo', + }, + ], + [ + 'git@ssh.dev.azure.com:v3/Org/Project/Repo', + { + platform: 'azure-devops', + host: 'dev.azure.com', + owner: 'Org/Project', + repo: 'Repo', + canonicalUrl: 'https://dev.azure.com/Org/Project/_git/Repo', + }, + ], + // Configured GitHub Enterprise host + [ + 'https://ghe.example.com/org/repo/pull/7', + { + platform: 'github', + host: 'ghe.example.com', + owner: 'org', + repo: 'repo', + canonicalUrl: 'https://ghe.example.com/org/repo', + }, + ], + // git:// keeps its port out of the canonical URL + [ + 'git://git.example.com:9418/group/project.git', + { + platform: 'unknown', + host: 'git.example.com', + port: 9418, + protocol: 'git', + owner: 'group', + repo: 'project', + canonicalUrl: 'https://git.example.com/group/project', + }, + ], + // Scheme-less host:port is HTTPS with that port, not scp + [ + 'gitlab.example.com:8443/group/proj', + { + platform: 'gitlab', + host: 'gitlab.example.com', + port: 8443, + protocol: 'https', + owner: 'group', + repo: 'proj', + canonicalUrl: 'https://gitlab.example.com:8443/group/proj', + }, + ], + [ + 'git@gitlab.example.com:8443/proj.git', + { + platform: 'gitlab', + host: 'gitlab.example.com', + protocol: 'ssh', + owner: '8443', + repo: 'proj', + canonicalUrl: 'https://gitlab.example.com/8443/proj', + }, + ], + // Unknown hosts keep the full path and an explicit HTTPS port + [ + 'https://code.example.org:8443/team/sub/app.git', + { + platform: 'unknown', + host: 'code.example.org', + port: 8443, + owner: 'team/sub', + repo: 'app', + canonicalUrl: 'https://code.example.org:8443/team/sub/app', + }, + ], +]; + +describe('parseRepoLocator', () => { + it.each(cases)('parses %s', (input, expected) => { + const locator = parseRepoLocator(input); + expect(locator).toMatchObject(expected); + expect(locator?.slug).toBe(`${expected.owner}/${expected.repo}`); + if (expected.port === undefined) expect(locator?.port).toBeUndefined(); + }); + + it.each([ + '', + 'not-a-url', + 'owner/repo', + 'docs/readme.md', + 'https://github.com/owner', + 'https://dev.azure.com/org/project', + 'ftp://github.com/owner/repo', + 'C:\\repos\\app', + 'localhost:repo', + ])('returns null for %j', (input) => { + expect(parseRepoLocator(input)).toBeNull(); + }); + + it.each([ + ['owner/repo', 'owner', 'repo'], + ['owner/repo.git', 'owner', 'repo'], + ['owner/repo///', 'owner', 'repo'], + ])('accepts %s as GitHub shorthand when allowed', (input, owner, repo) => { + expect(parseRepoLocator(input, { allowShorthand: true })).toMatchObject({ + platform: 'github', + protocol: 'shorthand', + owner, + repo, + canonicalUrl: `https://github.com/${owner}/${repo}`, + }); + }); + + it('never keeps credentials in the canonical URL', () => { + const locator = parseRepoLocator('https://x-access-token:secret@github.com/o/r.git'); + expect(JSON.stringify(locator)).not.toContain('secret'); + }); +}); + +describe('repository matching with configured hosts', () => { + it('maps API base URLs to their web hosts', () => { + expect(platformForHost('ghe.example.com')).toBe('github'); + expect(platformForHost('gitlab.example.com')).toBe('gitlab'); + expect(platformForHost('bitbucket.example.com')).toBe('bitbucket-server'); + expect(platformForHost('api.github.com')).toBe('unknown'); + }); + + it('accepts model links to self-hosted instances', () => { + expect(isRepositoryHostUrl('https://gitlab.example.com/group/project')).toBe(true); + expect(isRepositoryHostUrl('https://ghe.example.com/org/repo')).toBe(true); + expect(isRepositoryHostUrl('https://code.example.org/team/app')).toBe(false); + }); + + it('matches an SSH remote with a web link regardless of case', () => { + expect(normalizeRepositoryUrl('git@gitlab.example.com:Group/Project.git')).toBe( + normalizeRepositoryUrl('https://gitlab.example.com/group/project/-/tree/main') + ); + expect(normalizeRepositoryUrl('git@github.com-work:Owner/Repo.git')).toBe( + 'https://github.com/owner/repo' + ); + }); + + it('ignores ports when matching an SSH remote with a web link', () => { + expect(normalizeRepositoryUrl('ssh://git@gitlab.example.com:2222/g/p.git')).toBe( + normalizeRepositoryUrl('https://gitlab.example.com:8443/g/p') + ); + }); + + it('does not treat a dotted host with a dash as an SSH alias', () => { + expect(parseRepoLocator('git@github.com-mirror.corp.example:o/r.git')).toMatchObject({ + platform: 'unknown', + host: 'github.com-mirror.corp.example', + }); + }); +}); + +describe('self-hosted base paths', () => { + const config = CONFIG as unknown as Record<'gitlab' | 'bitbucket', { baseUrl: string }>; + const saved = { gitlab: config.gitlab.baseUrl, bitbucket: config.bitbucket.baseUrl }; + afterEach(() => { + config.gitlab.baseUrl = saved.gitlab; + config.bitbucket.baseUrl = saved.bitbucket; + }); + + it('strips the GitLab context path from owner and keeps it in the canonical URL', () => { + config.gitlab.baseUrl = 'https://example.com/gitlab/api/v4'; + expect(parseRepoLocator('https://example.com/gitlab/group/proj/-/tree/main')).toMatchObject({ + platform: 'gitlab', + owner: 'group', + repo: 'proj', + slug: 'group/proj', + canonicalUrl: 'https://example.com/gitlab/group/proj', + }); + expect(parseRepoLocator('git@example.com:group/proj.git')).toMatchObject({ + platform: 'gitlab', + slug: 'group/proj', + canonicalUrl: 'https://example.com/gitlab/group/proj', + }); + expect(parseRepoLocator('https://example.com/other/proj')?.platform).toBe('unknown'); + expect(parseRepoLocator('git@example.com:gitlab/proj.git')).toMatchObject({ + platform: 'gitlab', + slug: 'gitlab/proj', + canonicalUrl: 'https://example.com/gitlab/gitlab/proj', + }); + }); + + it('tells GitLab and Bitbucket Server apart on one host by base path', () => { + config.gitlab.baseUrl = 'https://example.com/gitlab'; + config.bitbucket.baseUrl = 'https://example.com/bitbucket/rest/api/1.0'; + expect(parseRepoLocator('https://example.com/bitbucket/projects/KEY/repos/r')).toMatchObject({ + platform: 'bitbucket-server', + slug: 'KEY/r', + canonicalUrl: 'https://example.com/bitbucket/projects/KEY/repos/r', + }); + expect(parseRepoLocator('https://example.com/gitlab/g/p')?.platform).toBe('gitlab'); + }); + + it('picks up a changed base URL between calls', () => { + expect(platformForHost('git.corp.example')).toBe('unknown'); + config.gitlab.baseUrl = 'https://git.corp.example'; + expect(platformForHost('git.corp.example')).toBe('gitlab'); + }); +}); diff --git a/packages/core/src/adapters/__tests__/url-utils.test.ts b/packages/core/src/utils/__tests__/repo-matching.test.ts similarity index 99% rename from packages/core/src/adapters/__tests__/url-utils.test.ts rename to packages/core/src/utils/__tests__/repo-matching.test.ts index 299b691f..a243f9eb 100644 --- a/packages/core/src/adapters/__tests__/url-utils.test.ts +++ b/packages/core/src/utils/__tests__/repo-matching.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { isRepositoryHostUrl, normalizeRepositoryUrl } from '../url-utils.js'; +import { isRepositoryHostUrl, normalizeRepositoryUrl } from '../repo-locator.js'; describe('isRepositoryHostUrl', () => { it('should accept GitHub URLs', () => { diff --git a/packages/core/src/utils/diff-sections.ts b/packages/core/src/utils/diff-sections.ts new file mode 100644 index 00000000..026c5509 --- /dev/null +++ b/packages/core/src/utils/diff-sections.ts @@ -0,0 +1,142 @@ +/** + * Splits a unified git diff into per-file sections and resolves the path each + * section belongs to. The header `diff --git ` is ambiguous when a + * path contains ` b/`, and its prefixes depend on `diff.noprefix` and + * `diff.mnemonicPrefix`, so the resolver prefers unambiguous lines and only + * falls back to splitting the header. + */ + +export interface DiffSection { + /** Path of the file after the change, or undefined when it cannot be resolved. */ + path: string | undefined; + text: string; +} + +const COMBINED_STARTS = ['diff --cc ', 'diff --combined ', '* Unmerged path ']; +const SECTION_STARTS = ['diff --git ', ...COMBINED_STARTS]; + +// Default, mnemonic (index/worktree/commit/object), --no-index, and no-prefix. +const PREFIX_PAIRS: readonly (readonly [string, string])[] = [ + ['a/', 'b/'], + ['i/', 'w/'], + ['c/', 'w/'], + ['c/', 'i/'], + ['o/', 'w/'], + ['1/', '2/'], + ['', ''], +]; + +const SRC_PREFIXES = PREFIX_PAIRS.map(([src]) => src); +const DST_PREFIXES = PREFIX_PAIRS.map(([, dst]) => dst); + +const C_ESCAPES: Record = { + a: 7, + b: 8, + t: 9, + n: 10, + v: 11, + f: 12, + r: 13, + '"': 34, + '\\': 92, +}; + +/** Decode a path that git quoted C-style (`"caf\303\251.ts"`); other input is returned as is. */ +export function unquoteGitPath(value: string): string { + if (value.length < 2 || !value.startsWith('"') || !value.endsWith('"')) return value; + const body = value.slice(1, -1); + const bytes: number[] = []; + for (let i = 0; i < body.length; i++) { + const ch = body.charAt(i); + if (ch !== '\\') { + bytes.push(...Buffer.from(ch, 'utf-8')); + continue; + } + const next = body.charAt(i + 1); + const octal = /^[0-7]{3}/.exec(body.slice(i + 1)); + if (octal) { + bytes.push(parseInt(octal[0], 8)); + i += 3; + } else { + bytes.push(C_ESCAPES[next] ?? next.charCodeAt(0)); + i += 1; + } + } + return Buffer.from(bytes).toString('utf-8'); +} + +function stripPrefix(path: string, prefixes: readonly string[]): string { + const prefix = prefixes.find((p) => p && path.startsWith(p)); + return prefix ? path.slice(prefix.length) : path; +} + +/** Resolve ` ` by length, which is exact even when the path contains spaces. */ +function symmetricHeaderPath(rest: string): string | undefined { + for (const [src, dst] of PREFIX_PAIRS) { + const doubled = rest.length - 1 - src.length - dst.length; + if (doubled < 2 || doubled % 2 !== 0) continue; + const path = rest.slice(src.length, src.length + doubled / 2); + if (rest === `${src}${path} ${dst}${path}`) return path; + } + return undefined; +} + +/** Read the second token of a header whose first token is C-quoted. */ +function quotedHeaderPath(rest: string): string | undefined { + if (!rest.startsWith('"')) return undefined; + let end = 1; + while (end < rest.length && rest[end] !== '"') end += rest[end] === '\\' ? 2 : 1; + const second = rest.slice(end + 2); + return second ? stripPrefix(unquoteGitPath(second), DST_PREFIXES) : undefined; +} + +function fileLinePath(lines: string[], marker: '+++ ' | '--- '): string | undefined { + const line = lines.find((l) => l.startsWith(marker)); + if (!line) return undefined; + const raw = line.slice(marker.length).replace(/\t$/, ''); + if (raw === '/dev/null') return undefined; + return stripPrefix(unquoteGitPath(raw), marker === '+++ ' ? DST_PREFIXES : SRC_PREFIXES); +} + +function resolveSectionPath(lines: string[]): string | undefined { + const header = lines[0] ?? ''; + for (const start of COMBINED_STARTS) { + if (header.startsWith(start)) return unquoteGitPath(header.slice(start.length)); + } + if (!header.startsWith('diff --git ')) return undefined; + + // Extended headers come before the first hunk; a content line cannot start with these. + const firstHunk = lines.findIndex((l) => l.startsWith('@@')); + const meta = firstHunk === -1 ? lines : lines.slice(0, firstHunk); + const renamed = meta.find((l) => l.startsWith('rename to ') || l.startsWith('copy to ')); + if (renamed) return unquoteGitPath(renamed.slice(renamed.indexOf(' to ') + 4)); + + const rest = header.slice('diff --git '.length); + const path = + symmetricHeaderPath(rest) ?? + quotedHeaderPath(rest) ?? + fileLinePath(meta, '+++ ') ?? + fileLinePath(meta, '--- '); + if (path) return path; + + const bIdx = rest.lastIndexOf(' b/'); + return bIdx === -1 ? undefined : rest.slice(bIdx + 3); +} + +/** Split a unified diff into sections, one per `diff --git` (or combined/unmerged) header. */ +export function splitDiffSections(diff: string): DiffSection[] { + const sections: string[][] = []; + let current: string[] | undefined; + for (const line of diff.split('\n')) { + if (SECTION_STARTS.some((s) => line.startsWith(s))) { + current = [line]; + sections.push(current); + } else if (current) { + current.push(line); + } + } + return sections.map((lines) => ({ + path: resolveSectionPath(lines), + text: lines.join('\n') + '\n', + })); +} diff --git a/packages/core/src/utils/git-diff.ts b/packages/core/src/utils/git-diff.ts index bf922d2f..328b8037 100644 --- a/packages/core/src/utils/git-diff.ts +++ b/packages/core/src/utils/git-diff.ts @@ -1,5 +1,7 @@ import { execFileSync } from 'child_process'; import { ErodeError, ErrorCode } from '../errors.js'; +import { splitDiffSections } from './diff-sections.js'; +import { parseRepoLocator } from './repo-locator.js'; export interface GitDiffOptions { /** Only include staged changes. */ @@ -38,8 +40,23 @@ const STATUS_MAP: Record = { D: 'removed', R: 'renamed', C: 'copied', + T: 'changed', + U: 'unmerged', }; +/** + * Options that make porcelain `git diff` output independent of the user's git + * config (`diff.noprefix`, `diff.mnemonicPrefix`, `color.diff`, `diff.external`, + * `diff.relative`, `diff.submodule`), so it can be parsed reliably. + */ +const STABLE_DIFF_OPTIONS = [ + '--no-color', + '--no-ext-diff', + '--src-prefix=a/', + '--dst-prefix=b/', + '--submodule=short', +]; + function classifyGitError(message: string): ErrorCode { if (/not a git repository/i.test(message)) return ErrorCode.IO_DIR_NOT_FOUND; if (/permission denied/i.test(message)) return ErrorCode.IO_PERMISSION_DENIED; @@ -48,11 +65,13 @@ function classifyGitError(message: string): ErrorCode { function run(args: string[], cwd: string): string { try { - return execFileSync('git', args, { + // LC_ALL=C keeps git messages in English; quotePath=false keeps non-ASCII paths unescaped. + return execFileSync('git', ['-c', 'core.quotePath=false', ...args], { cwd, encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024, - }).trim(); + env: { ...process.env, LC_ALL: 'C' }, + }); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new ErodeError( @@ -63,34 +82,45 @@ function run(args: string[], cwd: string): string { } } +function splitNul(output: string): string[] { + const fields = output.split('\0'); + if (fields.at(-1) === '') fields.pop(); + return fields; +} + /** - * Parse file list from `git diff --name-status` output. - * Each line is `\t` (e.g. `M\tsrc/index.ts`). + * Parse `git diff --name-status -z` output: `\0\0`, or + * `\0\0\0` for renames and copies. */ function parseNameStatus(output: string): GitDiffFile[] { - if (!output) return []; - return output.split('\n').reduce((acc, line) => { - const match = /^([AMDRC])\d*\t(?:.+\t)?(.+)$/.exec(line); - if (match?.[1] && match[2]) { - acc.push({ filename: match[2], status: STATUS_MAP[match[1]] ?? 'modified' }); - } - return acc; - }, []); + const fields = splitNul(output); + const files: GitDiffFile[] = []; + for (let i = 0; i < fields.length;) { + const code = (fields[i] ?? '').charAt(0); + const pathCount = code === 'R' || code === 'C' ? 2 : 1; + const filename = fields[i + pathCount]; + if (filename) files.push({ filename, status: STATUS_MAP[code] ?? 'modified' }); + i += pathCount + 1; + } + return files; } /** - * Parse `git diff --shortstat` output to extract additions, deletions, and file count. - * Example: " 3 files changed, 12 insertions(+), 5 deletions(-)" + * Parse `git diff --numstat -z` output: `\t\t\0`, or + * `\t\t\0\0\0` for renames and copies. Binary files report `-`. */ -function parseShortstat(output: string): DiffStats { - const filesMatch = /(\d+) files? changed/.exec(output); - const addMatch = /(\d+) insertions?/.exec(output); - const delMatch = /(\d+) deletions?/.exec(output); - return { - filesChanged: filesMatch?.[1] ? Number(filesMatch[1]) : 0, - additions: addMatch?.[1] ? Number(addMatch[1]) : 0, - deletions: delMatch?.[1] ? Number(delMatch[1]) : 0, - }; +function parseNumstat(output: string): DiffStats { + const fields = splitNul(output); + const stats: DiffStats = { additions: 0, deletions: 0, filesChanged: 0 }; + for (let i = 0; i < fields.length; i++) { + const match = /^(-|\d+)\t(-|\d+)\t(.*)$/s.exec(fields[i] ?? ''); + if (!match) continue; + stats.filesChanged++; + stats.additions += match[1] === '-' ? 0 : Number(match[1]); + stats.deletions += match[2] === '-' ? 0 : Number(match[2]); + if (match[3] === '') i += 2; + } + return stats; } function buildDiffArgs(options: GitDiffOptions): string[] { @@ -116,91 +146,63 @@ function buildDiffArgs(options: GitDiffOptions): string[] { /** Generate a git diff from the local working tree. */ export function generateGitDiff(options: GitDiffOptions = {}): GitDiffResult { const cwd = options.cwd ?? process.cwd(); - const args = buildDiffArgs(options); - - const diff = run(['diff', ...args], cwd); - const nameStatus = run(['diff', ...args, '--name-status'], cwd); - const shortstat = run(['diff', ...args, '--shortstat'], cwd); + // -c instead of --no-relative, which needs git 2.28 or later. + const args = [ + '-c', + 'diff.relative=false', + 'diff', + ...STABLE_DIFF_OPTIONS, + ...buildDiffArgs(options), + ]; + + const diff = run(args, cwd).trim(); + const nameStatus = run([...args, '--name-status', '-z'], cwd); + const numstat = run([...args, '--numstat', '-z'], cwd); return { diff, files: parseNameStatus(nameStatus), - stats: parseShortstat(shortstat), + stats: parseNumstat(numstat), }; } /** - * Filter a unified diff to include only segments for the given filenames. - * Splits on `diff --git` headers and reassembles matching segments. + * Filter a unified diff to include only sections for the given filenames. + * A type change produces two sections for one file; both are kept. */ export function filterDiffByFiles(diff: string, files: { filename: string }[]): string { if (!diff || files.length === 0) return ''; const allowed = new Set(files.map((f) => f.filename)); - const segments: string[] = []; - const marker = 'diff --git '; - - let current = ''; - for (const line of diff.split('\n')) { - if (line.startsWith(marker)) { - if (current) segments.push(current); - current = line + '\n'; - } else { - current += line + '\n'; - } - } - if (current) segments.push(current); - - return segments - .filter((seg) => { - const header = seg.split('\n')[0] ?? ''; - const bIdx = header.lastIndexOf(' b/'); - if (bIdx === -1) return false; - const filename = header.slice(bIdx + 3); - return allowed.has(filename); - }) + return splitDiffSections(diff) + .filter((section) => section.path !== undefined && allowed.has(section.path)) + .map((section) => section.text) .join('') .trimEnd(); } /** - * Parse file paths from a unified diff. - * Looks for `diff --git a/ b/` headers. + * Parse file paths from a unified diff. Accepts the default `a/` and `b/` + * prefixes, mnemonic prefixes, and `--no-prefix` output. */ export function parseFilesFromDiff(diff: string): GitDiffFile[] { const files: GitDiffFile[] = []; const seen = new Set(); - const prefix = 'diff --git a/'; - for (const line of diff.split('\n')) { - if (!line.startsWith(prefix)) continue; - const rest = line.slice(prefix.length); - const bIdx = rest.lastIndexOf(' b/'); - if (bIdx === -1) continue; - const filename = rest.slice(bIdx + 3); - if (filename && !seen.has(filename)) { - seen.add(filename); - files.push({ filename, status: 'modified' }); + for (const { path } of splitDiffSections(diff)) { + if (path && !seen.has(path)) { + seen.add(path); + files.push({ filename: path, status: 'modified' }); } } return files; } -/** Convert SSH-style git remote URLs to HTTPS, stripping any embedded credentials. */ +/** + * Convert a git remote (HTTPS, `ssh://` or scp-style) to the repository's + * canonical HTTPS URL, without credentials. Input that is not a repository + * location is returned without a trailing `.git`. + */ export function normalizeToHttps(remote: string): string { - // git@github.com:owner/repo.git → https://github.com/owner/repo - const sshMatch = /^git@([^:]+):(.+?)(?:\.git)?$/.exec(remote); - if (sshMatch?.[1] && sshMatch[2]) { - return `https://${sshMatch[1]}/${sshMatch[2]}`; - } - // HTTPS — strip credentials and trailing .git - try { - const url = new URL(remote); - url.username = ''; - url.password = ''; - url.pathname = url.pathname.replace(/\.git$/, ''); - return url.toString().replace(/\/$/, ''); - } catch { - return remote.replace(/\.git$/, ''); - } + return parseRepoLocator(remote)?.canonicalUrl ?? remote.trim().replace(/\.git$/, ''); } /** Read the URL of a named git remote (defaults to `origin`). */ @@ -212,35 +214,16 @@ export function getRemoteUrl(remote = 'origin', cwd?: string): string { 'Remote names starting with a dash could be interpreted as git flags. Use a valid remote name.' ); } - return run(['remote', 'get-url', remote], cwd ?? process.cwd()); + return run(['remote', 'get-url', remote], cwd ?? process.cwd()).trim(); } /** * Parse the repository owner and name from a git remote URL. - * Supports HTTPS and SSH formats. + * Supports HTTPS, `ssh://` and scp-style remotes. */ export function parseRepoFromRemote(remoteUrl: string): RepoIdentifier { - // HTTPS: https://github.com/owner/repo.git or https://github.com/owner/repo - try { - const url = new URL(remoteUrl); - const path = url.pathname - .replace(/^\//, '') - .replace(/\.git$/, '') - .replace(/\/$/, ''); - const parts = path.split('/'); - const repo = parts.at(-1); - const owner = parts.slice(0, -1).join('/'); - if (owner && repo) { - return { owner, repo }; - } - } catch { - // Not a valid URL, try SSH format below - } - // SSH: git@github.com:owner/repo.git - const sshMatch = /^[^@]+@[^:]+:(.+)\/([^/]+?)(?:\.git)?$/.exec(remoteUrl); - if (sshMatch?.[1] && sshMatch[2]) { - return { owner: sshMatch[1], repo: sshMatch[2] }; - } + const locator = parseRepoLocator(remoteUrl); + if (locator) return { owner: locator.owner, repo: locator.repo }; throw new ErodeError( `Cannot parse repository from remote URL: ${remoteUrl}`, ErrorCode.INPUT_INVALID, diff --git a/packages/core/src/utils/model-source.ts b/packages/core/src/utils/model-source.ts index a9a2e288..f05474fa 100644 --- a/packages/core/src/utils/model-source.ts +++ b/packages/core/src/utils/model-source.ts @@ -6,16 +6,10 @@ import { promisify } from 'node:util'; import { ConfigurationError, ErodeError, ErrorCode } from '../errors.js'; import { CONFIG } from './config.js'; import { redactUrlCredentials } from './url-credentials.js'; -import { detectPlatform } from '../platforms/platform-factory.js'; +import { parseRepoLocator, type RepoPlatform } from './repo-locator.js'; const execFileAsync = promisify(execFile); -function stripTrailingSlashes(s: string): string { - let end = s.length; - while (end > 0 && s[end - 1] === '/') end--; - return s.slice(0, end); -} - export interface ResolvedModelSource { /** Absolute path to the local directory containing model files. */ localPath: string; @@ -46,15 +40,22 @@ export async function resolveModelSource( }; } - const { cloneUrl, slug } = parseModelRepo(modelRepo); + const { cloneUrl, slug, platform, asGiven } = locateModelRepo(modelRepo); const ref = options.ref ?? 'main'; validateRef(ref); - const token = resolveToken(cloneUrl); + let token = asGiven ? undefined : resolveToken(platform); + if (token && !cloneUrl.startsWith('https://')) { + console.warn( + `[erode] Cloning ${cloneUrl} without credentials: the access token is never sent over plain http.` + ); + token = undefined; + } + const effectiveUrl = token ? injectAuthUsername(cloneUrl, platform) : cloneUrl; const tmpDir = await mkdtemp(join(tmpdir(), 'erode-model-')); try { - await cloneRepo(cloneUrl, tmpDir, ref, token); + await cloneRepo(effectiveUrl, cloneUrl, tmpDir, ref, token); } catch (error) { await rm(tmpDir, { recursive: true, force: true }); throw error; @@ -75,94 +76,76 @@ export async function resolveModelSource( /** * Parse a model repo argument into a clone URL and `owner/repo` slug. * - * Accepts: - * - Full URLs: `https://github.com/owner/repo`, `https://gitlab.com/group/project` - * - Slugs: `owner/repo` (infers GitHub) + * Accepts anything `parseRepoLocator` does, plus `owner/repo` (GitHub): + * - HTTPS URLs, including web links such as `.../-/tree/main` or `.../tree/main` + * - SSH remotes (`git@host:owner/repo.git`, `ssh://git@host:2222/owner/repo.git`). + * These are cloned over SSH as given, so the user's keys and host aliases + * apply; no token is used. `git://` URLs are also cloned as given. + * - `http://` URLs are cloned without a token. */ export function parseModelRepo(modelRepo: string): { cloneUrl: string; slug: string } { - // Full URL - if (/^https?:\/\//.test(modelRepo)) { - const parsed = new URL(modelRepo); - parsed.username = ''; - parsed.password = ''; - parsed.search = ''; - parsed.hash = ''; - const slug = extractSlugFromUrl(modelRepo); - parsed.pathname = `/${slug}.git`; - return { cloneUrl: parsed.toString(), slug }; - } - - // Bare slug — assume GitHub - const slug = stripTrailingSlashes(modelRepo); - return { cloneUrl: `https://github.com/${slug}.git`, slug }; + const { cloneUrl, slug } = locateModelRepo(modelRepo); + return { cloneUrl, slug }; } -function extractSlugFromUrl(url: string): string { - const parsed = new URL(url); - const path = parsed.pathname.replace(/^\//, '').replace(/\.git\/?$/, ''); - return stripTrailingSlashes(path); -} - -function resolveToken(cloneUrl: string): string | undefined { - try { - const platform = detectPlatform(cloneUrl); - switch (platform) { - case 'github': - return CONFIG.github.modelRepoPrToken ?? CONFIG.github.token; - case 'gitlab': - return CONFIG.gitlab.token; - case 'bitbucket': - return CONFIG.bitbucket.token; - default: - return undefined; - } - } catch (error) { - if (CONFIG.debug.verbose) { - console.error( - '[model-source] Platform detection failed, proceeding without auth:', - String(error) - ); - } - return undefined; +function locateModelRepo(modelRepo: string): { + cloneUrl: string; + slug: string; + platform: RepoPlatform; + /** Clone the input unchanged and without a token (SSH and `git://`). */ + asGiven: boolean; +} { + const locator = parseRepoLocator(modelRepo, { allowShorthand: true }); + if (!locator) { + throw new ConfigurationError( + `Invalid model repository: ${modelRepo}. Use owner/repo, an HTTPS URL, or an SSH remote.` + ); + } + const { slug, platform } = locator; + if (locator.protocol === 'ssh' || locator.protocol === 'git') { + return { cloneUrl: modelRepo.trim(), slug, platform, asGiven: true }; + } + let cloneUrl = `${locator.canonicalUrl}.git`; + if (platform === 'azure-devops') cloneUrl = locator.canonicalUrl; + if (platform === 'bitbucket-server') { + cloneUrl = locator.canonicalUrl.replace(/\/projects\/([^/]+)\/repos\//, '/scm/$1/') + '.git'; } + if (locator.protocol === 'http') cloneUrl = cloneUrl.replace(/^https:/, 'http:'); + return { cloneUrl, slug, platform, asGiven: false }; } -function authUsername(cloneUrl: string): string { - try { - const platform = detectPlatform(cloneUrl); - switch (platform) { - case 'github': - return 'x-access-token'; - case 'gitlab': - return 'oauth2'; - case 'bitbucket': - return 'x-token-auth'; - default: - return 'token'; - } - } catch (error) { - if (CONFIG.debug.verbose) { - console.error( - '[model-source] Platform detection failed, defaulting to generic auth:', - String(error) - ); - } - return 'token'; +function resolveToken(platform: RepoPlatform): string | undefined { + switch (platform) { + case 'github': + return CONFIG.github.modelRepoPrToken ?? CONFIG.github.token; + case 'gitlab': + return CONFIG.gitlab.token; + case 'bitbucket': + case 'bitbucket-server': + return CONFIG.bitbucket.token; + default: + return undefined; } } -function injectAuthUsername(cloneUrl: string): string { - const user = authUsername(cloneUrl); - return cloneUrl.replace('https://', `https://${user}@`); +const AUTH_USERNAMES: Partial> = { + github: 'x-access-token', + gitlab: 'oauth2', + bitbucket: 'x-token-auth', +}; + +function injectAuthUsername(cloneUrl: string, platform: RepoPlatform): string { + const user = AUTH_USERNAMES[platform] ?? 'token'; + return cloneUrl.replace(/^https:\/\//, `https://${user}@`); } async function cloneRepo( + effectiveUrl: string, cloneUrl: string, targetDir: string, ref: string, token?: string ): Promise { - const effectiveUrl = token ? injectAuthUsername(cloneUrl) : cloneUrl; const args = ['clone', '--depth', '1', '--branch', ref, '--', effectiveUrl, targetDir]; const env: Record = { ...process.env } as Record; diff --git a/packages/core/src/utils/repo-locator.ts b/packages/core/src/utils/repo-locator.ts new file mode 100644 index 00000000..0f24e9cc --- /dev/null +++ b/packages/core/src/utils/repo-locator.ts @@ -0,0 +1,354 @@ +/** + * One parser for repository identity, shared by git remotes, model links, + * `--model-repo`, `--repo` and PR URLs, so they agree within a run. + * + * Case: hosts are lowercased. Path segments keep their original case in + * `owner`, `repo`, `slug` and `canonicalUrl`, because API calls and display + * use them. GitHub, GitLab, Bitbucket and Azure DevOps treat paths as + * case-insensitive, so `repositoryMatchKey` lowercases the whole URL for + * comparing a remote with model links. + * + * Credentials: userinfo (`user:token@`, `git@`) is never copied into the result. + * + * Self-hosted instances come from `ERODE_*_BASE_URL`. Those settings hold API + * URLs, so the web base path is assumed to be the path before the API part: + * - GitHub: `https://ghe.example.com/api/v3`; a leading `api.` is dropped from + * the host and `/api/...` from the path. + * - GitLab: the instance URL, e.g. `https://example.com/gitlab`; a pasted + * `/api/v4` is dropped. + * - Bitbucket Data Center/Server: `https://example.com/bitbucket/rest/api/1.0`; + * `/rest/...` is dropped. + * Web URLs on such a host must start with the base path, which is stripped + * before reading owner and repo and kept in `canonicalUrl`. SSH remotes do + * not carry it, so they match on the host alone and keep their full path. + * + * SSH host aliases are only resolved in the `host-suffix` form + * (`github.com-work`); `ssh -G` is not consulted. + */ +import { CONFIG } from './config.js'; + +export type RepoPlatform = + 'github' | 'gitlab' | 'bitbucket' | 'bitbucket-server' | 'azure-devops' | 'unknown'; + +export interface RepoLocator { + platform: RepoPlatform; + /** Lowercase host without `www.`; SSH host aliases such as `github.com-work` are resolved. */ + host: string; + /** Port given in the input. For SSH and `git://` input it is not part of `canonicalUrl`. */ + port?: number; + /** Transport of the input; `shorthand` for `owner/repo`, `git` for `git://`. */ + protocol: 'https' | 'http' | 'ssh' | 'git' | 'shorthand'; + /** Repository path segments, e.g. `['group', 'sub', 'project']` or `['org', 'project', 'repo']` for Azure. */ + segments: string[]; + /** Everything before the repository name: owner, workspace, nested group, Bitbucket project key or Azure `org/project`. */ + owner: string; + repo: string; + /** `https://host[:port]/` without credentials, `.git`, platform suffixes or a trailing slash. */ + canonicalUrl: string; + /** `owner/repo`. */ + slug: string; +} + +export interface ParseRepoLocatorOptions { + /** Accept `owner/repo` as a GitHub repository. Off by default so relative links are not taken for repos. */ + allowShorthand?: boolean; +} + +const BUILT_IN_HOSTS: Record = { + 'github.com': 'github', + 'gitlab.com': 'gitlab', + 'bitbucket.org': 'bitbucket', + 'dev.azure.com': 'azure-devops', + 'ssh.dev.azure.com': 'azure-devops', +}; + +function splitPath(path: string): string[] { + return path.split('/').filter(Boolean); +} + +interface HostBase { + host: string; + /** Web base path segments, e.g. `['gitlab']` for `https://example.com/gitlab`. */ + basePath: string[]; + platform: RepoPlatform; +} + +interface HostRegistry { + hosts: Map; + bases: HostBase[]; +} + +function normalizeHost(host: string): string { + return host.toLowerCase().replace(/^www\./, ''); +} + +function configuredBase( + url: string | undefined, + platform: RepoPlatform, + apiSegment: string +): HostBase | undefined { + if (!url) return undefined; + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return undefined; + } + let host = normalizeHost(parsed.hostname); + if (platform === 'github') host = host.replace(/^api\./, ''); + if (host in BUILT_IN_HOSTS || host === 'api.bitbucket.org') return undefined; + const path = splitPath(parsed.pathname); + const api = path.findIndex((s) => s.toLowerCase() === apiSegment); + return { host, basePath: api === -1 ? path : path.slice(0, api), platform }; +} + +let registryCache: { key: string; registry: HostRegistry } | undefined; + +/** Hosts from built-ins plus the self-hosted instances configured via `ERODE_*_BASE_URL`. */ +function repositoryHosts(): HostRegistry { + const urls = [CONFIG.github.baseUrl, CONFIG.gitlab.baseUrl, CONFIG.bitbucket.baseUrl]; + const key = JSON.stringify(urls); + if (registryCache?.key === key) return registryCache.registry; + + const [github, gitlab, bitbucket] = urls; + const bases = [ + configuredBase(github, 'github', 'api'), + configuredBase(gitlab, 'gitlab', 'api'), + configuredBase(bitbucket, 'bitbucket-server', 'rest'), + ].filter((b): b is HostBase => b !== undefined); + const hosts = new Map(Object.entries(BUILT_IN_HOSTS)); + for (const base of bases) { + if (!hosts.has(base.host)) hosts.set(base.host, base.platform); + } + const registry = { hosts, bases }; + registryCache = { key, registry }; + return registry; +} + +function startsWithPath(path: string[], prefix: string[]): boolean { + return prefix.every((p, i) => path[i]?.toLowerCase() === p.toLowerCase()); +} + +/** + * The configured instance a location belongs to. Web URLs must carry the base + * path; SSH and `git://` remotes never do, so they match on the host alone. + */ +function matchBase( + bases: HostBase[], + host: string, + path: string[], + web: boolean +): HostBase | null | undefined { + const onHost = bases.filter((b) => b.host === host); + if (onHost.length === 0) return undefined; + if (!web) return onHost[0]; + const matching = onHost + .filter((b) => startsWithPath(path, b.basePath)) + .sort((a, b) => b.basePath.length - a.basePath.length); + return matching[0] ?? null; +} + +function resolveHost( + rawHost: string, + hosts: Map, + isSsh: boolean +): [string, RepoPlatform] { + const host = normalizeHost(rawHost); + const known = hosts.get(host); + if (known) return [host, known]; + // SSH config aliases like `github.com-work` point at the host before the suffix. + const alias = isSsh ? /^(.+\.[a-z]+)-[\w-]+$/.exec(host)?.[1] : undefined; + const aliased = alias ? hosts.get(alias) : undefined; + if (alias && aliased) return [alias, aliased]; + return [host, 'unknown']; +} + +interface RawLocation { + host: string; + port?: number; + protocol: RepoLocator['protocol']; + path: string[]; +} + +const SCHEME_PROTOCOLS: Record = { + 'https:': 'https', + 'http:': 'http', + 'ssh:': 'ssh', + 'git+ssh:': 'ssh', + 'ssh+git:': 'ssh', + 'git:': 'git', +}; + +function readLocation(input: string, allowShorthand: boolean): RawLocation | undefined { + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(input)) { + let url: URL; + try { + url = new URL(input); + } catch { + return undefined; + } + const protocol = SCHEME_PROTOCOLS[url.protocol]; + if (!protocol || !url.hostname) return undefined; + return { + host: url.hostname, + ...(url.port ? { port: Number(url.port) } : {}), + protocol, + path: splitPath(url.pathname), + }; + } + // scp-like `user@host:path`. A user or a dotted host is required so that + // Windows drive letters and bare words are not read as hosts. + const scp = /^(?:([^@/\s]+)@)?([^:/\s]+):(?!\/\/)(.+)$/.exec(input); + if (scp?.[2] && scp[3] && (scp[1] || scp[2].includes('.'))) { + // Without a user, `host:8443/group/repo` is a host and port, not scp. + const port = scp[1] ? undefined : /^(\d+)\/(.+)$/.exec(scp[3]); + if (port?.[1] && port[2]) { + return { host: scp[2], port: Number(port[1]), protocol: 'https', path: splitPath(port[2]) }; + } + return { host: scp[2], protocol: 'ssh', path: splitPath(scp[3]) }; + } + if (allowShorthand && /^[\w.-]+\/[\w.-]+\/*$/.test(input)) { + return { host: 'github.com', protocol: 'shorthand', path: splitPath(input) }; + } + return undefined; +} + +function stripGitSuffix(segment: string): string { + return segment.replace(/\.git$/i, ''); +} + +interface RepoPath { + /** Segments that identify the repository. */ + segments: string[]; + /** Path used in `canonicalUrl`. */ + canonicalPath: string; +} + +function simplePath(segments: string[]): RepoPath | undefined { + if (segments.length < 2) return undefined; + return { segments, canonicalPath: segments.join('/') }; +} + +function azurePath(path: string[]): RepoPath | undefined { + const gitIdx = path.indexOf('_git'); + const webRepo = gitIdx > 0 ? path[gitIdx + 1] : undefined; + let segments: string[] | undefined; + if (webRepo) { + segments = [...path.slice(0, gitIdx), webRepo]; + } else if (path[0] === 'v3' && path.length >= 4) { + segments = path.slice(1, 4); + } + if (!segments || segments.length < 2) return undefined; + const repo = stripGitSuffix(segments.at(-1) ?? ''); + const namespace = segments.slice(0, -1); + return { segments: [...namespace, repo], canonicalPath: `${namespace.join('/')}/_git/${repo}` }; +} + +function bitbucketServerPath(path: string[]): RepoPath | undefined { + let key: string | undefined; + let repo: string | undefined; + if (path[0] === 'projects' && path[2] === 'repos') [, key, , repo] = path; + else if (path[0] === 'scm') [, key, repo] = path; + else if (path.length === 2) [key, repo] = path; + if (!key || !repo) return undefined; + repo = stripGitSuffix(repo); + return { segments: [key, repo], canonicalPath: `projects/${key}/repos/${repo}` }; +} + +function repoPathFor(platform: RepoPlatform, rawPath: string[]): RepoPath | undefined { + // GitLab and unknown hosts end the project path at the `/-/` separator. + const dash = rawPath.indexOf('-'); + const path = dash === -1 ? rawPath : rawPath.slice(0, dash); + const withoutGit = (segments: string[]): string[] => + segments.map((s, i) => (i === segments.length - 1 ? stripGitSuffix(s) : s)); + + switch (platform) { + case 'github': + case 'bitbucket': + return simplePath(withoutGit(path.slice(0, 2))); + case 'gitlab': + return simplePath(withoutGit(path)); + case 'azure-devops': + return azurePath(path); + case 'bitbucket-server': + return bitbucketServerPath(path); + case 'unknown': + if ((path[0] === 'projects' && path[2] === 'repos') || path[0] === 'scm') { + return bitbucketServerPath(path); + } + return simplePath(withoutGit(path)); + } +} + +/** Parse a repository URL, git remote or (optionally) `owner/repo` shorthand. Returns null when it is not one. */ +export function parseRepoLocator( + input: string, + options: ParseRepoLocatorOptions = {} +): RepoLocator | null { + const location = readLocation(input.trim(), options.allowShorthand ?? false); + if (!location) return null; + + const isSsh = location.protocol === 'ssh'; + const isWeb = location.protocol === 'https' || location.protocol === 'http'; + const registry = repositoryHosts(); + let [host, platform] = resolveHost(location.host, registry.hosts, isSsh); + let basePath: string[] = []; + let path = location.path; + const base = matchBase(registry.bases, host, path, isWeb); + if (base === null) { + platform = 'unknown'; + } else if (base) { + platform = base.platform; + if (isWeb) { + basePath = path.slice(0, base.basePath.length); + path = path.slice(base.basePath.length); + } else { + basePath = base.basePath; + } + } + const repoPath = repoPathFor(platform, path); + if (!repoPath) return null; + if (platform === 'unknown' && repoPath.canonicalPath.startsWith('projects/')) { + platform = 'bitbucket-server'; + } + if (platform === 'azure-devops') host = 'dev.azure.com'; + + const { segments } = repoPath; + const repo = segments.at(-1) ?? ''; + const owner = segments.slice(0, -1).join('/'); + const webPort = isWeb && location.port ? `:${String(location.port)}` : ''; + const webPath = [...basePath, repoPath.canonicalPath].join('/'); + return { + platform, + host, + ...(location.port ? { port: location.port } : {}), + protocol: location.protocol, + segments, + owner, + repo, + canonicalUrl: `https://${host}${webPort}/${webPath}`, + slug: `${owner}/${repo}`, + }; +} + +/** The platform for a hostname, including configured self-hosted hosts. */ +export function platformForHost(hostname: string): RepoPlatform { + return resolveHost(hostname, repositoryHosts().hosts, false)[1]; +} + +/** True when the input points at a repository on a known (built-in or configured) host. */ +export function isRepositoryHostUrl(url: string): boolean { + const locator = parseRepoLocator(url); + return locator !== null && locator.platform !== 'unknown'; +} + +/** + * Lowercased canonical URL without a port, used to match a repository against + * model links; other input is returned unchanged. The port is dropped because + * an SSH remote and a web link to one repository often use different ports. + */ +export function normalizeRepositoryUrl(url: string): string { + const locator = parseRepoLocator(url); + if (!locator || locator.platform === 'unknown') return url; + return locator.canonicalUrl.replace(/^(https:\/\/[^/:]+):\d+/, '$1').toLowerCase(); +} diff --git a/packages/web/src/content/docs/docs/contributing/adrs/013-single-repository-locator.md b/packages/web/src/content/docs/docs/contributing/adrs/013-single-repository-locator.md new file mode 100644 index 00000000..477ccbff --- /dev/null +++ b/packages/web/src/content/docs/docs/contributing/adrs/013-single-repository-locator.md @@ -0,0 +1,40 @@ +--- +title: 'ADR-013: Single repository locator' +description: One parser for repository identity across git remotes, model links, model repositories and change request URLs. +--- + +**Status:** Proposed\ +**Date:** 2026-11-17\ +**Authors:** Anders Hassis + +## Context + +Repository identity was parsed in five places: `normalizeToHttps` and `parseRepoFromRemote` in `git-diff.ts`, `normalizeRepositoryUrl` and `isRepositoryHostUrl` in `url-utils.ts`, `parseModelRepo` in `model-source.ts`, a regex per platform reader, and host checks in `platform-factory.ts`. Each accepted different forms, so one run could disagree with itself: + +- `ssh://` remotes with a port, scp remotes with a user other than `git`, and SSH host aliases were not normalized. +- `--model-repo git@github.com:org/models.git` produced an invalid clone URL. +- `www.` hosts passed platform detection but failed in the readers. +- PR URLs with `/files`, `/diffs`, a trailing slash, a query or a fragment were rejected by GitLab and Bitbucket. +- Self-hosted hosts from `ERODE_GITHUB_BASE_URL` and `ERODE_GITLAB_BASE_URL` were not repository hosts, so model links to them were dropped. + +## Decision + +Add `packages/core/src/utils/repo-locator.ts` with `parseRepoLocator(input)`. It returns the platform, host, port, path segments, owner, repo, slug and a canonical HTTPS URL, or `null`. + +- It accepts HTTPS and HTTP URLs, `ssh://` and `git+ssh://` with user and port, scp-style `user@host:path`, and `owner/repo` when the caller opts in. +- It strips credentials, `.git`, trailing slashes and platform suffixes (`/-/...`, `/tree/...`, `/blob/...`, `/pull/...`). +- Hosts come from a built-in list plus the hosts in the configured base URLs. +- Owner and repo keep their case. Matching against model links uses the lowercased canonical URL. + +All call sites use the locator. `normalizeToHttps` and `parseRepoFromRemote` remain as thin wrappers because they are part of the public API. Readers parse PR URLs through one helper that finds the platform marker in the URL path and ignores anything after the number. + +## Rationale + +A single parser makes a remote, a model link and a PR URL for the same repository resolve to the same key. A dependency such as `git-url-parse` was not used; about 250 lines of `URL` handling and one scp regex cover the required forms without an extra package. + +## Consequences + +- Model links and remotes on configured self-hosted hosts now match components. +- An SSH `--model-repo` is cloned over SSH as given, without a token. +- Bitbucket Server and Data Center URLs are parsed for repository identity, but PR analysis still supports Bitbucket Cloud only. +- SSH host aliases are resolved only when they follow the `-` pattern; other aliases need `--repo`. diff --git a/packages/web/src/content/docs/docs/contributing/adrs/index.md b/packages/web/src/content/docs/docs/contributing/adrs/index.md index 7dc8d58d..3c410bc9 100644 --- a/packages/web/src/content/docs/docs/contributing/adrs/index.md +++ b/packages/web/src/content/docs/docs/contributing/adrs/index.md @@ -21,6 +21,7 @@ This project tracks significant architectural decisions as ADRs. Each record cap | [010](/docs/contributing/adrs/010-local-diff-check-command/) | Local diff check command | 2026-03-07 | Accepted | | [011](/docs/contributing/adrs/011-intent-based-provider-generation-profiles/) | Intent-based provider generation profiles | 2026-05-05 | Accepted | | [012](/docs/contributing/adrs/012-likec4-model-edits-via-diff-blocks/) | LikeC4 model edits via diff blocks | 2026-11-17 | Proposed | +| [013](/docs/contributing/adrs/013-single-repository-locator/) | Single repository locator | 2026-11-17 | Proposed | ## Adding a new ADR diff --git a/packages/web/src/content/docs/docs/integrations/bitbucket-pipelines.md b/packages/web/src/content/docs/docs/integrations/bitbucket-pipelines.md index 47382191..999e9740 100644 --- a/packages/web/src/content/docs/docs/integrations/bitbucket-pipelines.md +++ b/packages/web/src/content/docs/docs/integrations/bitbucket-pipelines.md @@ -101,6 +101,6 @@ variables: ERODE_BITBUCKET_BASE_URL: https://bitbucket.example.com/rest/api/1.0 ``` -Platform detection identifies `bitbucket.org` from PR URLs. Self-hosted Bitbucket instances require `ERODE_BITBUCKET_BASE_URL` and the full PR URL passed via `--url`. +Erode treats the host in `ERODE_BITBUCKET_BASE_URL` as a Bitbucket Data Center or Server host. Git remotes and model repository links on that host are recognized in the `/projects/KEY/repos/repo` and `/scm/key/repo` forms. PR URL detection covers `bitbucket.org` only. See [Configuration](/docs/reference/configuration/) for all environment variables and [Self-Hosted](/docs/integrations/self-hosted/) for other deployment options. diff --git a/packages/web/src/content/docs/docs/integrations/gitlab-ci.md b/packages/web/src/content/docs/docs/integrations/gitlab-ci.md index a19edf02..067625d2 100644 --- a/packages/web/src/content/docs/docs/integrations/gitlab-ci.md +++ b/packages/web/src/content/docs/docs/integrations/gitlab-ci.md @@ -90,6 +90,6 @@ variables: ERODE_GITLAB_BASE_URL: https://gitlab.example.com ``` -Platform detection identifies `github.com` and `gitlab.com` from PR/MR URLs. Self-hosted GitLab instances require `ERODE_GITLAB_BASE_URL` and the full MR URL passed via `--url`. +Erode treats the host in `ERODE_GITLAB_BASE_URL` as a GitLab host, alongside `gitlab.com`. MR URLs passed via `--url`, git remotes, and model repository links on that host are recognized. See [Configuration](/docs/reference/configuration/) for all environment variables and [Self-Hosted](/docs/integrations/self-hosted/) for other deployment options. diff --git a/packages/web/src/content/docs/docs/integrations/index.md b/packages/web/src/content/docs/docs/integrations/index.md index cc88b495..44fc1aea 100644 --- a/packages/web/src/content/docs/docs/integrations/index.md +++ b/packages/web/src/content/docs/docs/integrations/index.md @@ -49,7 +49,7 @@ Erode provides an entrypoint script (`entrypoint-gitlab.sh`) that handles model Bitbucket Pipelines support is new. The entrypoint and environment variable interface may change in future releases. ::: -Erode provides an entrypoint script (`entrypoint-bitbucket.sh`) for Bitbucket Cloud. Self-hosted Bitbucket Data Center and Server instances are also supported. +Erode provides an entrypoint script (`entrypoint-bitbucket.sh`) for Bitbucket Cloud. For self-hosted Bitbucket Data Center and Server, Erode matches repositories on your instance, but PR analysis supports Bitbucket Cloud only. [Set up Bitbucket Pipelines →](/docs/integrations/bitbucket-pipelines/) diff --git a/packages/web/src/content/docs/docs/reference/cli-commands.md b/packages/web/src/content/docs/docs/reference/cli-commands.md index b8897d6e..a996ed11 100644 --- a/packages/web/src/content/docs/docs/reference/cli-commands.md +++ b/packages/web/src/content/docs/docs/reference/cli-commands.md @@ -85,7 +85,15 @@ erode check ./model --branch main | `--model-repo ` | Clone architecture model from this repository | | | `--model-ref ` | Branch or tag to clone from model repository | | -When no flags are passed, `check` analyzes unstaged changes (`git diff`). Use `--staged` for pre-commit hooks and `--branch main` for pre-push hooks. +When no flags are passed, `check` analyzes unstaged changes (`git diff`). Use `--staged` for pre-commit hooks and `--branch main` for pre-push hooks. The diff is read with fixed options, so git settings such as `diff.noprefix`, `diff.mnemonicPrefix`, `color.diff`, `diff.external` and the system language do not change the result. + +`--repo` and `--model-repo` accept the same repository forms: + +- HTTPS URLs, including web links such as `https://gitlab.com/group/project/-/tree/main` +- SSH remotes: `git@github.com:org/repo.git`, `ssh://git@gitlab.example.com:2222/group/project.git`, and host aliases such as `git@github.com-work:org/repo.git` +- `owner/repo`, for `--model-repo` only, which means a GitHub repository + +An SSH `--model-repo` is cloned over SSH as given, using your SSH keys rather than a token. #### Git hook integration diff --git a/packages/web/src/content/docs/docs/reference/configuration.md b/packages/web/src/content/docs/docs/reference/configuration.md index 1b701ba0..18f798ea 100644 --- a/packages/web/src/content/docs/docs/reference/configuration.md +++ b/packages/web/src/content/docs/docs/reference/configuration.md @@ -114,6 +114,8 @@ See [AI Providers](/docs/reference/ai-providers/) for default model names and gu | `ERODE_BITBUCKET_TOKEN` | Bitbucket app password or token | — | | `ERODE_BITBUCKET_BASE_URL` | Bitbucket API base URL | `https://api.bitbucket.org/2.0` | +The host in each base URL is also treated as a repository host of that platform. With `ERODE_GITHUB_BASE_URL=https://github.example.com/api/v3` or `ERODE_GITLAB_BASE_URL=https://gitlab.example.com`, PR and MR URLs, git remotes and model repository links on that host are recognized. A leading `api.` is dropped from the GitHub host. An instance under a context path, such as `ERODE_GITLAB_BASE_URL=https://example.com/gitlab` or `ERODE_BITBUCKET_BASE_URL=https://example.com/bitbucket/rest/api/1.0`, is matched by host and path: web URLs must start with `/gitlab` or `/bitbucket`, and that prefix is not part of the owner. The path before `/api` (GitHub, GitLab) or `/rest` (Bitbucket) is taken as the context path. + See [Authentication](/docs/reference/authentication/) for required permissions, token types, and platform-specific setup. ## Timeouts From fade676d5146b684bf2c7d16d6358e047b4a0f82 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 19:00:43 +0100 Subject: [PATCH 2/3] fix(core): scope tokens to configured hosts and decode quoted git paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Send a platform token to a model repository only when its host, port and base path match the configured instance for that token (ERODE_*_BASE_URL), or the public host when none is configured. A path shape such as /scm/KEY/repo no longer decides on its own that a token is sent. - Decode C-quoted git paths as one UTF-8 byte buffer, encoding literal characters by code point, so names like src/😀".ts survive. - Decode quoted diff headers before matching prefixes, so quoted no-prefix and mnemonic-prefix headers resolve to the real path. --- .../src/utils/__tests__/diff-sections.test.ts | 20 +++ .../src/utils/__tests__/git-diff-repo.test.ts | 13 +- .../__tests__/model-source-token.test.ts | 114 ++++++++++++++++++ packages/core/src/utils/diff-sections.ts | 35 ++++-- packages/core/src/utils/model-source.ts | 34 ++++-- packages/core/src/utils/repo-locator.ts | 38 +++++- 6 files changed, 234 insertions(+), 20 deletions(-) create mode 100644 packages/core/src/utils/__tests__/model-source-token.test.ts diff --git a/packages/core/src/utils/__tests__/diff-sections.test.ts b/packages/core/src/utils/__tests__/diff-sections.test.ts index 295814ff..1558bb67 100644 --- a/packages/core/src/utils/__tests__/diff-sections.test.ts +++ b/packages/core/src/utils/__tests__/diff-sections.test.ts @@ -11,6 +11,8 @@ describe('unquoteGitPath', () => { ['plain/path.ts', 'plain/path.ts'], ['"src/caf\\303\\251.ts"', 'src/café.ts'], ['"a\\tb\\"c\\\\d.ts"', 'a\tb"c\\d.ts'], + ['"src/😀\\".ts"', 'src/😀".ts'], + ['"src/日本/caf\\303\\251\\".ts"', 'src/日本/café".ts'], ])('decodes %s', (input, expected) => { expect(unquoteGitPath(input)).toBe(expected); }); @@ -24,6 +26,9 @@ describe('splitDiffSections', () => { ['path containing " b/"', 'diff --git a/docs/a b/c.md b/docs/a b/c.md', 'docs/a b/c.md'], ['no prefix with " b/"', 'diff --git docs/a b/c.md docs/a b/c.md', 'docs/a b/c.md'], ['quoted paths', 'diff --git "a/caf\\303\\251.ts" "b/caf\\303\\251.ts"', 'café.ts'], + ['quoted no prefix', 'diff --git "caf\\303\\251.ts" "caf\\303\\251.ts"', 'café.ts'], + ['quoted mnemonic prefixes', 'diff --git "i/caf\\303\\251.ts" "w/caf\\303\\251.ts"', 'café.ts'], + ['quoted literal emoji', 'diff --git "a/src/😀\\".ts" "b/src/😀\\".ts"', 'src/😀".ts'], ['combined diff', 'diff --cc src/conflict.ts', 'src/conflict.ts'], ['unmerged marker', '* Unmerged path src/conflict.ts', 'src/conflict.ts'], ])('resolves the path for %s', (_name, header, expected) => { @@ -72,6 +77,21 @@ describe('parseFilesFromDiff and filterDiffByFiles with git config variants', () expect(result).not.toContain('+drop'); }); + it('decodes quoted no-prefix and mnemonic-prefix headers', () => { + const quoted = [ + 'diff --git "caf\\303\\251.ts" "caf\\303\\251.ts"', + '@@ -1 +1 @@', + '+keep', + 'diff --git "i/na\\303\\257ve.ts" "w/na\\303\\257ve.ts"', + '@@ -1 +1 @@', + '+drop', + ].join('\n'); + expect(parseFilesFromDiff(quoted).map((f) => f.filename)).toEqual(['café.ts', 'naïve.ts']); + const result = filterDiffByFiles(quoted, [{ filename: 'café.ts' }]); + expect(result).toContain('+keep'); + expect(result).not.toContain('+drop'); + }); + it('keeps both sections of a type change', () => { const typeChange = [ 'diff --git a/link b/link', diff --git a/packages/core/src/utils/__tests__/git-diff-repo.test.ts b/packages/core/src/utils/__tests__/git-diff-repo.test.ts index 3cbd0ffc..2f599e2a 100644 --- a/packages/core/src/utils/__tests__/git-diff-repo.test.ts +++ b/packages/core/src/utils/__tests__/git-diff-repo.test.ts @@ -29,6 +29,7 @@ beforeAll(() => { mkdirSync(join(dir, 'src')); write('docs/a b/c.md', 'one\n'); write('src/café.ts', 'export const a = 1;\n'); + write('src/say"hi".ts', 'export const q = 1;\n'); write('link.txt', 'target\n'); write('old.ts', 'export const moved = 1;\nexport const kept = 2;\n'); write('image.bin', Buffer.from([0, 1, 2, 3])); @@ -38,6 +39,7 @@ beforeAll(() => { write('docs/a b/c.md', 'one\ntwo\n'); write('src/café.ts', 'export const a = 2;\n'); + write('src/say"hi".ts', 'export const q = 2;\n'); rmSync(join(dir, 'link.txt')); symlinkSync('old.ts', join(dir, 'link.txt')); git('mv', 'old.ts', 'new.ts'); @@ -62,6 +64,7 @@ const expectedFiles = [ { filename: 'link.txt', status: 'changed' }, { filename: 'new.ts', status: 'renamed' }, { filename: 'src/café.ts', status: 'modified' }, + { filename: 'src/say"hi".ts', status: 'modified' }, ]; describe('generateGitDiff against a real repository', () => { @@ -78,8 +81,8 @@ describe('generateGitDiff against a real repository', () => { it('computes stats from numstat, counting binary files without lines', () => { const result = generateGitDiff({ cwd: dir, staged: true }); - // c.md +1, café.ts +1 -1, link.txt +1 -1, image.bin binary, rename 0/0. - expect(result.stats).toEqual({ additions: 3, deletions: 2, filesChanged: 5 }); + // c.md +1, café.ts +1 -1, say"hi".ts +1 -1, link.txt +1 -1, image.bin binary, rename 0/0. + expect(result.stats).toEqual({ additions: 4, deletions: 3, filesChanged: 6 }); }); it('emits a parseable diff with a/ and b/ prefixes and no colour', () => { @@ -87,6 +90,8 @@ describe('generateGitDiff against a real repository', () => { expect(diff).not.toContain('\x1b['); expect(diff).toContain('diff --git a/docs/a b/c.md b/docs/a b/c.md'); expect(diff).toContain('diff --git a/src/café.ts b/src/café.ts'); + // git still C-quotes a name containing `"` with core.quotePath=false. + expect(diff).toContain('diff --git "a/src/say\\"hi\\".ts" "b/src/say\\"hi\\".ts"'); expect(parseFilesFromDiff(diff).map((f) => f.filename)).toEqual( expectedFiles.map((f) => f.filename) ); @@ -101,6 +106,10 @@ describe('generateGitDiff against a real repository', () => { expect(filtered).toContain('+two'); expect(filtered.match(/^diff --git a\/link\.txt b\/link\.txt$/gm)).toHaveLength(2); expect(filtered).not.toContain('café'); + expect(filtered).not.toContain('say'); + expect(filterDiffByFiles(diff, [{ filename: 'src/say"hi".ts' }])).toContain( + '+export const q = 2;' + ); expect(filtered).not.toContain('image.bin'); expect(filtered).not.toContain('new.ts'); }); diff --git a/packages/core/src/utils/__tests__/model-source-token.test.ts b/packages/core/src/utils/__tests__/model-source-token.test.ts new file mode 100644 index 00000000..dcc97091 --- /dev/null +++ b/packages/core/src/utils/__tests__/model-source-token.test.ts @@ -0,0 +1,114 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import type { ExecException } from 'child_process'; +import { resolveModelSource } from '../model-source.js'; + +vi.mock('child_process', () => ({ + execFile: vi.fn(), +})); + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...(actual as Record), + mkdtemp: vi.fn().mockResolvedValue('/tmp/erode-model-token'), + rm: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + chmod: vi.fn().mockResolvedValue(undefined), + }; +}); + +vi.mock('../../utils/config.js', () => ({ + CONFIG: { + github: { token: 'gh-token', modelRepoPrToken: undefined, baseUrl: undefined }, + gitlab: { token: 'gl-token', baseUrl: undefined }, + bitbucket: { token: 'bb-token', baseUrl: undefined }, + }, +})); + +import { execFile } from 'child_process'; +import { writeFile } from 'node:fs/promises'; +import { CONFIG } from '../config.js'; + +type ExecFileCallback = ( + error: ExecException | null, + stdout: string | Buffer, + stderr: string | Buffer +) => void; + +const config = CONFIG as unknown as Record< + 'github' | 'gitlab' | 'bitbucket', + { baseUrl: string | undefined } +>; + +/** The clone URL and the token written to the askpass script, if any. */ +async function clone(modelRepo: string): Promise<{ url: string; token: string | undefined }> { + vi.mocked(writeFile).mockClear(); + vi.mocked(execFile).mockClear(); + await resolveModelSource('.', modelRepo); + const gitArgs = vi.mocked(execFile).mock.calls[0]?.[1] as string[]; + const script = vi.mocked(writeFile).mock.calls[0]?.[1] as string | undefined; + return { + url: gitArgs.at(-2) ?? '', + token: script ? /echo '(.*)'/.exec(script)?.[1] : undefined, + }; +} + +describe('resolveModelSource token scoping', () => { + beforeEach(() => { + vi.mocked(execFile).mockImplementation((...args: unknown[]) => { + const cb = args[args.length - 1] as ExecFileCallback | undefined; + if (cb) cb(null, '', ''); + return undefined as never; + }); + }); + + afterEach(() => { + config.github.baseUrl = undefined; + config.gitlab.baseUrl = undefined; + config.bitbucket.baseUrl = undefined; + }); + + it.each([ + ['https://github.com/o/r', 'gh-token'], + ['https://gitlab.com/g/p', 'gl-token'], + ['https://bitbucket.org/ws/r', 'bb-token'], + ])('sends the token to the public host for %s', async (repo, token) => { + expect((await clone(repo)).token).toBe(token); + }); + + it.each([ + 'https://other.example/scm/key/models', + 'https://other.example/projects/KEY/repos/models', + 'https://github.com.evil.example/o/r', + 'https://gitlab.com.evil.example/g/p', + 'https://github.com:8443/o/r', + ])('sends no token to %s', async (repo) => { + const result = await clone(repo); + expect(result.token).toBeUndefined(); + expect(result.url).not.toContain('@'); + }); + + it('sends the Bitbucket token only to the configured Bitbucket Server host and base path', async () => { + config.bitbucket.baseUrl = 'https://git.corp.example/bitbucket/rest/api/1.0'; + expect((await clone('https://git.corp.example/bitbucket/scm/KEY/models')).token).toBe( + 'bb-token' + ); + expect((await clone('https://git.corp.example/other/scm/KEY/models')).token).toBeUndefined(); + expect((await clone('https://other.example/scm/KEY/models')).token).toBeUndefined(); + expect((await clone('https://bitbucket.org/ws/r')).token).toBeUndefined(); + }); + + it('sends the GitHub token only to the configured Enterprise host', async () => { + config.github.baseUrl = 'https://ghe.corp.example/api/v3'; + expect((await clone('https://ghe.corp.example/o/r')).token).toBe('gh-token'); + expect((await clone('https://github.com/o/r')).token).toBeUndefined(); + expect((await clone('o/r')).token).toBeUndefined(); + }); + + it('sends the GitLab token only to the configured GitLab host and base path', async () => { + config.gitlab.baseUrl = 'https://corp.example/gitlab'; + expect((await clone('https://corp.example/gitlab/g/p')).token).toBe('gl-token'); + expect((await clone('https://corp.example/other/g/p')).token).toBeUndefined(); + expect((await clone('https://gitlab.com/g/p')).token).toBeUndefined(); + }); +}); diff --git a/packages/core/src/utils/diff-sections.ts b/packages/core/src/utils/diff-sections.ts index 026c5509..f1f782e0 100644 --- a/packages/core/src/utils/diff-sections.ts +++ b/packages/core/src/utils/diff-sections.ts @@ -41,15 +41,23 @@ const C_ESCAPES: Record = { '\\': 92, }; -/** Decode a path that git quoted C-style (`"caf\303\251.ts"`); other input is returned as is. */ +const utf8 = new TextEncoder(); + +/** + * Decode a path that git quoted C-style (`"caf\303\251.ts"`); other input is + * returned as is. Octal escapes are raw bytes and literal characters (left + * unescaped with `core.quotePath=false`) are UTF-8, so both go into one byte + * buffer that is decoded once. + */ export function unquoteGitPath(value: string): string { if (value.length < 2 || !value.startsWith('"') || !value.endsWith('"')) return value; const body = value.slice(1, -1); const bytes: number[] = []; for (let i = 0; i < body.length; i++) { - const ch = body.charAt(i); + const ch = String.fromCodePoint(body.codePointAt(i) ?? 0); if (ch !== '\\') { - bytes.push(...Buffer.from(ch, 'utf-8')); + bytes.push(...utf8.encode(ch)); + i += ch.length - 1; continue; } const next = body.charAt(i + 1); @@ -62,7 +70,7 @@ export function unquoteGitPath(value: string): string { i += 1; } } - return Buffer.from(bytes).toString('utf-8'); + return new TextDecoder('utf-8').decode(new Uint8Array(bytes)); } function stripPrefix(path: string, prefixes: readonly string[]): string { @@ -81,13 +89,25 @@ function symmetricHeaderPath(rest: string): string | undefined { return undefined; } -/** Read the second token of a header whose first token is C-quoted. */ +/** + * Resolve a header whose first token is C-quoted, e.g. `"a/caf\303\251.ts" "b/caf\303\251.ts"` + * or, without prefixes, `"caf\303\251.ts" "caf\303\251.ts"`. Both tokens are + * decoded before the prefixes are matched. + */ function quotedHeaderPath(rest: string): string | undefined { if (!rest.startsWith('"')) return undefined; let end = 1; while (end < rest.length && rest[end] !== '"') end += rest[end] === '\\' ? 2 : 1; const second = rest.slice(end + 2); - return second ? stripPrefix(unquoteGitPath(second), DST_PREFIXES) : undefined; + if (!second) return undefined; + const srcPath = unquoteGitPath(rest.slice(0, end + 1)); + const dstPath = unquoteGitPath(second); + for (const [src, dst] of PREFIX_PAIRS) { + if (!srcPath.startsWith(src) || !dstPath.startsWith(dst)) continue; + const path = dstPath.slice(dst.length); + if (path && srcPath.slice(src.length) === path) return path; + } + return stripPrefix(dstPath, DST_PREFIXES); } function fileLinePath(lines: string[], marker: '+++ ' | '--- '): string | undefined { @@ -112,9 +132,10 @@ function resolveSectionPath(lines: string[]): string | undefined { if (renamed) return unquoteGitPath(renamed.slice(renamed.indexOf(' to ') + 4)); const rest = header.slice('diff --git '.length); + // A quoted header must be decoded before its prefixes are matched. const path = - symmetricHeaderPath(rest) ?? quotedHeaderPath(rest) ?? + symmetricHeaderPath(rest) ?? fileLinePath(meta, '+++ ') ?? fileLinePath(meta, '--- '); if (path) return path; diff --git a/packages/core/src/utils/model-source.ts b/packages/core/src/utils/model-source.ts index f05474fa..06f2bd5c 100644 --- a/packages/core/src/utils/model-source.ts +++ b/packages/core/src/utils/model-source.ts @@ -6,7 +6,13 @@ import { promisify } from 'node:util'; import { ConfigurationError, ErodeError, ErrorCode } from '../errors.js'; import { CONFIG } from './config.js'; import { redactUrlCredentials } from './url-credentials.js'; -import { parseRepoLocator, type RepoPlatform } from './repo-locator.js'; +import { + isTokenInstance, + parseRepoLocator, + type RepoLocator, + type RepoPlatform, + type TokenPlatform, +} from './repo-locator.js'; const execFileAsync = promisify(execFile); @@ -40,10 +46,10 @@ export async function resolveModelSource( }; } - const { cloneUrl, slug, platform, asGiven } = locateModelRepo(modelRepo); + const { cloneUrl, slug, platform, asGiven, locator } = locateModelRepo(modelRepo); const ref = options.ref ?? 'main'; validateRef(ref); - let token = asGiven ? undefined : resolveToken(platform); + let token = asGiven ? undefined : resolveToken(locator); if (token && !cloneUrl.startsWith('https://')) { console.warn( `[erode] Cloning ${cloneUrl} without credentials: the access token is never sent over plain http.` @@ -94,6 +100,7 @@ function locateModelRepo(modelRepo: string): { platform: RepoPlatform; /** Clone the input unchanged and without a token (SSH and `git://`). */ asGiven: boolean; + locator: RepoLocator; } { const locator = parseRepoLocator(modelRepo, { allowShorthand: true }); if (!locator) { @@ -103,7 +110,7 @@ function locateModelRepo(modelRepo: string): { } const { slug, platform } = locator; if (locator.protocol === 'ssh' || locator.protocol === 'git') { - return { cloneUrl: modelRepo.trim(), slug, platform, asGiven: true }; + return { cloneUrl: modelRepo.trim(), slug, platform, asGiven: true, locator }; } let cloneUrl = `${locator.canonicalUrl}.git`; if (platform === 'azure-devops') cloneUrl = locator.canonicalUrl; @@ -111,20 +118,27 @@ function locateModelRepo(modelRepo: string): { cloneUrl = locator.canonicalUrl.replace(/\/projects\/([^/]+)\/repos\//, '/scm/$1/') + '.git'; } if (locator.protocol === 'http') cloneUrl = cloneUrl.replace(/^https:/, 'http:'); - return { cloneUrl, slug, platform, asGiven: false }; + return { cloneUrl, slug, platform, asGiven: false, locator }; } -function resolveToken(platform: RepoPlatform): string | undefined { - switch (platform) { +const TOKEN_PLATFORMS: Partial> = { + github: 'github', + gitlab: 'gitlab', + bitbucket: 'bitbucket', + 'bitbucket-server': 'bitbucket', +}; + +/** The platform token, only when the repository is on the instance that token belongs to. */ +function resolveToken(locator: RepoLocator): string | undefined { + const tokenPlatform = TOKEN_PLATFORMS[locator.platform]; + if (!tokenPlatform || !isTokenInstance(locator, tokenPlatform)) return undefined; + switch (tokenPlatform) { case 'github': return CONFIG.github.modelRepoPrToken ?? CONFIG.github.token; case 'gitlab': return CONFIG.gitlab.token; case 'bitbucket': - case 'bitbucket-server': return CONFIG.bitbucket.token; - default: - return undefined; } } diff --git a/packages/core/src/utils/repo-locator.ts b/packages/core/src/utils/repo-locator.ts index 0f24e9cc..401c9a4b 100644 --- a/packages/core/src/utils/repo-locator.ts +++ b/packages/core/src/utils/repo-locator.ts @@ -70,6 +70,7 @@ interface HostBase { host: string; /** Web base path segments, e.g. `['gitlab']` for `https://example.com/gitlab`. */ basePath: string[]; + port?: number; platform: RepoPlatform; } @@ -99,7 +100,12 @@ function configuredBase( if (host in BUILT_IN_HOSTS || host === 'api.bitbucket.org') return undefined; const path = splitPath(parsed.pathname); const api = path.findIndex((s) => s.toLowerCase() === apiSegment); - return { host, basePath: api === -1 ? path : path.slice(0, api), platform }; + return { + host, + basePath: api === -1 ? path : path.slice(0, api), + ...(parsed.port ? { port: Number(parsed.port) } : {}), + platform, + }; } let registryCache: { key: string; registry: HostRegistry } | undefined; @@ -336,6 +342,36 @@ export function platformForHost(hostname: string): RepoPlatform { return resolveHost(hostname, repositoryHosts().hosts, false)[1]; } +export type TokenPlatform = 'github' | 'gitlab' | 'bitbucket'; + +const TOKEN_DEFAULT_HOSTS: Record = { + github: 'github.com', + gitlab: 'gitlab.com', + bitbucket: 'bitbucket.org', +}; + +const TOKEN_BASE_PLATFORMS: Record = { + github: 'github', + gitlab: 'gitlab', + bitbucket: 'bitbucket-server', +}; + +/** + * True when the locator is on the instance a platform token is issued for: the + * self-hosted instance from `ERODE_*_BASE_URL` (host, port and base path) when + * one is set, otherwise the public host. The platform guessed from a path shape + * such as `/scm/KEY/repo` never qualifies on its own. + */ +export function isTokenInstance(locator: RepoLocator, tokenPlatform: TokenPlatform): boolean { + const platform = TOKEN_BASE_PLATFORMS[tokenPlatform]; + const base = repositoryHosts().bases.find((b) => b.platform === platform); + if (!base) { + return locator.host === TOKEN_DEFAULT_HOSTS[tokenPlatform] && locator.port === undefined; + } + if (locator.host !== base.host || locator.port !== base.port) return false; + return startsWithPath(splitPath(new URL(locator.canonicalUrl).pathname), base.basePath); +} + /** True when the input points at a repository on a known (built-in or configured) host. */ export function isRepositoryHostUrl(url: string): boolean { const locator = parseRepoLocator(url); From cfe6569dfabb6efc39b62f141dab99267bc5abc5 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 19:18:16 +0100 Subject: [PATCH 3/3] fix(core): pick the platform API from the change request host A public PR URL was fetched from the configured self-hosted API, so erode could analyse a same-named repository there and send the instance token. Readers and writers now resolve the endpoint from the URL host: the public host uses the public API without the token, the configured instance uses ERODE_*_BASE_URL with its token, and any other host is rejected naming the host and the setting. Applies to GitHub, GitLab and Bitbucket. --- .../platforms/__tests__/api-endpoint.test.ts | 246 ++++++++++++++++++ packages/core/src/platforms/api-endpoint.ts | 56 ++++ .../bitbucket/__tests__/writer.test.ts | 14 +- .../src/platforms/bitbucket/api-client.ts | 6 +- .../core/src/platforms/bitbucket/reader.ts | 27 +- .../core/src/platforms/bitbucket/writer.ts | 8 +- .../platforms/github/__tests__/writer.test.ts | 6 +- packages/core/src/platforms/github/reader.ts | 23 +- packages/core/src/platforms/github/writer.ts | 10 +- .../platforms/gitlab/__tests__/writer.test.ts | 12 +- packages/core/src/platforms/gitlab/reader.ts | 21 +- packages/core/src/platforms/gitlab/writer.ts | 8 +- .../core/src/platforms/platform-factory.ts | 6 +- packages/core/src/utils/repo-locator.ts | 9 +- 14 files changed, 392 insertions(+), 60 deletions(-) create mode 100644 packages/core/src/platforms/__tests__/api-endpoint.test.ts create mode 100644 packages/core/src/platforms/api-endpoint.ts diff --git a/packages/core/src/platforms/__tests__/api-endpoint.test.ts b/packages/core/src/platforms/__tests__/api-endpoint.test.ts new file mode 100644 index 00000000..b9b2f98e --- /dev/null +++ b/packages/core/src/platforms/__tests__/api-endpoint.test.ts @@ -0,0 +1,246 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { ErodeError, ErrorCode } from '../../errors.js'; + +const octokitOptions: Record[] = []; +const gitlabOptions: Record[] = []; + +vi.mock('@octokit/rest', () => ({ + Octokit: class MockOctokit { + constructor(options: Record) { + octokitOptions.push(options); + } + rest = { + pulls: { + get: vi.fn().mockRejectedValue(new Error('stop')), + listCommits: vi.fn().mockRejectedValue(new Error('stop')), + }, + }; + }, +})); + +vi.mock('@gitbeaker/rest', () => ({ + Gitlab: class MockGitlab { + constructor(options: Record) { + gitlabOptions.push(options); + } + MergeRequests = { + show: vi.fn().mockRejectedValue(new Error('stop')), + allCommits: vi.fn().mockRejectedValue(new Error('stop')), + }; + }, +})); + +vi.mock('../../utils/config.js', async (importOriginal) => ({ + ...(await importOriginal()), + CONFIG: { + github: { token: 'gh-token', modelRepoPrToken: null, baseUrl: 'https://api.github.com' }, + gitlab: { token: 'gl-token', baseUrl: 'https://gitlab.com' }, + bitbucket: { token: 'bb-token', baseUrl: 'https://api.bitbucket.org/2.0' }, + constraints: { maxFilesPerDiff: 50, maxLinesPerDiff: 5000 }, + }, +})); + +import { CONFIG } from '../../utils/config.js'; +import { resolvePlatformEndpoint } from '../api-endpoint.js'; +import { GitHubReader } from '../github/reader.js'; +import { GitHubWriter } from '../github/writer.js'; +import { GitLabReader } from '../gitlab/reader.js'; +import { GitLabWriter } from '../gitlab/writer.js'; +import { BitbucketWriter } from '../bitbucket/writer.js'; + +const GHE_API = 'https://ghe.example.com/api/v3'; +const GITLAB_SELF_HOSTED = 'https://git.example.com/gitlab'; + +function useDefaults(): void { + CONFIG.github.baseUrl = 'https://api.github.com'; + CONFIG.gitlab.baseUrl = 'https://gitlab.com'; + CONFIG.bitbucket.baseUrl = 'https://api.bitbucket.org/2.0'; +} + +beforeEach(() => { + octokitOptions.length = 0; + gitlabOptions.length = 0; + useDefaults(); +}); + +describe('resolvePlatformEndpoint', () => { + it('uses the public API and token without a self-hosted setting', () => { + expect(resolvePlatformEndpoint('https://github.com/o/r', 'github')).toEqual({ + baseUrl: 'https://api.github.com', + tokenApplies: true, + }); + }); + + it('uses the public API without the token for a public URL when GHE is configured', () => { + CONFIG.github.baseUrl = GHE_API; + expect(resolvePlatformEndpoint('https://github.com/o/r', 'github')).toEqual({ + baseUrl: 'https://api.github.com', + tokenApplies: false, + }); + }); + + it('uses the configured base URL and token for the GHE host', () => { + CONFIG.github.baseUrl = GHE_API; + expect(resolvePlatformEndpoint('https://ghe.example.com/o/r', 'github')).toEqual({ + baseUrl: GHE_API, + tokenApplies: true, + }); + }); + + it('rejects an unrelated host and names the host and the setting', () => { + CONFIG.github.baseUrl = GHE_API; + expect(() => resolvePlatformEndpoint('https://other.example.org/o/r', 'github')).toThrow( + /other\.example\.org.*ERODE_GITHUB_BASE_URL/ + ); + try { + resolvePlatformEndpoint('https://other.example.org/o/r', 'github'); + } catch (error) { + expect(error).toBeInstanceOf(ErodeError); + expect((error as ErodeError).code).toBe(ErrorCode.PLATFORM_INVALID_URL); + } + }); + + it('rejects the GHE host on a different port', () => { + CONFIG.github.baseUrl = GHE_API; + expect(() => resolvePlatformEndpoint('https://ghe.example.com:8443/o/r', 'github')).toThrow( + ErodeError + ); + }); + + it('uses the public API without the token for gitlab.com when self-hosted is configured', () => { + CONFIG.gitlab.baseUrl = GITLAB_SELF_HOSTED; + expect(resolvePlatformEndpoint('https://gitlab.com/g/p', 'gitlab')).toEqual({ + baseUrl: 'https://gitlab.com', + tokenApplies: false, + }); + }); + + it('uses the configured base URL and token for the self-hosted GitLab', () => { + CONFIG.gitlab.baseUrl = GITLAB_SELF_HOSTED; + expect(resolvePlatformEndpoint(`${GITLAB_SELF_HOSTED}/g/p`, 'gitlab')).toEqual({ + baseUrl: GITLAB_SELF_HOSTED, + tokenApplies: true, + }); + }); + + it('rejects an unrelated host for GitLab', () => { + CONFIG.gitlab.baseUrl = GITLAB_SELF_HOSTED; + expect(() => resolvePlatformEndpoint('https://other.example.org/g/p', 'gitlab')).toThrow( + /other\.example\.org.*ERODE_GITLAB_BASE_URL/ + ); + }); +}); + +describe('GitHub with GHE configured', () => { + beforeEach(() => { + CONFIG.github.baseUrl = GHE_API; + }); + + it('reader sends a github.com PR to api.github.com without the GHE token', async () => { + const reader = new GitHubReader(); + const ref = reader.parseChangeRequestUrl('https://github.com/o/r/pull/1'); + await expect(reader.fetchChangeRequest(ref)).rejects.toThrow(); + expect(octokitOptions).toEqual([{ baseUrl: 'https://api.github.com' }]); + }); + + it('reader sends a GHE PR to the GHE base URL with the token', async () => { + const reader = new GitHubReader(); + const ref = reader.parseChangeRequestUrl('https://ghe.example.com/o/r/pull/1'); + await expect(reader.fetchChangeRequest(ref)).rejects.toThrow(); + expect(octokitOptions).toEqual([{ auth: 'gh-token', baseUrl: GHE_API }]); + }); + + it('reader rejects a ref on an unrelated host before any API call', async () => { + const reader = new GitHubReader(); + const ref = { + number: 1, + url: 'https://other.example.org/o/r/pull/1', + repositoryUrl: 'https://other.example.org/o/r', + platformId: { owner: 'o', repo: 'r' }, + }; + await expect(reader.fetchChangeRequest(ref)).rejects.toThrow(/ERODE_GITHUB_BASE_URL/); + expect(octokitOptions).toEqual([]); + }); + + it('reader rejects an unrelated host URL when parsing', () => { + expect(() => + new GitHubReader().parseChangeRequestUrl('https://other.example.org/o/r/pull/1') + ).toThrow(ErodeError); + }); + + it('writer refuses a github.com repository instead of using the GHE token', () => { + expect(() => new GitHubWriter('o', 'r', 'https://github.com/o/r')).toThrow( + 'A GitHub token is needed' + ); + expect(octokitOptions).toEqual([]); + }); + + it('writer uses the GHE base URL for a GHE repository', () => { + new GitHubWriter('o', 'r', 'https://ghe.example.com/o/r'); + expect(octokitOptions).toEqual([{ auth: 'gh-token', baseUrl: GHE_API }]); + }); + + it('writer rejects an unrelated host', () => { + expect(() => new GitHubWriter('o', 'r', 'https://other.example.org/o/r')).toThrow( + /ERODE_GITHUB_BASE_URL/ + ); + }); +}); + +describe('GitLab with a self-hosted instance configured', () => { + beforeEach(() => { + CONFIG.gitlab.baseUrl = GITLAB_SELF_HOSTED; + }); + + it('reader sends a gitlab.com MR to gitlab.com without the self-hosted token', async () => { + const reader = new GitLabReader(); + const ref = reader.parseChangeRequestUrl('https://gitlab.com/g/p/-/merge_requests/1'); + await expect(reader.fetchChangeRequest(ref)).rejects.toThrow(); + expect(gitlabOptions).toEqual([{ host: 'https://gitlab.com' }]); + }); + + it('reader sends a self-hosted MR to the configured base URL with the token', async () => { + const reader = new GitLabReader(); + const ref = reader.parseChangeRequestUrl(`${GITLAB_SELF_HOSTED}/g/p/-/merge_requests/1`); + await expect(reader.fetchChangeRequest(ref)).rejects.toThrow(); + expect(gitlabOptions).toEqual([{ token: 'gl-token', host: GITLAB_SELF_HOSTED }]); + }); + + it('reader rejects a ref on an unrelated host before any API call', async () => { + const reader = new GitLabReader(); + const ref = { + number: 1, + url: 'https://other.example.org/g/p/-/merge_requests/1', + repositoryUrl: 'https://other.example.org/g/p', + platformId: { owner: 'g', repo: 'p' }, + }; + await expect(reader.fetchChangeRequest(ref)).rejects.toThrow(/ERODE_GITLAB_BASE_URL/); + expect(gitlabOptions).toEqual([]); + }); + + it('writer refuses a gitlab.com repository instead of using the self-hosted token', () => { + expect(() => new GitLabWriter('g', 'p', 'https://gitlab.com/g/p')).toThrow( + 'A GitLab token is needed' + ); + }); + + it('writer uses the configured base URL for a self-hosted repository', () => { + new GitLabWriter('g', 'p', `${GITLAB_SELF_HOSTED}/g/p`); + expect(gitlabOptions).toEqual([{ token: 'gl-token', host: GITLAB_SELF_HOSTED }]); + }); + + it('writer rejects an unrelated host', () => { + expect(() => new GitLabWriter('g', 'p', 'https://other.example.org/g/p')).toThrow( + /ERODE_GITLAB_BASE_URL/ + ); + }); +}); + +describe('Bitbucket with a custom base URL configured', () => { + it('writer refuses bitbucket.org instead of using the custom instance token', () => { + CONFIG.bitbucket.baseUrl = 'https://bb.example.com/rest/api/1.0'; + expect(() => new BitbucketWriter('w', 'r', 'https://bitbucket.org/w/r')).toThrow( + 'A Bitbucket token is needed' + ); + }); +}); diff --git a/packages/core/src/platforms/api-endpoint.ts b/packages/core/src/platforms/api-endpoint.ts new file mode 100644 index 00000000..a5219418 --- /dev/null +++ b/packages/core/src/platforms/api-endpoint.ts @@ -0,0 +1,56 @@ +import { CONFIG } from '../utils/config.js'; +import { ErodeError, ErrorCode } from '../errors.js'; +import { + isPublicInstance, + isTokenInstance, + parseRepoLocator, + type TokenPlatform, +} from '../utils/repo-locator.js'; + +const PUBLIC_API_URLS: Record = { + github: 'https://api.github.com', + gitlab: 'https://gitlab.com', + bitbucket: 'https://api.bitbucket.org/2.0', +}; + +const BASE_URL_SETTINGS: Record = { + github: 'ERODE_GITHUB_BASE_URL', + gitlab: 'ERODE_GITLAB_BASE_URL', + bitbucket: 'ERODE_BITBUCKET_BASE_URL', +}; + +export interface PlatformEndpoint { + /** API base URL for the repository's host. */ + baseUrl: string; + /** True only when the configured token was issued for this host. */ + tokenApplies: boolean; +} + +/** + * Pick the API endpoint from the repository URL's host, with the same host, + * port and base path rule that URL parsing and token scoping use. Without this, + * a public URL would be sent to the configured self-hosted instance, which may + * hold a different repository under the same name, along with its token. + */ +export function resolvePlatformEndpoint( + repositoryUrl: string, + platform: TokenPlatform +): PlatformEndpoint { + const locator = parseRepoLocator(repositoryUrl); + if (locator && isTokenInstance(locator, platform)) { + return { baseUrl: CONFIG[platform].baseUrl, tokenApplies: true }; + } + if (locator && isPublicInstance(locator, platform)) { + return { baseUrl: PUBLIC_API_URLS[platform], tokenApplies: false }; + } + const setting = BASE_URL_SETTINGS[platform]; + const host = locator + ? locator.port + ? `${locator.host}:${String(locator.port)}` + : locator.host + : repositoryUrl; + const message = + `Repository host ${host} is neither the public ${platform} host nor the instance ` + + `configured in ${setting} (${CONFIG[platform].baseUrl}). Set ${setting} to that instance's API URL.`; + throw new ErodeError(message, ErrorCode.PLATFORM_INVALID_URL, message); +} diff --git a/packages/core/src/platforms/bitbucket/__tests__/writer.test.ts b/packages/core/src/platforms/bitbucket/__tests__/writer.test.ts index f374f054..d8f5c1da 100644 --- a/packages/core/src/platforms/bitbucket/__tests__/writer.test.ts +++ b/packages/core/src/platforms/bitbucket/__tests__/writer.test.ts @@ -19,6 +19,8 @@ vi.mock('../api-client.js', () => ({ vi.mock('../../../utils/config.js', async (importOriginal) => ({ ...(await importOriginal()), CONFIG: { + github: { token: 'test-token', modelRepoPrToken: null, baseUrl: 'https://api.github.com' }, + gitlab: { token: 'test-token', baseUrl: 'https://gitlab.com' }, bitbucket: { token: 'test-token', baseUrl: 'https://api.bitbucket.org/2.0' }, }, })); @@ -40,7 +42,7 @@ describe('BitbucketWriter', () => { beforeEach(() => { vi.clearAllMocks(); - writer = new BitbucketWriter('workspace', 'repo'); + writer = new BitbucketWriter('workspace', 'repo', 'https://bitbucket.org/workspace/repo'); }); describe('constructor', () => { @@ -50,10 +52,12 @@ describe('BitbucketWriter', () => { CONFIG.bitbucket.token = undefined; try { - expect(() => new BitbucketWriter('workspace', 'repo')).toThrow(ErodeError); - expect(() => new BitbucketWriter('workspace', 'repo')).toThrow( - 'A Bitbucket token is needed' - ); + expect( + () => new BitbucketWriter('workspace', 'repo', 'https://bitbucket.org/workspace/repo') + ).toThrow(ErodeError); + expect( + () => new BitbucketWriter('workspace', 'repo', 'https://bitbucket.org/workspace/repo') + ).toThrow('A Bitbucket token is needed'); } finally { CONFIG.bitbucket.token = originalToken; } diff --git a/packages/core/src/platforms/bitbucket/api-client.ts b/packages/core/src/platforms/bitbucket/api-client.ts index a137ebd9..c81e9e2d 100644 --- a/packages/core/src/platforms/bitbucket/api-client.ts +++ b/packages/core/src/platforms/bitbucket/api-client.ts @@ -13,9 +13,9 @@ export class BitbucketApiClient { private readonly baseUrl: string; private readonly token: string | undefined; - constructor(token?: string) { - this.token = token ?? CONFIG.bitbucket.token; - this.baseUrl = CONFIG.bitbucket.baseUrl; + constructor(token?: string, baseUrl: string = CONFIG.bitbucket.baseUrl) { + this.token = token; + this.baseUrl = baseUrl; } private buildHeaders(extra?: Record): Record { diff --git a/packages/core/src/platforms/bitbucket/reader.ts b/packages/core/src/platforms/bitbucket/reader.ts index e400944b..7c7a7471 100644 --- a/packages/core/src/platforms/bitbucket/reader.ts +++ b/packages/core/src/platforms/bitbucket/reader.ts @@ -18,6 +18,8 @@ import { import { BitbucketApiClient } from './api-client.js'; import { applyDiffTruncation, wrapPlatformError } from '../platform-utils.js'; import { parseChangeRequestRef } from '../change-request-url.js'; +import { resolvePlatformEndpoint } from '../api-endpoint.js'; +import { CONFIG } from '../../utils/config.js'; /** Parse "Name " format used by Bitbucket commit authors. */ function parseAuthorRaw(raw: string): { name: string; email: string } { @@ -29,10 +31,14 @@ function parseAuthorRaw(raw: string): { name: string; email: string } { } export class BitbucketReader implements SourcePlatformReader { - private api: BitbucketApiClient; + constructor(private readonly token?: string) {} - constructor(token?: string) { - this.api = new BitbucketApiClient(token); + private clientFor(ref: ChangeRequestRef): BitbucketApiClient { + const { baseUrl, tokenApplies } = resolvePlatformEndpoint(ref.repositoryUrl, 'bitbucket'); + return new BitbucketApiClient( + this.token ?? (tokenApplies ? CONFIG.bitbucket.token : undefined), + baseUrl + ); } parseChangeRequestUrl(url: string): ChangeRequestRef { @@ -49,20 +55,18 @@ export class BitbucketReader implements SourcePlatformReader { const prId = ref.number; const basePath = `/repositories/${workspace}/${repoSlug}/pullrequests/${String(prId)}`; + const api = this.clientFor(ref); try { - const pr = await this.api.request(basePath, BitbucketPrResponseSchema); + const pr = await api.request(basePath, BitbucketPrResponseSchema); - const diffstatEntries = await this.api.paginate( + const diffstatEntries = await api.paginate( `${basePath}/diffstat`, BitbucketDiffstatEntrySchema ); - const commitEntries = await this.api.paginate( - `${basePath}/commits`, - BitbucketCommitEntrySchema - ); + const commitEntries = await api.paginate(`${basePath}/commits`, BitbucketCommitEntrySchema); - const rawDiff = await this.api.requestText(`${basePath}/diff`); + const rawDiff = await api.requestText(`${basePath}/diff`); const files = diffstatEntries.map((entry) => ({ filename: entry.new?.path ?? entry.old?.path ?? 'unknown', @@ -126,8 +130,9 @@ export class BitbucketReader implements SourcePlatformReader { const prId = ref.number; const basePath = `/repositories/${workspace}/${repoSlug}/pullrequests/${String(prId)}`; + const api = this.clientFor(ref); try { - const commits = await this.api.paginate(`${basePath}/commits`, BitbucketCommitEntrySchema); + const commits = await api.paginate(`${basePath}/commits`, BitbucketCommitEntrySchema); const result = commits.map((commit) => { const { name, email } = parseAuthorRaw(commit.author.raw); return { diff --git a/packages/core/src/platforms/bitbucket/writer.ts b/packages/core/src/platforms/bitbucket/writer.ts index 31abdc91..6b7d487c 100644 --- a/packages/core/src/platforms/bitbucket/writer.ts +++ b/packages/core/src/platforms/bitbucket/writer.ts @@ -8,6 +8,7 @@ import type { CreateOrUpdateChangeRequestOptions, } from '../source-platform.js'; import { BitbucketCommentSchema } from '../../schemas/bitbucket-api.schema.js'; +import { resolvePlatformEndpoint } from '../api-endpoint.js'; import { BitbucketApiClient } from './api-client.js'; import { wrapPlatformError } from '../platform-utils.js'; @@ -31,8 +32,9 @@ export class BitbucketWriter implements SourcePlatformWriter { private readonly workspace: string; private readonly repoSlug: string; - constructor(targetOwner: string, targetRepo: string) { - const token = CONFIG.bitbucket.token; + constructor(targetOwner: string, targetRepo: string, repositoryUrl: string) { + const { baseUrl, tokenApplies } = resolvePlatformEndpoint(repositoryUrl, 'bitbucket'); + const token = tokenApplies ? CONFIG.bitbucket.token : undefined; if (!token) { throw new ErodeError( 'A Bitbucket token is needed to create pull requests', @@ -40,7 +42,7 @@ export class BitbucketWriter implements SourcePlatformWriter { `Provide ${ENV_VAR_NAMES.bitbucketToken} in your environment or ${RC_FILENAME} to create pull requests.` ); } - this.api = new BitbucketApiClient(token); + this.api = new BitbucketApiClient(token, baseUrl); this.workspace = targetOwner; this.repoSlug = targetRepo; } diff --git a/packages/core/src/platforms/github/__tests__/writer.test.ts b/packages/core/src/platforms/github/__tests__/writer.test.ts index 07aa1cd6..48749657 100644 --- a/packages/core/src/platforms/github/__tests__/writer.test.ts +++ b/packages/core/src/platforms/github/__tests__/writer.test.ts @@ -49,7 +49,9 @@ vi.mock('@octokit/rest', () => ({ vi.mock('../../../utils/config.js', async (importOriginal) => ({ ...(await importOriginal()), CONFIG: { - github: { token: 'test-token', modelRepoPrToken: null }, + github: { token: 'test-token', modelRepoPrToken: null, baseUrl: 'https://api.github.com' }, + gitlab: { token: 'test-token', baseUrl: 'https://gitlab.com' }, + bitbucket: { token: 'test-token', baseUrl: 'https://api.bitbucket.org/2.0' }, }, })); @@ -88,7 +90,7 @@ describe('GitHubWriter', () => { beforeEach(() => { vi.clearAllMocks(); - writer = new GitHubWriter('org', 'repo'); + writer = new GitHubWriter('org', 'repo', 'https://github.com/org/repo'); }); describe('createOrUpdateChangeRequest', () => { diff --git a/packages/core/src/platforms/github/reader.ts b/packages/core/src/platforms/github/reader.ts index 1e9f6e19..d2757768 100644 --- a/packages/core/src/platforms/github/reader.ts +++ b/packages/core/src/platforms/github/reader.ts @@ -14,16 +14,15 @@ import { } from '../../schemas/source-platform.schema.js'; import { applyDiffTruncation, wrapPlatformError } from '../platform-utils.js'; import { parseChangeRequestRef } from '../change-request-url.js'; +import { resolvePlatformEndpoint } from '../api-endpoint.js'; export class GitHubReader implements SourcePlatformReader { - private octokit: Octokit; + constructor(private readonly token?: string) {} - constructor(token?: string) { - const authToken = token ?? CONFIG.github.token; - this.octokit = new Octokit({ - ...(authToken ? { auth: authToken } : {}), - baseUrl: CONFIG.github.baseUrl, - }); + private clientFor(ref: ChangeRequestRef): Octokit { + const { baseUrl, tokenApplies } = resolvePlatformEndpoint(ref.repositoryUrl, 'github'); + const authToken = this.token ?? (tokenApplies ? CONFIG.github.token : undefined); + return new Octokit({ ...(authToken ? { auth: authToken } : {}), baseUrl }); } parseChangeRequestUrl(url: string): ChangeRequestRef { @@ -39,14 +38,15 @@ export class GitHubReader implements SourcePlatformReader { const repo = ref.platformId.repo; const pull_number = ref.number; + const octokit = this.clientFor(ref); try { - const { data: pr } = await this.octokit.rest.pulls.get({ + const { data: pr } = await octokit.rest.pulls.get({ owner, repo, pull_number, }); - const { data: files } = await this.octokit.rest.pulls.listFiles({ + const { data: files } = await octokit.rest.pulls.listFiles({ owner, repo, pull_number, @@ -71,7 +71,7 @@ export class GitHubReader implements SourcePlatformReader { totalLines ); - const { data: comparison } = await this.octokit.rest.repos.compareCommits({ + const { data: comparison } = await octokit.rest.repos.compareCommits({ owner, repo, base: pr.base.sha, @@ -127,8 +127,9 @@ export class GitHubReader implements SourcePlatformReader { const repo = ref.platformId.repo; const pull_number = ref.number; + const octokit = this.clientFor(ref); try { - const { data: commits } = await this.octokit.rest.pulls.listCommits({ + const { data: commits } = await octokit.rest.pulls.listCommits({ owner, repo, pull_number, diff --git a/packages/core/src/platforms/github/writer.ts b/packages/core/src/platforms/github/writer.ts index e5194c37..374e9e06 100644 --- a/packages/core/src/platforms/github/writer.ts +++ b/packages/core/src/platforms/github/writer.ts @@ -10,6 +10,7 @@ import type { } from '../source-platform.js'; import { wrapPlatformError, isTransientError } from '../platform-utils.js'; import { extractStatusCode } from '../../utils/error-utils.js'; +import { resolvePlatformEndpoint } from '../api-endpoint.js'; function throw403AsPermissionError(error: unknown, prNumber: number): void { if (error instanceof Error && extractStatusCode(error) === 403) { @@ -27,8 +28,11 @@ export class GitHubWriter implements SourcePlatformWriter { private readonly targetOwner: string; private readonly targetRepo: string; - constructor(targetOwner: string, targetRepo: string) { - const token = CONFIG.github.modelRepoPrToken ?? CONFIG.github.token; + constructor(targetOwner: string, targetRepo: string, repositoryUrl: string) { + const { baseUrl, tokenApplies } = resolvePlatformEndpoint(repositoryUrl, 'github'); + const token = tokenApplies + ? (CONFIG.github.modelRepoPrToken ?? CONFIG.github.token) + : undefined; if (!token) { throw new ErodeError( 'A GitHub token is needed to create PRs', @@ -36,7 +40,7 @@ export class GitHubWriter implements SourcePlatformWriter { `Provide ${ENV_VAR_NAMES.modelRepoPrToken} or ${ENV_VAR_NAMES.githubToken} in your environment or ${RC_FILENAME} to create PRs.` ); } - this.octokit = new Octokit({ auth: token, baseUrl: CONFIG.github.baseUrl }); + this.octokit = new Octokit({ auth: token, baseUrl }); this.targetOwner = targetOwner; this.targetRepo = targetRepo; } diff --git a/packages/core/src/platforms/gitlab/__tests__/writer.test.ts b/packages/core/src/platforms/gitlab/__tests__/writer.test.ts index f1c4888a..05fa63e4 100644 --- a/packages/core/src/platforms/gitlab/__tests__/writer.test.ts +++ b/packages/core/src/platforms/gitlab/__tests__/writer.test.ts @@ -41,7 +41,9 @@ vi.mock('@gitbeaker/rest', () => ({ vi.mock('../../../utils/config.js', async (importOriginal) => ({ ...(await importOriginal()), CONFIG: { + github: { token: 'test-token', modelRepoPrToken: null, baseUrl: 'https://api.github.com' }, gitlab: { token: 'test-token', baseUrl: 'https://gitlab.com' }, + bitbucket: { token: 'test-token', baseUrl: 'https://api.bitbucket.org/2.0' }, }, })); @@ -62,7 +64,7 @@ describe('GitLabWriter', () => { beforeEach(() => { vi.clearAllMocks(); - writer = new GitLabWriter('org', 'repo'); + writer = new GitLabWriter('org', 'repo', 'https://gitlab.com/org/repo'); }); describe('constructor', () => { @@ -72,8 +74,12 @@ describe('GitLabWriter', () => { CONFIG.gitlab.token = undefined; try { - expect(() => new GitLabWriter('org', 'repo')).toThrow(ErodeError); - expect(() => new GitLabWriter('org', 'repo')).toThrow('A GitLab token is needed'); + expect(() => new GitLabWriter('org', 'repo', 'https://gitlab.com/org/repo')).toThrow( + ErodeError + ); + expect(() => new GitLabWriter('org', 'repo', 'https://gitlab.com/org/repo')).toThrow( + 'A GitLab token is needed' + ); } finally { CONFIG.gitlab.token = originalToken; } diff --git a/packages/core/src/platforms/gitlab/reader.ts b/packages/core/src/platforms/gitlab/reader.ts index c5150e7e..adbc87f1 100644 --- a/packages/core/src/platforms/gitlab/reader.ts +++ b/packages/core/src/platforms/gitlab/reader.ts @@ -19,16 +19,15 @@ import { } from '../../schemas/source-platform.schema.js'; import { applyDiffTruncation, wrapPlatformError } from '../platform-utils.js'; import { parseChangeRequestRef } from '../change-request-url.js'; +import { resolvePlatformEndpoint } from '../api-endpoint.js'; export class GitLabReader implements SourcePlatformReader { - private api: InstanceType; + constructor(private readonly token?: string) {} - constructor(token?: string) { - const authToken = token ?? CONFIG.gitlab.token; - this.api = new Gitlab({ - ...(authToken ? { token: authToken } : {}), - host: CONFIG.gitlab.baseUrl, - }); + private clientFor(ref: ChangeRequestRef): InstanceType { + const { baseUrl, tokenApplies } = resolvePlatformEndpoint(ref.repositoryUrl, 'gitlab'); + const authToken = this.token ?? (tokenApplies ? CONFIG.gitlab.token : undefined); + return new Gitlab({ ...(authToken ? { token: authToken } : {}), host: baseUrl }); } parseChangeRequestUrl(url: string): ChangeRequestRef { @@ -45,15 +44,16 @@ export class GitLabReader implements SourcePlatformReader { const projectPath = `${owner}/${repo}`; const mrIid = ref.number; + const api = this.clientFor(ref); try { const mr = validate( GitLabMrResponseSchema, - await this.api.MergeRequests.show(projectPath, mrIid), + await api.MergeRequests.show(projectPath, mrIid), 'GitLab MR response' ); const diffs = validate( z.array(GitLabDiffEntrySchema), - await this.api.MergeRequests.allDiffs(projectPath, mrIid), + await api.MergeRequests.allDiffs(projectPath, mrIid), 'GitLab MR diffs' ); @@ -143,10 +143,11 @@ export class GitLabReader implements SourcePlatformReader { const projectPath = `${owner}/${repo}`; const mrIid = ref.number; + const api = this.clientFor(ref); try { const commits = validate( z.array(GitLabCommitEntrySchema), - await this.api.MergeRequests.allCommits(projectPath, mrIid), + await api.MergeRequests.allCommits(projectPath, mrIid), 'GitLab MR commits' ); const result = commits.map((commit) => ({ diff --git a/packages/core/src/platforms/gitlab/writer.ts b/packages/core/src/platforms/gitlab/writer.ts index 60db1f1b..557397a7 100644 --- a/packages/core/src/platforms/gitlab/writer.ts +++ b/packages/core/src/platforms/gitlab/writer.ts @@ -8,6 +8,7 @@ import type { CreateOrUpdateChangeRequestOptions, } from '../source-platform.js'; import { wrapPlatformError } from '../platform-utils.js'; +import { resolvePlatformEndpoint } from '../api-endpoint.js'; /** Subset of the GitLab MR response fields we access. */ interface GitLabMrResponse { @@ -19,8 +20,9 @@ export class GitLabWriter implements SourcePlatformWriter { private readonly api: InstanceType; private readonly projectPath: string; - constructor(targetOwner: string, targetRepo: string) { - const token = CONFIG.gitlab.token; + constructor(targetOwner: string, targetRepo: string, repositoryUrl: string) { + const { baseUrl, tokenApplies } = resolvePlatformEndpoint(repositoryUrl, 'gitlab'); + const token = tokenApplies ? CONFIG.gitlab.token : undefined; if (!token) { throw new ErodeError( 'A GitLab token is needed to create merge requests', @@ -28,7 +30,7 @@ export class GitLabWriter implements SourcePlatformWriter { `Provide ${ENV_VAR_NAMES.gitlabToken} in your environment or ${RC_FILENAME} to create merge requests.` ); } - this.api = new Gitlab({ token, host: CONFIG.gitlab.baseUrl }); + this.api = new Gitlab({ token, host: baseUrl }); this.projectPath = `${targetOwner}/${targetRepo}`; } diff --git a/packages/core/src/platforms/platform-factory.ts b/packages/core/src/platforms/platform-factory.ts index f0e4eb14..2e425abc 100644 --- a/packages/core/src/platforms/platform-factory.ts +++ b/packages/core/src/platforms/platform-factory.ts @@ -71,11 +71,11 @@ export function createPlatformWriter( const platform = detectPlatform(repositoryUrl); switch (platform) { case 'github': - return new GitHubWriter(targetOwner, targetRepo); + return new GitHubWriter(targetOwner, targetRepo, repositoryUrl); case 'gitlab': - return new GitLabWriter(targetOwner, targetRepo); + return new GitLabWriter(targetOwner, targetRepo, repositoryUrl); case 'bitbucket': - return new BitbucketWriter(targetOwner, targetRepo); + return new BitbucketWriter(targetOwner, targetRepo, repositoryUrl); default: { const _exhaustive: never = platform; throw new ErodeError( diff --git a/packages/core/src/utils/repo-locator.ts b/packages/core/src/utils/repo-locator.ts index 401c9a4b..e6d0d7d4 100644 --- a/packages/core/src/utils/repo-locator.ts +++ b/packages/core/src/utils/repo-locator.ts @@ -356,6 +356,11 @@ const TOKEN_BASE_PLATFORMS: Record = { bitbucket: 'bitbucket-server', }; +/** True when the locator is on the platform's public host (github.com, gitlab.com, bitbucket.org). */ +export function isPublicInstance(locator: RepoLocator, tokenPlatform: TokenPlatform): boolean { + return locator.host === TOKEN_DEFAULT_HOSTS[tokenPlatform] && locator.port === undefined; +} + /** * True when the locator is on the instance a platform token is issued for: the * self-hosted instance from `ERODE_*_BASE_URL` (host, port and base path) when @@ -365,9 +370,7 @@ const TOKEN_BASE_PLATFORMS: Record = { export function isTokenInstance(locator: RepoLocator, tokenPlatform: TokenPlatform): boolean { const platform = TOKEN_BASE_PLATFORMS[tokenPlatform]; const base = repositoryHosts().bases.find((b) => b.platform === platform); - if (!base) { - return locator.host === TOKEN_DEFAULT_HOSTS[tokenPlatform] && locator.port === undefined; - } + if (!base) return isPublicInstance(locator, tokenPlatform); if (locator.host !== base.host || locator.port !== base.port) return false; return startsWithPath(splitPath(new URL(locator.canonicalUrl).pathname), base.basePath); }