# HG changeset patch
# User Anton Shestakov <av6@dwimlabs.net>
# Date 1620490255 -28800
#      Sun May 09 00:10:55 2021 +0800
# Branch stable
# Node ID 1a8e86053adb67cbf873f279820a09554ad442e9
# Parent  13c406d9912cb10e2cfb23d7e094941b4a2484e2
topic: don't lose any file changes when changing topic of a merge commit

This file-related logic is taken directly from cmdutil.amend().

diff --git a/CHANGELOG b/CHANGELOG
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -6,6 +6,10 @@
 
   * next: remove duplicated targets when updating from an unstable changeset
 
+topic (0.22.2)
+
+  * topic: don't lose any file changes when changing topic of a merge commit
+
 10.3.1 -- 2021-04-25
 --------------------
 
diff --git a/hgext3rd/topic/__init__.py b/hgext3rd/topic/__init__.py
--- a/hgext3rd/topic/__init__.py
+++ b/hgext3rd/topic/__init__.py
@@ -1059,6 +1059,14 @@
     for r in revs:
         c = repo[r]
 
+        if len(c.parents()) > 1:
+            # ctx.files() isn't reliable for merges, so fall back to the
+            # slower repo.status() method
+            st = c.p1().status(c)
+            files = set(st.modified) | set(st.added) | set(st.removed)
+        else:
+            files = set(c.files())
+
         def filectxfn(repo, ctx, path):
             try:
                 return c[path]
@@ -1097,7 +1105,7 @@
         mc = context.memctx(repo,
                             (p1, p2),
                             c.description(),
-                            c.files(),
+                            files,
                             filectxfn,
                             user=c.user(),
                             date=c.date(),
diff --git a/tests/test-amend-merge.t b/tests/test-amend-merge.t
--- a/tests/test-amend-merge.t
+++ b/tests/test-amend-merge.t
@@ -70,3 +70,29 @@
   +++ b/apple	Thu Jan 01 00:00:00 1970 +0000
   @@ -0,0 +1,1 @@
   +apple
+
+topics
+
+  $ hg topics -r . foo
+  switching to topic foo
+  changed topic on 1 changesets to "foo"
+  $ hg diff -r 'p1(.)' -r '.'
+  diff -r 88a060ab6523 -r 52150b9639f7 banana
+  --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+  +++ b/banana	Thu Jan 01 00:00:00 1970 +0000
+  @@ -0,0 +1,1 @@
+  +banana
+  $ hg diff -r 'p2(.)' -r '.'
+  diff -r d8c7baf0ca58 -r 52150b9639f7 apple
+  --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+  +++ b/apple	Thu Jan 01 00:00:00 1970 +0000
+  @@ -0,0 +1,1 @@
+  +apple
+
+  $ hg files
+  apple
+  banana
+  root
+  $ hg cat apple banana
+  apple
+  banana