Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

14.4 KB
Raw Blame
import { execFile } from 'node:child_process';
import { tmpdir } from 'node:os';
import { promisify } from 'node:util';

import { createLogger } from '../logger';
import type {
  GitPullRequestAction,
  GitPullRequestActionResult,
  GitPullRequestActivity,
  GitPullRequestCheck,
  GitPullRequestDetail,
  GitPullRequestDetailResult,
  GitPullRequestMergeContext,
} from './types';

const log = createLogger('local-file-shell:git');
const execFileAsync = promisify(execFile);

const GITHUB_PULL_REQUEST_DETAIL_FIELDS =
  'number,title,body,state,isDraft,isCrossRepository,mergedAt,mergeable,mergeStateStatus,reviewDecision,autoMergeRequest,baseRefName,headRefName,headRefOid,url,author,additions,deletions,changedFiles,commits,comments,reviews,statusCheckRollup';

type GithubPullRequestAuthor = { login?: string | null } | null;

type GithubPullRequestCommit = {
  authors?: { login?: string | null }[] | null;
  committedDate?: string | null;
  messageHeadline?: string | null;
  oid: string;
};

type GithubPullRequestComment = {
  author?: GithubPullRequestAuthor;
  body?: string | null;
  createdAt?: string | null;
  id: string;
};

type GithubPullRequestReview = {
  author?: GithubPullRequestAuthor;
  state: string;
  submittedAt?: string | null;
};

type GithubStatusCheckRollupNode = {
  completedAt?: string | null;
  conclusion?: string | null;
  context?: string | null;
  createdAt?: string | null;
  detailsUrl?: string | null;
  name?: string | null;
  startedAt?: string | null;
  state?: string | null;
  status?: string | null;
  targetUrl?: string | null;
};

type GithubPullRequestDetailPayload = {
  additions: number;
  author?: GithubPullRequestAuthor;
  autoMergeRequest?: { mergeMethod?: string | null } | null;
  baseRefName: string;
  body?: string | null;
  changedFiles: number;
  comments?: GithubPullRequestComment[] | null;
  commits?: GithubPullRequestCommit[] | null;
  deletions: number;
  headRefName: string;
  headRefOid: string;
  isCrossRepository?: boolean;
  isDraft?: boolean;
  mergeable?: string | null;
  mergedAt?: string | null;
  mergeStateStatus?: string | null;
  number: number;
  reviewDecision?: string | null;
  reviews?: GithubPullRequestReview[] | null;
  state: string;
  statusCheckRollup?: GithubStatusCheckRollupNode[] | null;
  title: string;
  url: string;
};

export type GithubRepoInfo = { name: string; owner: string };

const failureConclusions = new Set([
  'action_required',
  'cancelled',
  'failure',
  'startup_failure',
  'timed_out',
]);
const successConclusions = new Set(['neutral', 'skipped', 'success']);

const toLowerOrUndefined = (value?: string | null) => value?.toLowerCase();

const normalizeCheckStatus = (node: GithubStatusCheckRollupNode): GitPullRequestCheck['status'] => {
  const state = toLowerOrUndefined(node.state);
  if (state) {
    if (state === 'success') return 'success';
    if (state === 'failure' || state === 'error') return 'failure';
    return 'pending';
  }

  const status = toLowerOrUndefined(node.status);
  if (status && status !== 'completed') return 'pending';

  const conclusion = toLowerOrUndefined(node.conclusion);
  if (conclusion === 'skipped') return 'skipped';
  if (conclusion === 'cancelled') return 'cancelled';
  if (conclusion && successConclusions.has(conclusion))
    return conclusion === 'neutral' ? 'neutral' : 'success';
  if (conclusion && failureConclusions.has(conclusion)) return 'failure';
  return 'pending';
};

const normalizeCheck = (node: GithubStatusCheckRollupNode): GitPullRequestCheck => {
  const name = node.name ?? node.context ?? '';
  const detailsUrl = node.detailsUrl ?? node.targetUrl ?? undefined;
  const startedAt = node.startedAt ?? node.createdAt ?? undefined;

  return {
    ...(node.completedAt ? { completedAt: node.completedAt } : {}),
    ...(detailsUrl ? { detailsUrl } : {}),
    name,
    required: false,
    ...(startedAt ? { startedAt } : {}),
    status: normalizeCheckStatus(node),
  };
};

const toMergeMethod = (raw?: string | null): 'merge' | 'rebase' | 'squash' | undefined => {
  const lower = toLowerOrUndefined(raw);
  if (lower === 'merge' || lower === 'rebase' || lower === 'squash') return lower;
  return undefined;
};

export const repoFromPullRequestUrl = (url: string): GithubRepoInfo => {
  const match = /github\.com\/([^/]+)\/([^/]+)\/pull\//.exec(url ?? '');
  return { name: match?.[2] ?? '', owner: match?.[1] ?? '' };
};

const normalizePullRequestActivity = (
  raw: Pick<GithubPullRequestDetailPayload, 'comments' | 'commits' | 'reviews'>,
): GitPullRequestActivity => ({
  comments: (raw.comments ?? []).map((comment) => ({
    author: comment.author?.login ?? '',
    body: comment.body ?? '',
    createdAt: comment.createdAt ?? '',
    id: comment.id,
  })),
  commits: (raw.commits ?? []).map((commit) => ({
    author: commit.authors?.[0]?.login ?? '',
    committedAt: commit.committedDate ?? '',
    message: commit.messageHeadline ?? '',
    sha: commit.oid,
  })),
  reviews: (raw.reviews ?? []).map((review) => ({
    author: review.author?.login ?? '',
    state: review.state as GitPullRequestDetail['reviews'][number]['state'],
    submittedAt: review.submittedAt ?? '',
  })),
});

export const getPullRequestActivity = async (payload: {
  number: number;
  path: string;
}): Promise<GitPullRequestActivity> => {
  const { stdout } = await execFileAsync(
    'gh',
    ['pr', 'view', String(payload.number), '--json', 'comments,commits,reviews'],
    { cwd: payload.path, timeout: 8000 },
  );
  return normalizePullRequestActivity(JSON.parse(stdout));
};

export const normalizePullRequestDetail = (
  raw: GithubPullRequestDetailPayload,
  repo: GithubRepoInfo,
): GitPullRequestDetail => {
  const autoMergeMethod = toMergeMethod(raw.autoMergeRequest?.mergeMethod);

  return {
    additions: raw.additions,
    author: raw.author?.login ?? '',
    autoMerge: autoMergeMethod ? { method: autoMergeMethod } : null,
    baseBehindBy: 0,
    baseRefName: raw.baseRefName,
    body: raw.body ?? '',
    changedFiles: raw.changedFiles,
    checks: (raw.statusCheckRollup ?? []).map(normalizeCheck),
    ...normalizePullRequestActivity(raw),
    deletions: raw.deletions,
    headRefName: raw.headRefName,
    headRefOid: raw.headRefOid,
    isCrossRepository: raw.isCrossRepository ?? false,
    isDraft: raw.isDraft ?? false,
    mergeable: (raw.mergeable as GitPullRequestDetail['mergeable']) ?? 'UNKNOWN',
    ...(raw.mergedAt ? { mergedAt: raw.mergedAt } : {}),
    mergeStateStatus:
      (raw.mergeStateStatus as GitPullRequestDetail['mergeStateStatus']) ?? 'UNKNOWN',
    number: raw.number,
    repo: { name: repo.name, owner: repo.owner },
    reviewDecision: (raw.reviewDecision || null) as GitPullRequestDetail['reviewDecision'],
    state: raw.mergedAt ? 'merged' : toLowerOrUndefined(raw.state) === 'closed' ? 'closed' : 'open',
    title: raw.title,
    url: raw.url,
    viewerCanBypass: false,
    viewerCanWrite: false,
  };
};

const MERGE_CONTEXT_GRAPHQL = `
query($owner: String!, $name: String!, $number: Int!) {
  repository(owner: $owner, name: $name) {
    viewerPermission
    pullRequest(number: $number) {
      baseRef {
        branchProtectionRule { requiredStatusCheckContexts }
      }
    }
  }
}`.trim();

type MergeContextPayload = {
  data?: {
    repository?: {
      pullRequest?: {
        baseRef?: {
          branchProtectionRule?: { requiredStatusCheckContexts?: string[] | null } | null;
        } | null;
      } | null;
      viewerPermission?: string | null;
    } | null;
  };
};

const EMPTY_MERGE_CONTEXT: GitPullRequestMergeContext = {
  baseBehindBy: 0,
  requiredChecks: [],
  viewerCanBypass: false,
  viewerCanWrite: false,
};

export const normalizeMergeContext = (
  payload: MergeContextPayload,
  baseBehindBy: number,
): GitPullRequestMergeContext => {
  const repository = payload.data?.repository;
  const viewerPermission = repository?.viewerPermission ?? '';
  return {
    baseBehindBy,
    requiredChecks:
      repository?.pullRequest?.baseRef?.branchProtectionRule?.requiredStatusCheckContexts ?? [],
    viewerCanBypass: viewerPermission === 'ADMIN',
    viewerCanWrite:
      viewerPermission === 'ADMIN' ||
      viewerPermission === 'MAINTAIN' ||
      viewerPermission === 'WRITE',
  };
};

export const getPullRequestMergeContext = async (payload: {
  baseRefName: string;
  headRefOid: string;
  number: number;
  path: string;
  repo: GithubRepoInfo;
}): Promise<GitPullRequestMergeContext> => {
  const { path: dirPath, number, repo, baseRefName, headRefOid } = payload;
  assertBranchName(baseRefName);
  if (!/^[a-f\d]{40}$/i.test(headRefOid)) return EMPTY_MERGE_CONTEXT;
  const exec = (args: string[]) => execFileAsync('gh', args, { cwd: dirPath, timeout: 8000 });

  const [graphql, compare] = await Promise.allSettled([
    exec([
      'api',
      'graphql',
      '-F',
      `owner=${repo.owner}`,
      '-F',
      `name=${repo.name}`,
      '-F',
      `number=${number}`,
      '-f',
      `query=${MERGE_CONTEXT_GRAPHQL}`,
    ]),
    exec([
      'api',
      `repos/${repo.owner}/${repo.name}/compare/${baseRefName}...${headRefOid}`,
      '--jq',
      '.behind_by',
    ]),
  ]);

  if (graphql.status === 'rejected')
    log.debug('[getPullRequestMergeContext] failed', { number, stderr: graphql.reason?.stderr });
  const parsed =
    graphql.status === 'fulfilled'
      ? (JSON.parse(graphql.value.stdout.trim() || '{}') as MergeContextPayload)
      : {};
  const baseBehindBy =
    compare.status === 'fulfilled' ? Number(compare.value.stdout.trim()) || 0 : 0;
  return normalizeMergeContext(parsed, baseBehindBy);
};

const VALID_BRANCH_NAME = /^[\w./-]+$/;

const assertBranchName = (name: string) => {
  if (!VALID_BRANCH_NAME.test(name) || name.split('/').includes('..'))
    throw new Error('Invalid branch name');
};

const isGhMissing = (error: any): boolean => {
  const code = error?.code;
  const stderr: string = error?.stderr ?? '';
  return code === 'ENOENT' || /auth\s+login|not\s+logged\s+in|authentication/i.test(stderr);
};

export const getPullRequestDetail = async (payload: {
  coreOnly?: boolean;
  number: number;
  path: string;
}): Promise<GitPullRequestDetailResult> => {
  const { path: dirPath, number } = payload;

  try {
    const { stdout } = await execFileAsync(
      'gh',
      [
        'pr',
        'view',
        String(number),
        '--json',
        payload.coreOnly
          ? GITHUB_PULL_REQUEST_DETAIL_FIELDS.split(',')
              .filter((field) => !['comments', 'commits', 'reviews'].includes(field))
              .join(',')
          : GITHUB_PULL_REQUEST_DETAIL_FIELDS,
      ],
      { cwd: dirPath, timeout: 8000 },
    );

    const raw = JSON.parse(stdout.trim() || '{}') as GithubPullRequestDetailPayload;

    return {
      detail: normalizePullRequestDetail(raw, repoFromPullRequestUrl(raw.url)),
      status: 'ok',
    };
  } catch (error: any) {
    if (isGhMissing(error)) return { detail: null, status: 'gh-missing' };
    log.debug('[getPullRequestDetail] failed', {
      code: error?.code,
      number,
      stderr: error?.stderr,
    });
    return { detail: null, status: 'error' };
  }
};

export const pullRequestActionArgs = (
  number: number,
  action: GitPullRequestAction,
  url?: string,
): string[][] => {
  const n = url ?? String(number);
  if (
    (action.type === 'merge' || action.type === 'autoMerge') &&
    !/^[a-f\d]{40}$/i.test(action.headRefOid ?? '')
  )
    throw new Error('A valid pull request head commit is required');

  switch (action.type) {
    case 'merge': {
      const argv = [
        'pr',
        'merge',
        n,
        `--${action.method}`,
        '--match-head-commit',
        action.headRefOid,
      ];
      if (action.admin) argv.push('--admin');
      if (action.deleteBranch) argv.push('--delete-branch');
      return [argv];
    }
    case 'autoMerge': {
      return [
        [
          'pr',
          'merge',
          n,
          '--auto',
          `--${action.method}`,
          '--match-head-commit',
          action.headRefOid,
        ],
      ];
    }
    case 'disableAutoMerge': {
      return [['pr', 'merge', n, '--disable-auto']];
    }
    case 'updateBranch': {
      return [
        action.method === 'rebase'
          ? ['pr', 'update-branch', n, '--rebase']
          : ['pr', 'update-branch', n],
      ];
    }
    case 'ready': {
      return [['pr', 'ready', n]];
    }
    case 'comment': {
      return [['pr', 'comment', n, '--body', action.body]];
    }
    case 'close': {
      return [['pr', 'close', n]];
    }
    case 'reopen': {
      return [['pr', 'reopen', n]];
    }
    case 'deleteBranch': {
      assertBranchName(action.head);
      const repo = url ? repoFromPullRequestUrl(url) : { name: '{repo}', owner: '{owner}' };
      const host = url ? ['--hostname', 'github.com'] : [];
      return [
        [
          'api',
          ...host,
          '-X',
          'DELETE',
          `repos/${repo.owner}/${repo.name}/git/refs/heads/${action.head}`,
        ],
      ];
    }
    case 'changeBase': {
      assertBranchName(action.base);
      return [['pr', 'edit', n, '--base', action.base]];
    }
  }
};

export const runPullRequestAction = async (payload: {
  action: GitPullRequestAction;
  number: number;
  path: string;
  url?: string;
}): Promise<GitPullRequestActionResult> => {
  const { path: dirPath, number, action, url } = payload;

  try {
    const commands = pullRequestActionArgs(number, action, url);
    if (url) {
      if (action.type === 'merge' && action.deleteBranch)
        throw new Error('Deleting the local branch requires the selected checkout');
      // The cloud has approved dirPath. Resolve the numeric PR there first, so
      // a workspace member cannot use the device's GitHub account on a PR in
      // another repository by supplying its URL.
      const { stdout } = await execFileAsync(
        'gh',
        ['pr', 'view', String(number), '--json', 'url'],
        {
          cwd: dirPath,
          timeout: 8000,
        },
      );
      const confirmed = JSON.parse(stdout) as { url?: string };
      if (confirmed.url?.toLowerCase() !== url.toLowerCase())
        throw new Error('The pull request does not match the approved repository');
    }

    for (const argv of commands) {
      await execFileAsync('gh', argv, { cwd: url ? tmpdir() : dirPath, timeout: 60_000 });
    }
    return { success: true };
  } catch (error: any) {
    log.debug('[runPullRequestAction] failed', { action: action.type, code: error?.code, number });
    return {
      error: (error?.stderr as string)?.trim() || error?.message || 'unknown error',
      success: false,
    };
  }
};