export type Source = { url: string; host: string; name: string };
export type Parsed = { line: string; source: Source | null; problem: string | null };
const handle = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/;
const repoName = /^[A-Za-z0-9._-]{1,100}$/;
export const ownerProblem = (owner: string) =>
owner === '' ? 'Enter the Sailfork user or organization that will own the repositories.' : handle.test(owner) ? null : 'Use the handle as it appears in your Sailfork URL: lowercase letters, numbers and hyphens.';
// Accepts https and scp-style ssh URLs from any git host, including GitLab subgroups; the last path segment becomes the name.
export const parseSource = (raw: string): Parsed => {
const trimmed = raw.trim();
// A pasted address bar URL often has no scheme; git needs one.
const line = /^[\w.-]+\.[a-z]{2,}\/[^\s]+$/i.test(trimmed) ? `https://${trimmed}` : trimmed;
const https = /^https?:\/\/([^/\s]+)\/((?:[^/\s]+\/)*[^/\s]+?)(?:\.git)?\/?$/.exec(line);
const scp = /^(?:ssh:\/\/)?[\w.-]+@([^:/\s]+)[:/]((?:[^/\s]+\/)*[^/\s]+?)(?:\.git)?\/?$/.exec(line);
const match = https ?? scp;
if (!match) return { line, source: null, problem: 'Not a git URL. Paste it the way you would pass it to git clone.' };
const [, host = '', path = ''] = match;
if (!path.includes('/')) return { line, source: null, problem: 'Include the owner and the repository, like github.com/acme/api.' };
const name = path.split('/').pop() ?? '';
if (!repoName.test(name)) return { line, source: null, problem: `“${name}” cannot be a repository name on Sailfork. Use letters, numbers, dots, hyphens and underscores.` };
return { line, source: { url: line, host, name }, problem: null };
};
export const target = (owner: string, name: string, protocol: 'ssh' | 'https') =>
protocol === 'ssh' ? `git@sailfork.com:${owner}/${name}.git` : `https://sailfork.com/${owner}/${name}.git`;
const quote = (s: string) => `'${s.replaceAll("'", `'\\''`)}'`;
// A bare clone holds only branches and tags, so host-only refs like GitHub's refs/pull/* never reach Sailfork.
export const script = (sources: Source[], owner: string, protocol: 'ssh' | 'https') =>
[
'#!/usr/bin/env bash',
'set -euo pipefail',
'work=$(mktemp -d)',
'trap \'rm -rf "$work"\' EXIT',
'',
...sources.flatMap((s) => {
const to = target(owner, s.name, protocol);
return [
`# ${s.name}`,
`git clone --bare ${quote(s.url)} "$work/${s.name}.git"`,
`git -C "$work/${s.name}.git" push ${quote(to)} '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'`,
`diff <(git ls-remote --heads --tags ${quote(s.url)} | sort) <(git ls-remote --heads --tags ${quote(to)} | sort) && echo "${s.name}: every branch and tag matches"`,
''
];
})
].join('\n');
export const remoteUpdate = (owner: string, protocol: 'ssh' | 'https', name: string) => `git remote set-url origin ${target(owner, name, protocol)}`;