← 中文资源

简体中文版本

求两个分支的合并基点

根据提交的父链接与两个分支头,返回合并基点以及各分支独有的提交,让变基计划明晰。

阅读英文原文

任务

从两个头分别遍历祖先集合,找出交集、选出最近的共同祖先;再输出各自不在基点祖先集内的提交。

契约

  • 输入:JSON 对象:{ commits: [{ hash, parents: string[] }], headA, headB }
  • 输出:JSON 对象:{ mergeBase, onlyA: string[], onlyB: string[] }

样例

  1. 输入 {"commits":[{"hash":"a1","parents":["base"]},{"hash":"b1","parents":["base"]},{"hash":"base","parents":[]}],"headA":"a1","headB":"b1"} -> 期望 {"mergeBase":"base","onlyA":["a1"],"onlyB":["b1"]}。两个分支都从 base 分叉出去。
  2. 输入 {"commits":[{"hash":"x1","parents":["x0"]},{"hash":"x0","parents":["base"]},{"hash":"base","parents":[]}],"headA":"x1","headB":"x0"} -> 期望 {"mergeBase":"x0","onlyA":["x1"],"onlyB":[]}。一个头是另一个的祖先,因此该祖先就是合并基点。

参考实现

function solve({ commits, headA, headB }) {
      const parents = new Map(commits.map((c) => [c.hash, c.parents ?? []]));
      const ancestors = (start) => {
        const seen = new Set();
        const queue = [start];
        while (queue.length) {
          const hash = queue.shift();
          if (seen.has(hash)) continue;
          seen.add(hash);
          for (const parent of parents.get(hash) ?? []) queue.push(parent);
        }
        return seen;
      };
      const a = ancestors(headA);
      const b = ancestors(headB);
      const common = [...a].filter((hash) => b.has(hash));
      const isAncestor = (maybe, of) => ancestors(of).has(maybe);
      const mergeBase = common
        .filter((hash) => !common.some((other) => other !== hash && isAncestor(hash, other)))
        .sort((x, y) => x.localeCompare(y))[0] ?? null;
      return {
        mergeBase,
        onlyA: [...a].filter((h) => !b.has(h)).sort(),
        onlyB: [...b].filter((h) => !a.has(h)).sort(),
      };
    }

为什么有效

变基与摘取出错,常常因为把共享祖先当成想当然,而不是算出来的。走一遍提交图能让计划可审计。

两个头都属于各自的祖先集合,因此当某个头是祖先时,它必须作为合并基点出现。