Skip to content

feat(gitGraph): add multi parent merge#7950

Open
WhiteFox0-0 wants to merge 6 commits into
mermaid-js:developfrom
WhiteFox0-0:feature/add-multi-parent-merge
Open

feat(gitGraph): add multi parent merge#7950
WhiteFox0-0 wants to merge 6 commits into
mermaid-js:developfrom
WhiteFox0-0:feature/add-multi-parent-merge

Conversation

@WhiteFox0-0

@WhiteFox0-0 WhiteFox0-0 commented Jul 7, 2026

Copy link
Copy Markdown

📑 Summary

Added support for octopus (multi-parent) merges in gitGraph. Updated the parser, database to allow multiple branches to merge into a single commit node

Resolves #7462

📏 Design Decisions

Extended the existing gitGraph model to support octopus (multi-parent) merges by allowing multiple parent relationships for a single commit. Which can be use like:

merge [branch_1], [branch_2] ...
This matches the git octopus merge

Example

gitGraph TB:
    commit
    branch feature1
    checkout feature1
    commit
    checkout main
    branch feature2
    checkout feature2
    commit
    checkout main
    merge feature1, feature2
Screenshot 2026-07-07 at 7 09 33 PM

gitGraph
    commit id: "init"
    commit id: "setup"
    branch feature/1
    commit id: "feat1-impl"
    checkout main
    branch feature/2
    commit id: "feat2-impl"
    checkout main
    merge feature/1, feature/2 id: "merge" type: HIGHLIGHT
Screenshot 2026-07-07 at 7 11 54 PM

📋 Tasks

Make sure you

  • 📖 have read the contribution guidelines
  • 💻 have added necessary unit/e2e tests.
  • 📓 have added documentation. Make sure MERMAID_RELEASE_VERSION is used for all new features.
  • 🦋 If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running pnpm changeset and following the prompts. Changesets that add features should be minor and those that fix bugs should be patch. Please prefix changeset messages with feat:, fix:, or chore:.

Added octopus (multi-parent) merge support to gitGraph, allowing a single merge commit node to accept multiple parent branches via merge feature1, feature2, ... (resolving #7462).

Highlights:

  • Updated the gitGraph grammar and parser to parse merge statements with one-or-more branch references separated by commas.
  • Refactored gitGraph types and AST/DB models to represent merges as branches: string[] (instead of a single branch).
  • Enhanced merge logic to resolve each provided branch head, validate multi-branch merge rules (including rejecting self-merges, invalid/empty targets, duplicate branch inputs, and conflicting custom commit IDs), and generate a multi-parent commit with parents: [currentHead, ...verifiedBranches].
  • Improved merge commit message formatting for single vs multi-branch merges.
  • Added/updated unit tests covering multi-branch merges (including commit IDs, parent ordering, and head/branch mappings) and the duplicate-branch error case.
  • Updated demos/git.html with new “Multiple branch merge graph” examples (left-to-right, top-to-bottom, bottom-to-top).
  • Added changesets marking mermaid and @mermaid-js/parser minor version bumps and documenting the new feature.

@changeset-bot

changeset-bot Bot commented Jul 7, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: dc89e47

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
mermaid Minor
@mermaid-js/parser Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@netlify

netlify Bot commented Jul 7, 2026

Copy link
Copy Markdown

Deploy Preview for mermaid-js ready!

Name Link
🔨 Latest commit dc89e47
🔍 Latest deploy log https://app.netlify.com/projects/mermaid-js/deploys/6a566fc358c0af0008df54b7
😎 Deploy Preview https://deploy-preview-7950--mermaid-js.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions github-actions Bot added the Type: Enhancement New feature or request label Jul 7, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 7, 2026

Copy link
Copy Markdown

Open in StackBlitz

@mermaid-js/examples

npm i https://pkg.pr.new/@mermaid-js/examples@7950

mermaid

npm i https://pkg.pr.new/mermaid@7950

@mermaid-js/layout-elk

npm i https://pkg.pr.new/@mermaid-js/layout-elk@7950

@mermaid-js/layout-tidy-tree

npm i https://pkg.pr.new/@mermaid-js/layout-tidy-tree@7950

@mermaid-js/mermaid-zenuml

npm i https://pkg.pr.new/@mermaid-js/mermaid-zenuml@7950

@mermaid-js/parser

npm i https://pkg.pr.new/@mermaid-js/parser@7950

@mermaid-js/tiny

npm i https://pkg.pr.new/@mermaid-js/tiny@7950

commit: dc89e47

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 92b5dfe6-c7b3-4d74-871b-ef9c34775f06

📥 Commits

Reviewing files that changed from the base of the PR and between 74b15df and 0785055.

📒 Files selected for processing (1)
  • packages/mermaid/src/diagrams/git/gitGraphAst.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/mermaid/src/diagrams/git/gitGraphAst.ts

📝 Walkthrough

Walkthrough

gitGraph merge handling now accepts multiple source branches in one statement. The grammar, types, parser mapping, AST merge logic, tests, demos, and changesets were updated to use branches arrays and validate multi-parent merge behavior.

Changes

Multi-branch merge support

Layer / File(s) Summary
Grammar and type contracts
packages/parser/src/language/gitGraph/gitGraph.langium, packages/mermaid/src/diagrams/git/gitGraphTypes.ts
Merge now parses comma-separated branches, and MergeDB/MergeAst now carry branches: string[].
Parser mapping and parser tests
packages/mermaid/src/diagrams/git/gitGraphParser.ts, packages/parser/tests/gitGraph.test.ts
parseMerge uses merge.branches, and parser tests were updated for array-shaped merge data and multi-branch inputs.
Multi-branch merge commit logic
packages/mermaid/src/diagrams/git/gitGraphAst.ts, packages/mermaid/src/diagrams/git/gitGraph.spec.ts
Merge construction now resolves all target branches, validates duplicate/missing cases, and creates a merge commit with all verified parents; spec coverage was added for multi-branch merges and duplicate branches.
Demo examples and release notes
demos/git.html, .changeset/*.md
The git demo adds multi-branch merge examples and fixes a closing tag, and the changesets record the minor bumps plus the new gitGraph feature note.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant LangiumGrammar as gitGraph.langium
  participant gitGraphParser as gitGraphParser
  participant gitGraphAst as gitGraphAst
  participant Demo as git.html
  LangiumGrammar->>gitGraphParser: parse Merge branches array
  gitGraphParser->>gitGraphAst: mergeDB.branches
  gitGraphAst->>gitGraphAst: validate branches and build parents list
  Demo->>Demo: render multi-branch merge examples
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding multi-parent merge support to gitGraph.
Description check ✅ Passed The description includes a summary, linked issue reference, design decisions, and task checklist, matching the template well.
Linked Issues check ✅ Passed The changes implement multi-branch merge syntax and shared merge-node behavior requested by #7462.
Out of Scope Changes check ✅ Passed The demo updates, tests, parser changes, and changesets all support the gitGraph multi-parent merge feature.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.54%. Comparing base (f0ffb41) to head (dc89e47).

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #7950      +/-   ##
===========================================
+ Coverage    77.46%   77.54%   +0.08%     
===========================================
  Files          564      564              
  Lines        74906    74919      +13     
  Branches     12661    12664       +3     
===========================================
+ Hits         58026    58097      +71     
+ Misses       15881    15823      -58     
  Partials       999      999              
Flag Coverage Δ
e2e 70.75% <20.00%> (+0.22%) ⬆️
unit 74.83% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
packages/mermaid/src/diagrams/git/gitGraphAst.ts 73.79% <100.00%> (+1.28%) ⬆️
...ackages/mermaid/src/diagrams/git/gitGraphParser.ts 98.98% <100.00%> (ø)
packages/mermaid/src/diagrams/git/gitGraphTypes.ts 100.00% <ø> (ø)

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
demos/git.html (1)

202-258: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

New multi-branch merge examples look correct but TB/BT are less thorough than LR.

The LR example demonstrates a 3-way octopus merge (merge feature1, feature2, feature3), while the TB and BT examples only demonstrate a 2-way merge (merge feature1, feature2). Consider extending TB/BT to also cover the 3-branch scenario for consistency and to give users a complete picture of octopus-merge rendering across all diagram orientations.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@demos/git.html` around lines 202 - 258, The multi-branch merge examples are
inconsistent because the LR gitGraph demonstrates a 3-branch octopus merge while
the TB and BT variants only show 2-branch merges. Update the Mermaid snippets in
the multiple branch merge section so the TB and BT diagrams match the LR example
by including the third feature branch and merging all three branches, keeping
the examples aligned across orientations in the relevant gitGraph blocks.
packages/parser/tests/gitGraph.test.ts (1)

128-132: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Test title doesn't match the syntax under test.

The test is titled "should parse multiple branches separated by single space" but the input merge feature1, feature2 is comma-separated, not space-separated.

✏️ Suggested rename
-  it('should parse multiple branches separated by single space', () => {
+  it('should parse multiple branches separated by a comma', () => {
     const result = parse(`gitGraph\n merge feature1, feature2\n`);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/parser/tests/gitGraph.test.ts` around lines 128 - 132, The test
title in gitGraph.test.ts does not match the syntax being parsed: the Merge
parsing case uses comma-separated branches via parse and Merge.branches, not
single-space separation. Rename the test to describe comma-separated branches so
it accurately reflects the input and expected output.
packages/mermaid/src/diagrams/git/gitGraphAst.ts (1)

230-245: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Custom-id collision check is re-evaluated unnecessarily on every branch iteration.

customId and state.records.commits don't change between iterations, so this check yields the same result each time the loop runs; hoisting it above the for loop would avoid redundant work for merges with many branches.

♻️ Proposed refactor: hoist the customId check out of the loop
   const currentBranchCheck = state.records.branches.get(state.records.currBranch);
   const currentCommit = currentBranchCheck
     ? state.records.commits.get(currentBranchCheck)
     : undefined;
 
+  if (customId && state.records.commits.has(customId)) {
+    const error: any = new Error(
+      'Incorrect usage of "merge". Commit with id:' + customId + ' already exists, use different custom id'
+    );
+    error.hash = {
+      text: `merge ${otherBranches.join(' ')} ${customId} ${overrideType} ${customTags?.join(' ')}`,
+      token: `merge ${otherBranches.join(' ')} ${customId} ${overrideType} ${customTags?.join(' ')}`,
+      expected: [`merge ${otherBranches.join(' ')} ${customId}_UNIQUE ${overrideType} ${customTags?.join(' ')}`],
+    };
+    throw error;
+  }
+
   const verifiedBranches: string[] = [];
   for (const branch of otherBranches) {
     ...
-    if (customId && state.records.commits.has(customId)) {
-      const error: any = new Error(
-        'Incorrect usage of "merge". Commit with id:' +
-          customId +
-          ' already exists, use different custom id'
-      );
-      error.hash = {
-        text: `merge ${otherBranch} ${customId} ${overrideType} ${customTags?.join(' ')}`,
-        token: `merge ${otherBranch} ${customId} ${overrideType} ${customTags?.join(' ')}`,
-        expected: [
-          `merge ${otherBranch} ${customId}_UNIQUE ${overrideType} ${customTags?.join(' ')}`,
-        ],
-      };
-
-      throw error;
-    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/mermaid/src/diagrams/git/gitGraphAst.ts` around lines 230 - 245, The
custom-id collision check in the merge handling logic is being repeated on every
branch iteration even though `customId` and `state.records.commits` are
unchanged. Move the `customId && state.records.commits.has(customId)`
validation, including the `Error` construction and `error.hash` setup, to before
the `for` loop in the merge path so it runs once per merge instead of once per
branch. Use the surrounding merge function in `gitGraphAst` to place the guard
at the earliest point where `customId` is available.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.changeset/tender-adults-see.md:
- Line 6: Fix the user-facing changelog typo in the changeset entry: replace
“muli-parent” with “multi-parent” in the release note text so the summary for
gitGraph is spelled correctly. This is a simple content-only update in the
changeset markdown, with no code changes needed.

In `@packages/mermaid/src/diagrams/git/gitGraphAst.ts`:
- Around line 175-187: The new self-merge guard in gitGraphAst’s merge handling
is redundant and overrides the existing structured error path. Remove the plain
Error check that compares currentCommit.branch to otherBranch, and keep the
state.records.currBranch === otherBranch branch so the merge() failure continues
to emit the structured error with error.hash metadata used by downstream error
handling.

---

Nitpick comments:
In `@demos/git.html`:
- Around line 202-258: The multi-branch merge examples are inconsistent because
the LR gitGraph demonstrates a 3-branch octopus merge while the TB and BT
variants only show 2-branch merges. Update the Mermaid snippets in the multiple
branch merge section so the TB and BT diagrams match the LR example by including
the third feature branch and merging all three branches, keeping the examples
aligned across orientations in the relevant gitGraph blocks.

In `@packages/mermaid/src/diagrams/git/gitGraphAst.ts`:
- Around line 230-245: The custom-id collision check in the merge handling logic
is being repeated on every branch iteration even though `customId` and
`state.records.commits` are unchanged. Move the `customId &&
state.records.commits.has(customId)` validation, including the `Error`
construction and `error.hash` setup, to before the `for` loop in the merge path
so it runs once per merge instead of once per branch. Use the surrounding merge
function in `gitGraphAst` to place the guard at the earliest point where
`customId` is available.

In `@packages/parser/tests/gitGraph.test.ts`:
- Around line 128-132: The test title in gitGraph.test.ts does not match the
syntax being parsed: the Merge parsing case uses comma-separated branches via
parse and Merge.branches, not single-space separation. Rename the test to
describe comma-separated branches so it accurately reflects the input and
expected output.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cb24213c-800f-4fab-b16b-338c805dd48c

📥 Commits

Reviewing files that changed from the base of the PR and between f3dea58 and 6c95e54.

📒 Files selected for processing (8)
  • .changeset/tender-adults-see.md
  • demos/git.html
  • packages/mermaid/src/diagrams/git/gitGraph.spec.ts
  • packages/mermaid/src/diagrams/git/gitGraphAst.ts
  • packages/mermaid/src/diagrams/git/gitGraphParser.ts
  • packages/mermaid/src/diagrams/git/gitGraphTypes.ts
  • packages/parser/src/language/gitGraph/gitGraph.langium
  • packages/parser/tests/gitGraph.test.ts

Comment thread .changeset/tender-adults-see.md Outdated
Comment thread packages/mermaid/src/diagrams/git/gitGraphAst.ts Outdated
@argos-ci

argos-ci Bot commented Jul 7, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Argos notifications ↗︎

Build Status Details Updated (UTC)
default (Inspect) ✅ No changes detected - Jul 14, 2026, 5:40 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Type: Enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gitgraph cannot handle merge conflicts

1 participant