Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

15.0 KB
Raw Blame
import { type SpawnSyncOptions, spawnSync } from 'node:child_process';
import { accessSync, existsSync, constants as fsConstants, readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { isAbsolute, join, delimiter as PATH_DELIM } from 'node:path';
import { currentCliCommandName } from '@inkeep/open-knowledge-core';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';

export const MIN_GIT_VERSION = '2.31.0';

const PROBE_TIMEOUT_MS = 5000;

export interface GitDetected {
  readonly ok: true;
  readonly version: string;
  readonly resolvedPath: string;
  readonly source: 'PATH' | 'fallback';
}

export interface InstallOption {
  readonly label: string;
  readonly command: string;
  readonly requiresAdmin: boolean;
}

export interface InstallGuidance {
  readonly product: string;
  readonly options: readonly InstallOption[];
  readonly url: string;
}

type GitProbeFailureReason = 'enoent' | 'spawn-failed' | 'unparseable' | 'timeout' | 'nonzero';

export interface GitProbeFailures {
  readonly path: GitProbeFailureReason;
  readonly fallback: GitProbeFailureReason | null;
}

export class GitNotAvailableError extends Error {
  readonly code = 'GIT_NOT_AVAILABLE';
  readonly platform: NodeJS.Platform;
  readonly guidance: InstallGuidance;
  readonly probe: GitProbeFailures | null;

  constructor(
    platform: NodeJS.Platform,
    guidance: InstallGuidance,
    options?: { cause?: unknown; probe?: GitProbeFailures },
  ) {
    super(buildMissingMessage(guidance), options);
    this.name = 'GitNotAvailableError';
    this.platform = platform;
    this.guidance = guidance;
    this.probe = options?.probe ?? null;
  }
}

export class GitProbeTimeoutError extends Error {
  readonly code = 'GIT_PROBE_TIMEOUT';
  readonly platform: NodeJS.Platform;
  readonly guidance: InstallGuidance;
  readonly probe: GitProbeFailures;

  constructor(platform: NodeJS.Platform, guidance: InstallGuidance, probe: GitProbeFailures) {
    super(buildProbeTimeoutMessage(guidance, probe));
    this.name = 'GitProbeTimeoutError';
    this.platform = platform;
    this.guidance = guidance;
    this.probe = probe;
  }
}

export class GitTooOldError extends Error {
  readonly code = 'GIT_TOO_OLD';
  readonly platform: NodeJS.Platform;
  readonly detected: string;
  readonly required: string;
  readonly resolvedPath: string;
  readonly guidance: InstallGuidance;

  constructor(
    platform: NodeJS.Platform,
    detected: string,
    required: string,
    resolvedPath: string,
    guidance: InstallGuidance,
    options?: { cause?: unknown },
  ) {
    super(buildTooOldMessage(detected, required, resolvedPath, guidance), options);
    this.name = 'GitTooOldError';
    this.platform = platform;
    this.detected = detected;
    this.required = required;
    this.resolvedPath = resolvedPath;
    this.guidance = guidance;
  }
}

export function detectGit(): GitDetected {
  const stage1 = probeGit('git');
  if (stage1.kind === 'ok') {
    return {
      ok: true,
      version: stage1.version,
      resolvedPath: stage1.resolvedPath,
      source: 'PATH',
    };
  }

  let fallback: GitProbeFailureReason | null = null;
  let fallbackTimedOut = false;
  for (const candidate of fallbackPaths(process.platform)) {
    if (!existsSync(candidate)) continue;
    const result = probeGit(candidate);
    if (result.kind === 'ok') {
      return {
        ok: true,
        version: result.version,
        resolvedPath: candidate,
        source: 'fallback',
      };
    }
    fallback = result.reason;
    fallbackTimedOut ||= result.reason === 'timeout';
  }

  const probe = {
    path: stage1.reason,
    fallback: fallbackTimedOut ? 'timeout' : fallback,
  };
  if (stage1.reason === 'timeout' || fallbackTimedOut) {
    throw new GitProbeTimeoutError(process.platform, buildGuidance(process.platform), probe);
  }
  throw new GitNotAvailableError(process.platform, buildGuidance(process.platform), { probe });
}

export function assertGitAvailable(): GitDetected {
  const detected = detectGit();
  if (compareSemver(detected.version, MIN_GIT_VERSION) < 0) {
    throw new GitTooOldError(
      process.platform,
      detected.version,
      MIN_GIT_VERSION,
      detected.resolvedPath,
      buildGuidance(process.platform),
    );
  }
  return detected;
}

type ProbeResult =
  | { kind: 'ok'; version: string; resolvedPath: string }
  | { kind: 'fail'; reason: GitProbeFailureReason };

function probeGit(command: string): ProbeResult {
  const opts: SpawnSyncOptions = withHiddenWindowsConsole({
    encoding: 'utf-8',
    timeout: PROBE_TIMEOUT_MS,
    env: { ...process.env, LANG: 'C', LC_ALL: 'C' },
  });
  // oxlint-disable-next-line ok/require-windowshide-on-spawn -- windowsHide is set on `opts` via withHiddenWindowsConsole above; the rule can't see through the by-reference options variable.
  const result = spawnSync(command, ['--version'], opts);
  if (result.error) {
    if ('signal' in result && result.signal === 'SIGTERM')
      return { kind: 'fail', reason: 'timeout' };
    const code = (result.error as NodeJS.ErrnoException).code;
    return { kind: 'fail', reason: code === 'ENOENT' ? 'enoent' : 'spawn-failed' };
  }
  if (result.status !== 0) {
    return { kind: 'fail', reason: 'nonzero' };
  }
  const stdout = typeof result.stdout === 'string' ? result.stdout : '';
  const version = parseGitVersion(stdout);
  if (version === null) return { kind: 'fail', reason: 'unparseable' };
  const resolvedPath = command === 'git' ? (resolveOnPath('git') ?? command) : command;
  return { kind: 'ok', version, resolvedPath };
}

export function parseGitVersion(stdout: string): string | null {
  const match = stdout.match(/git version (\d+)\.(\d+)\.(\d+)/);
  if (!match) return null;
  return `${match[1]}.${match[2]}.${match[3]}`;
}

const SAFE_COMMAND_NAME_RE = /^[a-zA-Z0-9_.-]+$/;

const resolveOnPathCache = new Map<string, string>();

export function __resetResolveOnPathCacheForTests(): void {
  resolveOnPathCache.clear();
}

export function __seedResolveOnPathCacheForTests(name: string, resolvedPath: string): void {
  resolveOnPathCache.set(name, resolvedPath);
}

function envValue(name: string): string | undefined {
  if (process.platform !== 'win32') return process.env[name];
  const key = Object.keys(process.env).find((k) => k.toUpperCase() === name);
  return key === undefined ? undefined : process.env[key];
}

function commandFileNames(name: string): readonly string[] {
  if (process.platform !== 'win32') return [name];
  const configured = (envValue('PATHEXT') ?? '')
    .split(';')
    .map((ext) => ext.trim().toLowerCase())
    .filter((ext) => ext.startsWith('.'));
  const extensions = configured.length > 0 ? configured : ['.com', '.exe', '.bat', '.cmd'];
  const lower = name.toLowerCase();
  return extensions.some((ext) => lower.endsWith(ext))
    ? [name]
    : extensions.map((ext) => `${name}${ext}`);
}

function isRunnableFile(path: string): boolean {
  try {
    if (!statSync(path).isFile()) return false;
    if (process.platform !== 'win32') accessSync(path, fsConstants.X_OK);
    return true;
  } catch {
    return false;
  }
}

export function resolveOnPath(name: string, pathOverride?: string): string | null {
  if (!SAFE_COMMAND_NAME_RE.test(name)) return null;
  const cacheKey = pathOverride === undefined ? name : `${pathOverride}\u0000${name}`;
  const cached = resolveOnPathCache.get(cacheKey);
  if (cached !== undefined) return cached;
  const dirs = (pathOverride ?? envValue('PATH') ?? '')
    .split(PATH_DELIM)
    .map((dir) => dir.trim().replace(/^"(.*)"$/, '$1'))
    .filter((dir) => dir !== '' && isAbsolute(dir));
  const fileNames = commandFileNames(name);
  for (const dir of dirs) {
    for (const fileName of fileNames) {
      const candidate = join(dir, fileName);
      if (isRunnableFile(candidate)) {
        resolveOnPathCache.set(cacheKey, candidate);
        return candidate;
      }
    }
  }
  return null;
}

export function fallbackPaths(platform: NodeJS.Platform): readonly string[] {
  switch (platform) {
    case 'darwin':
      return [
        '/opt/homebrew/bin/git',
        '/usr/local/bin/git',
        '/Library/Developer/CommandLineTools/usr/bin/git',
        '/usr/bin/git',
      ];
    case 'win32':
      return [
        'C:\\Program Files\\Git\\cmd\\git.exe',
        'C:\\Program Files (x86)\\Git\\cmd\\git.exe',
        join(homedir(), 'scoop', 'apps', 'git', 'current', 'cmd', 'git.exe'),
      ];
    default:
      return [
        '/usr/bin/git',
        '/usr/local/bin/git',
        join(homedir(), '.local', 'bin', 'git'),
        '/snap/bin/git',
      ];
  }
}

export function buildGuidance(platform: NodeJS.Platform): InstallGuidance {
  switch (platform) {
    case 'darwin': {
      const options: InstallOption[] = [];
      if (hasBrew()) {
        options.push({
          label: 'Install with Homebrew (recommended; no admin needed)',
          command: 'brew install git',
          requiresAdmin: false,
        });
      }
      options.push({
        label: 'Install Xcode Command Line Tools',
        command: 'xcode-select --install',
        requiresAdmin: true,
      });
      return {
        product: 'Git',
        url: 'https://git-scm.com/download/mac',
        options,
      };
    }
    case 'win32': {
      const options: InstallOption[] = [];
      if (hasWinget()) {
        options.push({
          label: 'Install with winget',
          command: 'winget install --id Git.Git -e --source winget',
          requiresAdmin: true,
        });
      }
      if (hasScoop()) {
        options.push({
          label: 'Install with Scoop (no admin)',
          command: 'scoop install git',
          requiresAdmin: false,
        });
      }
      if (hasChoco()) {
        options.push({
          label: 'Install with Chocolatey',
          command: 'choco install git -y',
          requiresAdmin: true,
        });
      }
      options.push({
        label: 'Download the official installer',
        command: 'Open https://gitforwindows.org/ in your browser',
        requiresAdmin: false,
      });
      return {
        product: 'Git for Windows',
        url: 'https://gitforwindows.org/',
        options,
      };
    }
    default:
      return {
        product: 'Git',
        url: 'https://git-scm.com/download/linux',
        options: linuxInstallOptions(),
      };
  }
}

function linuxInstallOptions(): InstallOption[] {
  const family = detectLinuxFamily();
  switch (family) {
    case 'debian':
      return [{ label: 'Install with apt', command: 'sudo apt install git', requiresAdmin: true }];
    case 'fedora':
      return [{ label: 'Install with dnf', command: 'sudo dnf install git', requiresAdmin: true }];
    case 'arch':
      return [{ label: 'Install with pacman', command: 'sudo pacman -S git', requiresAdmin: true }];
    case 'opensuse':
      return [
        { label: 'Install with zypper', command: 'sudo zypper install git', requiresAdmin: true },
      ];
    case 'alpine':
      return [{ label: 'Install with apk', command: 'sudo apk add git', requiresAdmin: true }];
    default:
      return [
        {
          label: "Use your distribution's package manager",
          command:
            'apt / dnf / pacman / zypper / apk install git (one of these will fit your system)',
          requiresAdmin: true,
        },
      ];
  }
}

export type LinuxFamily = 'debian' | 'fedora' | 'arch' | 'opensuse' | 'alpine' | 'unknown';

export function detectLinuxFamily(osReleaseContents?: string): LinuxFamily {
  let contents = osReleaseContents;
  if (contents === undefined) {
    try {
      contents = readFileSync('/etc/os-release', 'utf-8');
    } catch {
      return 'unknown';
    }
  }
  const id = /^ID=(.+)$/m.exec(contents)?.[1]?.replace(/["']/g, '');
  const idLike = /^ID_LIKE=(.+)$/m.exec(contents)?.[1]?.replace(/["']/g, '') ?? '';
  const tokens = [id, ...idLike.split(/\s+/)].filter((t): t is string => Boolean(t));
  if (tokens.some((t) => /^(debian|ubuntu|mint|pop)$/i.test(t))) return 'debian';
  if (tokens.some((t) => /^(fedora|rhel|centos|alma|rocky)$/i.test(t))) return 'fedora';
  if (tokens.some((t) => /^(arch|manjaro|endeavouros)$/i.test(t))) return 'arch';
  if (tokens.some((t) => /^opensuse/i.test(t)) || tokens.includes('suse')) return 'opensuse';
  if (tokens.some((t) => /^alpine$/i.test(t))) return 'alpine';
  return 'unknown';
}

function hasCommand(name: string): boolean {
  return resolveOnPath(name) !== null;
}

function hasBrew(): boolean {
  return hasCommand('brew');
}
function hasWinget(): boolean {
  return hasCommand('winget');
}
function hasScoop(): boolean {
  return hasCommand('scoop');
}
function hasChoco(): boolean {
  return hasCommand('choco');
}

function buildMissingMessage(g: InstallGuidance): string {
  const lines: string[] = [];
  lines.push(
    `OpenKnowledge needs ${g.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`,
  );
  lines.push('');
  if (g.options.length > 0) {
    lines.push(`Install ${g.product}:`);
    for (const opt of g.options) {
      const adminTag = opt.requiresAdmin ? ' (admin required)' : '';
      lines.push(`  • ${opt.label}${adminTag}`);
      lines.push(`      ${opt.command}`);
    }
    lines.push('');
  }
  lines.push(`Or download from: ${g.url}`);
  lines.push('');
  lines.push('After installing, re-run OpenKnowledge.');
  lines.push(
    `Run \`${currentCliCommandName()} diagnose health --check git\` to verify your installation.`,
  );
  return lines.join('\n');
}

function buildProbeTimeoutMessage(g: InstallGuidance, probe: GitProbeFailures): string {
  return [
    `OpenKnowledge could not verify ${g.product} because the Git probe timed out. Git may be installed but unavailable while the machine is busy.`,
    '',
    `Probe results: PATH=${probe.path}, fallback=${probe.fallback ?? 'not attempted'}.`,
    'Check that Git is installed and retry OpenKnowledge.',
    `Run \`${currentCliCommandName()} diagnose health --check git\` to verify your installation.`,
  ].join('\n');
}

function buildTooOldMessage(
  detected: string,
  required: string,
  resolvedPath: string,
  g: InstallGuidance,
): string {
  const lines: string[] = [];
  lines.push(
    `OpenKnowledge requires ${g.product} ${required} or newer (detected ${detected} at ${resolvedPath}).`,
  );
  lines.push('');
  if (g.options.length > 0) {
    lines.push(`Update ${g.product}:`);
    for (const opt of g.options) {
      const adminTag = opt.requiresAdmin ? ' (admin required)' : '';
      lines.push(`  • ${opt.label}${adminTag}`);
      lines.push(`      ${opt.command}`);
    }
    lines.push('');
  }
  lines.push(`Or download from: ${g.url}`);
  lines.push('');
  lines.push('After updating, re-run OpenKnowledge.');
  lines.push(
    `Run \`${currentCliCommandName()} diagnose health --check git\` to verify your installation.`,
  );
  return lines.join('\n');
}

export function compareSemver(a: string, b: string): number {
  const pa = a.split('.').map((s) => Number.parseInt(s, 10) || 0);
  const pb = b.split('.').map((s) => Number.parseInt(s, 10) || 0);
  for (let i = 0; i < 3; i++) {
    const av = pa[i] ?? 0;
    const bv = pb[i] ?? 0;
    if (av !== bv) return av - bv;
  }
  return 0;
}

export const PATH_DELIMITER: string = PATH_DELIM;