Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Warn that force push deletes remote-only files (GHY-3917) (#76012)

Eric Normand82544e925592
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
index f3863372eec..ba296878344 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
@@ -157,6 +157,8 @@
- clean: whether a 3-way merge would apply with no conflicts
- conflicts: human-readable labels of the entities that conflict (empty when clean)
- summary: counts of remote changes a merge would fold in
+ - force_push_casualties: remote content a force push (rather than a merge) would discard, as
+ `{:deleted [labels] :overwritten [labels]}`
- reason: \"history-rewritten\" when the remote was force-pushed/rebased so no merge base exists
Requires superuser permissions."
@@ -165,12 +167,14 @@
(api/check-superuser)
(api/check-400 (settings/remote-sync-enabled) "Remote sync is not configured.")
(let [branch-name (check-branch-matches-setting! branch)
- {:keys [diverged? clean? conflicts summary reason]} (impl/preview-export-merge branch-name)]
- {:has_changes diverged?
- :clean clean?
- :conflicts conflicts
- :summary summary
- :reason (some-> reason name)}))
+ {:keys [diverged? clean? conflicts summary force-push-casualties reason]}
+ (impl/preview-export-merge branch-name)]
+ {:has_changes diverged?
+ :clean clean?
+ :conflicts conflicts
+ :summary summary
+ :force_push_casualties force-push-casualties
+ :reason (some-> reason name)}))
(api.macros/defendpoint :get "/current-task" :- [:maybe remote-sync.schema/SyncTask]
"Get the current sync task"
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
index 9f46c21d442..ffdfcd65226 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
@@ -1089,12 +1089,14 @@
- `:clean?` - whether a 3-way merge would apply with no conflicts
- `:conflicts` - human-readable labels of the entities that conflict (empty when clean)
- `:summary` - `{:added :updated :removed}` counts of remote changes a merge would fold in
+ - `:force-push-casualties` - `{:deleted :overwritten}` labels of remote content a force push would discard
- `:reason` - `:history-rewritten` when the remote was force-pushed/rebased so no merge base exists
`branch` is the branch to preview against — the caller is responsible for having validated it against
the `remote-sync-branch` setting."
[branch]
- (let [no-changes {:diverged? false :clean? true :conflicts [] :summary {:added 0 :updated 0 :removed 0}}
+ (let [no-changes {:diverged? false :clean? true :conflicts [] :summary {:added 0 :updated 0 :removed 0}
+ :force-push-casualties {:deleted [] :overwritten []}}
source (source/source-from-settings branch)
snapshot (source.p/snapshot source)
remote-version (source.p/version snapshot)
@@ -1106,8 +1108,14 @@
(if-let [models (spec/extract-entities-for-export)]
(assoc (source/preview-merge models snapshot base-snapshot nil) :diverged? true)
(assoc no-changes :diverged? true)))
+ ;; No merge base — the remote history was rewritten. A merge is impossible, but a force push is
+ ;; still offered, so surface what it would discard (every remote entity not identical to ours).
{:diverged? true :clean? false :reason :history-rewritten
- :conflicts [] :summary {:added 0 :updated 0 :removed 0}}))))
+ :conflicts [] :summary {:added 0 :updated 0 :removed 0}
+ :force-push-casualties (serdes/with-cache
+ (if-let [models (spec/extract-entities-for-export)]
+ (source/force-push-casualties-no-base models snapshot)
+ {:deleted [] :overwritten []}))}))))
(defn create-branch!
"Creates a new remote branch from `base-branch` and switches `remote-sync-branch`
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/merge.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/merge.clj
index 81a68ed2443..1966ab61bd1 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/merge.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/merge.clj
@@ -147,3 +147,29 @@
(update acc :conflicts conj {:key k :base bv :ours ov :theirs tv}))))
{:merged [] :conflicts [] :summary {:added 0 :updated 0 :removed 0}}
all-keys)))
+
+(defn force-push-casualties
+ "Remote content that a force push would discard. A force export rewrites every managed file from `ours`,
+ so any change the remote made since the merge `base` is lost. Returns `{:deleted :overwritten}`, each a
+ sequence of human-readable labels (see [[conflict-label]]):
+ - `:deleted` - entities present on the remote (`theirs`) but absent from `ours` (removed entirely)
+ - `:overwritten` - entities present in both whose remote content, changed since `base`, differs from
+ what `ours` would write (the remote edit is replaced)
+
+ Entities the remote hasn't touched since `base`, or whose remote content already equals `ours`, are not
+ casualties — that's a routine push, not a loss. `base`, `ours`, `theirs` are sequences of
+ `{:path :content}` specs."
+ [base ours theirs]
+ (let [b (index-by-key base)
+ o (index-by-key ours)]
+ (reduce-kv
+ (fn [acc k tv]
+ (let [ov (get o k)
+ bv (get b k)]
+ (cond
+ ;; remote unchanged since base, or already matches ours -> nothing lost
+ (or (same? tv bv) (same? tv ov)) acc
+ (nil? ov) (update acc :deleted conj (conflict-label {:key k :theirs tv}))
+ :else (update acc :overwritten conj (conflict-label {:key k :ours ov :theirs tv})))))
+ {:deleted [] :overwritten []}
+ (index-by-key theirs))))
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/schema.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/schema.clj
index de508a676db..bde97707984 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/schema.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/schema.clj
@@ -109,6 +109,13 @@
[:updated :int]
[:removed :int]])
+(def ForcePushCasualties
+ "Remote content a force push would discard, keyed by how: entities removed entirely (`:deleted`) or
+ whose remote-side edits would be replaced (`:overwritten`). Each is human-readable entity labels."
+ [:map
+ [:deleted [:sequential :string]]
+ [:overwritten [:sequential :string]]])
+
(def ExportPreflightResponse
"Schema for GET /export-preflight response."
[:map
@@ -116,6 +123,7 @@
[:clean :boolean]
[:conflicts [:sequential :string]]
[:summary MergeSummary]
+ [:force_push_casualties ForcePushCasualties]
[:reason [:maybe :string]]])
(def SettingsUpdateResponse
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj
index d570a0fbc18..2a03d2d3a9c 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj
@@ -122,7 +122,9 @@
(defn compute-merge
"Runs the entity-identity 3-way merge of local state against the remote tip, without writing. Returns
- the raw merge result `{:merged :conflicts :summary}` from [[remote-sync.merge/three-way-merge]]:
+ the raw merge result `{:merged :conflicts :summary}` from [[remote-sync.merge/three-way-merge]], plus
+ `:force-push-casualties` (remote content a force push would discard; see
+ [[remote-sync.merge/force-push-casualties]]):
- `base-snapshot` - the last successfully synced state (the merge base)
- `stream` - the local state to serialize (ours)
- `snapshot` - the current remote tip (theirs)
@@ -133,7 +135,8 @@
(let [ours (serialize-specs stream task-id)
base (snapshot->specs base-snapshot)
theirs (snapshot->specs snapshot)]
- (remote-sync.merge/three-way-merge base ours theirs)))
+ (assoc (remote-sync.merge/three-way-merge base ours theirs)
+ :force-push-casualties (remote-sync.merge/force-push-casualties base ours theirs))))
(defn specs->snapshot
"Builds an in-memory read-only SourceSnapshot backed by `specs` (a seq of `{:path :content}`), so merged
@@ -149,13 +152,27 @@
(defn preview-merge
"Dry-run of [[merge-and-store!]]: computes the 3-way merge without writing anything. Returns
- `{:clean? bool :conflicts [labels] :summary {:added :updated :removed}}`. Pass nil for `task-id` to
- skip progress reporting."
+ `{:clean? bool :conflicts [labels] :summary {:added :updated :removed}
+ :force-push-casualties {:deleted [labels] :overwritten [labels]}}`. The casualties are the remote
+ content a force push (rather than a merge) would discard. Pass nil for `task-id` to skip progress
+ reporting."
[stream snapshot base-snapshot task-id]
- (let [{:keys [conflicts summary]} (compute-merge stream snapshot base-snapshot task-id)]
- {:clean? (empty? conflicts)
- :conflicts (mapv remote-sync.merge/conflict-label conflicts)
- :summary summary}))
+ (let [{:keys [conflicts summary force-push-casualties]}
+ (compute-merge stream snapshot base-snapshot task-id)]
+ {:clean? (empty? conflicts)
+ :conflicts (mapv remote-sync.merge/conflict-label conflicts)
+ :summary summary
+ :force-push-casualties force-push-casualties}))
+
+(defn force-push-casualties-no-base
+ "Casualties of a force push when there is no merge base — the remote history was rewritten
+ (force-pushed/rebased upstream), so the prior sync point is gone. Without a base we can't tell what
+ changed since divergence, so every remote entity that isn't identical to what we'd write counts: remote
+ content is foreign and gets discarded wholesale. Returns `{:deleted [labels] :overwritten [labels]}`
+ (see [[remote-sync.merge/force-push-casualties]]). `stream` is the local state to serialize (ours),
+ `snapshot` the rewritten remote tip (theirs)."
+ [stream snapshot]
+ (remote-sync.merge/force-push-casualties [] (serialize-specs stream nil) (snapshot->specs snapshot)))
(defn merge-and-store!
"Like [[store!]], but reconciles the freshly serialized local state against a remote branch that has
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj
index 5820a7c0ca4..ca32b5cbaaa 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj
@@ -156,10 +156,15 @@
Takes a source map containing a :git Git instance and :commit-ish (the ref to resolve). Can optionally take a
second commit-ish argument which overrides the :commit-ish from the source map.
- Returns the full commit SHA string, or nil if the commit-ish cannot be resolved."
+ Returns the full commit SHA string, or nil if the commit-ish cannot be resolved — including a full SHA
+ whose object is absent from the local clone (e.g. a base commit orphaned by an upstream force-push or
+ rebase). JGit parses a complete SHA into an ObjectId without checking the object exists, so the
+ existence check is what makes orphaned bases resolve to nil rather than blowing up on a later read."
[{:keys [^Git git]} ^String commit-ish]
- (when-let [ref (.resolve (.getRepository git) commit-ish)]
- (.name ref)))
+ (let [repo (.getRepository git)]
+ (when-let [object-id (.resolve repo commit-ish)]
+ (when (.has (.getObjectDatabase repo) object-id)
+ (.name object-id)))))
(defn log
"Retrieves the commit history log for a branch.
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
index 80c3edd88b9..ee7ed3b801a 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj
@@ -1815,7 +1815,8 @@ serdes/meta:
(testing "preview reports no changes when the remote has not advanced"
(with-redefs [remote-sync.task/last-version (constantly "remote-R") ; == snapshot version
source/source-from-settings (constantly (export-test-source))]
- (is (= {:diverged? false :clean? true :conflicts [] :summary {:added 0 :updated 0 :removed 0}}
+ (is (= {:diverged? false :clean? true :conflicts [] :summary {:added 0 :updated 0 :removed 0}
+ :force-push-casualties {:deleted [] :overwritten []}}
(impl/preview-export-merge "main"))))))
(deftest preview-export-merge-clean-test
@@ -1850,13 +1851,17 @@ serdes/meta:
(default-branch [_] "main")
(snapshot [_] (export-test-snapshot "remote-R"))
(snapshot-at [_ _] nil))]
- (with-redefs [remote-sync.task/last-version (constantly "gone-base")
- source/source-from-settings (constantly no-base-source)
- spec/extract-entities-for-export (constantly [{:dummy true}])]
+ (with-redefs [remote-sync.task/last-version (constantly "gone-base")
+ source/source-from-settings (constantly no-base-source)
+ spec/extract-entities-for-export (constantly [{:dummy true}])
+ source/force-push-casualties-no-base (fn [_ _] {:deleted ["Audit Logs"] :overwritten []})]
(let [result (impl/preview-export-merge "main")]
(is (true? (:diverged? result)))
(is (false? (:clean? result)))
- (is (= :history-rewritten (:reason result))))))))
+ (is (= :history-rewritten (:reason result)))
+ (testing "force-push casualties are still computed without a merge base"
+ (is (= {:deleted ["Audit Logs"] :overwritten []}
+ (:force-push-casualties result)))))))))
;;; ------------------------------------- local-only pull merge tests -------------------------------------
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/merge_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/merge_test.clj
index f49858b8052..464eea15167 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/merge_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/merge_test.clj
@@ -127,3 +127,62 @@
{:key [::remote-sync.merge/by-path "collections/x.yaml"]
:ours {:path "collections/x.yaml" :content "not-an-entity"}
:theirs {:path "collections/x.yaml" :content "also-not"}})))))
+
+(deftest ^:parallel force-push-casualties-deleted-test
+ (testing "GHY-3917: a force push reports remote content it would discard"
+ (testing "remote-only entity (added on remote, absent locally) -> deleted"
+ (is (= {:deleted ["d (collections/d.yaml)"] :overwritten []}
+ (remote-sync.merge/force-push-casualties
+ [(card "A" "a")] ; base
+ [(card "A" "a")] ; ours: nothing for D
+ [(card "A" "a") (card "D" "d")])))) ; theirs added D
+ (testing "entity dropped locally but edited on the remote -> deleted (the remote edit is lost)"
+ (is (= {:deleted ["b (collections/b.yaml)"] :overwritten []}
+ (remote-sync.merge/force-push-casualties
+ [(card "A" "a") (card "B" "b")]
+ [(card "A" "a")] ; ours dropped B
+ [(card "A" "a") (card "B" "b" "y: 2\n")])))))) ; theirs edited B
+
+(deftest ^:parallel force-push-casualties-overwritten-test
+ (testing "GHY-3917: an entity edited on the remote and locally -> overwritten (remote edit replaced)"
+ (is (= {:deleted [] :overwritten ["a (collections/a.yaml)"]}
+ (remote-sync.merge/force-push-casualties
+ [(card "A" "a")]
+ [(card "A" "a" "x: ours\n")]
+ [(card "A" "a" "x: theirs\n")])))))
+
+(deftest ^:parallel force-push-casualties-routine-push-not-a-casualty-test
+ (testing "GHY-3917: a routine push (local edit, remote untouched since base) is not a casualty"
+ (is (= {:deleted [] :overwritten []}
+ (remote-sync.merge/force-push-casualties
+ [(card "A" "a")]
+ [(card "A" "a" "x: 1\n")] ; ours edited A
+ [(card "A" "a")])))) ; theirs unchanged
+ (testing "GHY-3917: remote and local converged on the same content -> nothing lost"
+ (is (= {:deleted [] :overwritten []}
+ (remote-sync.merge/force-push-casualties
+ [(card "A" "a")]
+ [(card "A" "a" "x: 1\n")]
+ [(card "A" "a" "x: 1\n")]))))
+ (testing "GHY-3917: a locally-added entity is not a casualty (it's not on the remote)"
+ (is (= {:deleted [] :overwritten []}
+ (remote-sync.merge/force-push-casualties
+ [(card "A" "a")]
+ [(card "A" "a") (card "C" "c")] ; ours adds C
+ [(card "A" "a")])))))
+
+(deftest ^:parallel force-push-casualties-no-base-test
+ (testing "GHY-3917: with no merge base (history rewritten), every remote entity not identical to ours is a casualty"
+ (testing "remote-only -> deleted; present-but-different -> overwritten; identical -> neither"
+ (is (= {:deleted ["b (collections/b.yaml)"]
+ :overwritten ["a (collections/a.yaml)"]}
+ (remote-sync.merge/force-push-casualties
+ [] ; no base
+ [(card "A" "a" "x: ours\n") (card "C" "c")] ; ours: edits A, has C (not on remote)
+ [(card "A" "a" "x: theirs\n") (card "B" "b")])))) ; theirs: different A, remote-only B
+ (testing "an entity identical on both sides is not a casualty even without a base"
+ (is (= {:deleted [] :overwritten []}
+ (remote-sync.merge/force-push-casualties
+ []
+ [(card "A" "a")]
+ [(card "A" "a")]))))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj
index e050062bf14..d4054d6057c 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj
@@ -151,6 +151,22 @@
master-snapshot (source.p/snapshot master)]
(is (= (git/commit-sha master "master") (:version master-snapshot))))))
+(deftest commit-sha-missing-object-is-nil-test
+ (testing "GHY-3917: a full SHA whose object isn't in the clone resolves to nil, not a phantom id"
+ (mt/with-temp-dir [remote-dir nil]
+ (let [[master _remote] (init-source! "master" remote-dir
+ :files {"master.txt" "File in master"})
+ ;; JGit parses any complete 40-hex string into an ObjectId without a presence check; the
+ ;; existence guard is what turns a base commit orphaned by an upstream force-push/rebase into
+ ;; nil here instead of a later MissingObjectException when its tree is read.
+ absent-sha "0000000000000000000000000000000000000000"]
+ (is (some? (git/commit-sha master "master"))
+ "a real ref still resolves")
+ (is (nil? (git/commit-sha master absent-sha))
+ "a syntactically valid but absent full SHA resolves to nil")
+ (is (nil? (source.p/snapshot-at master absent-sha))
+ "snapshot-at returns nil for the orphaned base, so callers take the history-rewritten path")))))
+
(deftest list-files
(mt/with-temp-dir [remote-dir nil]
(let [[master remote] (init-source! "master" remote-dir
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx
index 4c9ebad9100..2d7db588661 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx
@@ -401,6 +401,8 @@ export const GitSyncControls = () => {
variant={conflictVariant}
canMerge={conflictPreflight?.clean}
conflicts={conflictPreflight?.conflicts}
+ forcePushCasualties={conflictPreflight?.force_push_casualties}
+ historyRewritten={conflictPreflight?.reason === "history-rewritten"}
/>
)}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/ForcePushWarning.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/ForcePushWarning.tsx
new file mode 100644
index 00000000000..3d7c4162404
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/ForcePushWarning.tsx
@@ -0,0 +1,127 @@
+import { useState } from "react";
+import { c, msgid, ngettext, t } from "ttag";
+
+import {
+ Anchor,
+ Box,
+ Collapse,
+ Group,
+ Icon,
+ List,
+ Stack,
+ Text,
+} from "metabase/ui";
+import type { ForcePushCasualties } from "metabase-types/api";
+
+interface ForcePushWarningProps {
+ casualties: ForcePushCasualties;
+ branch: string;
+ /**
+ * The remote's history was rewritten (force-pushed/rebased upstream) so there's no common base. The
+ * whole remote is foreign content that a force push replaces wholesale, so we add an explanation.
+ */
+ historyRewritten?: boolean;
+}
+
+/**
+ * Spells out what a force push to `branch` would discard: files that exist only on the remote are
+ * permanently deleted, and remote-side edits are overwritten by this instance's version. Shows the
+ * counts and an expandable list of the affected entities. Renders nothing when there's nothing to lose.
+ */
+export const ForcePushWarning = ({
+ casualties,
+ branch,
+ historyRewritten,
+}: ForcePushWarningProps) => {
+ const { deleted, overwritten } = casualties;
+ const [expanded, setExpanded] = useState(false);
+
+ const total = deleted.length + overwritten.length;
+ if (total === 0) {
+ return null;
+ }
+
+ const deletedText =
+ deleted.length > 0
+ ? ngettext(
+ msgid`${deleted.length} file on ${branch} that isn’t here will be permanently deleted`,
+ `${deleted.length} files on ${branch} that aren’t here will be permanently deleted`,
+ deleted.length,
+ )
+ : null;
+ const overwrittenText =
+ overwritten.length > 0
+ ? ngettext(
+ msgid`${overwritten.length} file’s changes on ${branch} will be discarded and overwritten`,
+ `${overwritten.length} files’ changes on ${branch} will be discarded and overwritten`,
+ overwritten.length,
+ )
+ : null;
+
+ return (
+ <Box
+ mt="md"
+ p="md"
+ bg="background-error-secondary"
+ style={{ borderRadius: "var(--mantine-radius-md)" }}
+ >
+ <Group gap="sm" align="flex-start" wrap="nowrap">
+ <Icon name="warning" c="error" mt="2px" />
+ <Box>
+ {historyRewritten && (
+ <Text fw="bold" mb="xs">
+ {t`The remote branch’s history was rewritten, so there’s no common base. Force pushing replaces it entirely with this instance’s content:`}
+ </Text>
+ )}
+ <Stack gap="xs">
+ {deletedText && (
+ <Text fw="bold" c="error">
+ {deletedText}
+ </Text>
+ )}
+ {overwrittenText && <Text fw="bold">{overwrittenText}</Text>}
+ </Stack>
+ <Anchor
+ component="button"
+ type="button"
+ size="sm"
+ mt="xs"
+ onClick={() => setExpanded((value) => !value)}
+ >
+ {expanded ? t`Hide files` : t`Show files`}
+ </Anchor>
+ <Collapse in={expanded}>
+ <Stack gap="sm" mt="sm">
+ {deleted.length > 0 && (
+ <Box>
+ <Text size="sm" fw="bold" mb="xs">
+ {c("Header for a list of files that will be deleted")
+ .t`Will be deleted`}
+ </Text>
+ <List spacing="xs" size="sm" withPadding>
+ {deleted.map((label) => (
+ <List.Item key={label}>{label}</List.Item>
+ ))}
+ </List>
+ </Box>
+ )}
+ {overwritten.length > 0 && (
+ <Box>
+ <Text size="sm" fw="bold" mb="xs">
+ {c("Header for a list of files that will be overwritten")
+ .t`Will be overwritten`}
+ </Text>
+ <List spacing="xs" size="sm" withPadding>
+ {overwritten.map((label) => (
+ <List.Item key={label}>{label}</List.Item>
+ ))}
+ </List>
+ </Box>
+ )}
+ </Stack>
+ </Collapse>
+ </Box>
+ </Group>
+ </Box>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/ForcePushWarning.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/ForcePushWarning.unit.spec.tsx
new file mode 100644
index 00000000000..69e29954ed1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/ForcePushWarning.unit.spec.tsx
@@ -0,0 +1,87 @@
+import userEvent from "@testing-library/user-event";
+
+import { render, screen } from "__support__/ui";
+import type { ForcePushCasualties } from "metabase-types/api";
+
+import { ForcePushWarning } from "./ForcePushWarning";
+
+const setup = (
+ casualties: ForcePushCasualties,
+ { branch = "main", historyRewritten = false } = {},
+) => {
+ render(
+ <ForcePushWarning
+ casualties={casualties}
+ branch={branch}
+ historyRewritten={historyRewritten}
+ />,
+ );
+};
+
+describe("ForcePushWarning", () => {
+ it("renders nothing when there is nothing to lose", () => {
+ setup({ deleted: [], overwritten: [] });
+ expect(screen.queryByText("Show files")).not.toBeInTheDocument();
+ expect(screen.queryByText(/permanently deleted/)).not.toBeInTheDocument();
+ });
+
+ it("summarizes deleted files with the branch name", () => {
+ setup({ deleted: ["Card A (collections/a.yaml)"], overwritten: [] });
+ expect(
+ screen.getByText(/1 file on main.*permanently deleted/),
+ ).toBeInTheDocument();
+ });
+
+ it("pluralizes the deleted-file count", () => {
+ setup({
+ deleted: ["Card A (collections/a.yaml)", "Card B (collections/b.yaml)"],
+ overwritten: [],
+ });
+ expect(
+ screen.getByText(/2 files on main.*permanently deleted/),
+ ).toBeInTheDocument();
+ });
+
+ it("summarizes overwritten files", () => {
+ setup({ deleted: [], overwritten: ["Card C (collections/c.yaml)"] });
+ expect(
+ screen.getByText(
+ /1 file.s changes on main will be discarded and overwritten/,
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it("explains when the remote history was rewritten", () => {
+ setup(
+ { deleted: ["Card A (collections/a.yaml)"], overwritten: [] },
+ { historyRewritten: true },
+ );
+ expect(screen.getByText(/history was rewritten/)).toBeInTheDocument();
+ });
+
+ it("omits the rewritten-history note for a normal divergence", () => {
+ setup({ deleted: ["Card A (collections/a.yaml)"], overwritten: [] });
+ expect(screen.queryByText(/history was rewritten/)).not.toBeInTheDocument();
+ });
+
+ it("toggles the file list open and closed", async () => {
+ setup({
+ deleted: ["Card A (collections/a.yaml)"],
+ overwritten: ["Card C (collections/c.yaml)"],
+ });
+
+ expect(screen.getByText("Show files")).toBeInTheDocument();
+ expect(screen.queryByText("Hide files")).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByText("Show files"));
+
+ expect(screen.getByText("Hide files")).toBeInTheDocument();
+ expect(screen.getByText("Will be deleted")).toBeInTheDocument();
+ expect(screen.getByText("Will be overwritten")).toBeInTheDocument();
+ expect(screen.getByText("Card A (collections/a.yaml)")).toBeInTheDocument();
+ expect(screen.getByText("Card C (collections/c.yaml)")).toBeInTheDocument();
+
+ await userEvent.click(screen.getByText("Hide files"));
+ expect(screen.getByText("Show files")).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.tsx
index 380bbef3e72..5e96d1f9d7a 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.tsx
@@ -21,6 +21,13 @@ interface OutOfSyncOption {
label: string;
}
+/**
+ * Options that permanently destroy content: force-push wipes remote files that aren't here, discard
+ * throws away local changes. Everything else (merge, push, new branch) keeps all content. Used to split
+ * the choices into a safe and a destructive group.
+ */
+const DESTRUCTIVE_OPTIONS = new Set<OptionValue>(["force-push", "discard"]);
+
export const OutOfSyncOptions = (props: BranchSwitchOptionsProps) => {
const {
currentBranch,
@@ -44,7 +51,7 @@ export const OutOfSyncOptions = (props: BranchSwitchOptionsProps) => {
const forcePushOption: OutOfSyncOption = {
value: "force-push",
label: c("{0} is the current GitHub branch name")
- .t`Force push to ${currentBranch} (this will overwrite the remote branch)`,
+ .t`Force push to ${currentBranch}, discarding and overwriting everything (can’t be undone)`,
};
// Push merges and pushes the result; pull merges into local only (the push happens later).
const mergeOption: OutOfSyncOption = {
@@ -80,6 +87,13 @@ export const OutOfSyncOptions = (props: BranchSwitchOptionsProps) => {
}
}, [currentBranch, isRemoteSyncReadOnly, variant, canMerge]);
+ const safeOptions = options.filter(
+ (option) => !DESTRUCTIVE_OPTIONS.has(option.value),
+ );
+ const destructiveOptions = options.filter((option) =>
+ DESTRUCTIVE_OPTIONS.has(option.value),
+ );
+
return (
<Box mt="xl">
<Text fw="bold" mb="sm" pb="xs">{t`Choose how to proceed:`}</Text>
@@ -87,17 +101,48 @@ export const OutOfSyncOptions = (props: BranchSwitchOptionsProps) => {
onChange={(value) => handleOptionChange(value as OptionValue)}
value={optionValue}
>
- <Stack gap="sm">
- {options.map((option) => (
- <Radio
- key={option.value}
- value={option.value}
- label={option.label}
- pb="xs"
+ <Stack gap="lg">
+ {safeOptions.length > 0 && (
+ <OptionGroup title={t`Keep all changes`} options={safeOptions} />
+ )}
+ {destructiveOptions.length > 0 && (
+ <OptionGroup
+ title={t`Permanently lose changes (can’t be undone)`}
+ destructive
+ options={destructiveOptions}
/>
- ))}
+ )}
</Stack>
</Radio.Group>
</Box>
);
};
+
+interface OptionGroupProps {
+ title: string;
+ options: OutOfSyncOption[];
+ destructive?: boolean;
+}
+
+const OptionGroup = ({ title, options, destructive }: OptionGroupProps) => (
+ <Box>
+ <Text
+ size="sm"
+ fw="bold"
+ c={destructive ? "error" : "text-secondary"}
+ mb="sm"
+ >
+ {title}
+ </Text>
+ <Stack gap="sm">
+ {options.map((option) => (
+ <Radio
+ key={option.value}
+ value={option.value}
+ label={option.label}
+ pb="xs"
+ />
+ ))}
+ </Stack>
+ </Box>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.unit.spec.tsx
index ff38694094d..fbd3b713d84 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.unit.spec.tsx
@@ -35,7 +35,7 @@ describe("OutOfSyncOptions", () => {
).toBeInTheDocument();
expect(
screen.getByLabelText(
- /Force push to main \(this will overwrite the remote branch\)/,
+ /Force push to main, discarding and overwriting everything/,
),
).toBeInTheDocument();
});
@@ -71,7 +71,7 @@ describe("OutOfSyncOptions", () => {
expect(screen.getAllByRole("radio")).toHaveLength(3);
expect(
screen.getByLabelText(
- /Force push to main \(this will overwrite the remote branch\)/,
+ /Force push to main, discarding and overwriting everything/,
),
).toBeInTheDocument();
expect(
@@ -129,4 +129,18 @@ describe("OutOfSyncOptions", () => {
).toBeInTheDocument();
});
});
+
+ describe("safe vs destructive grouping", () => {
+ it("splits options into a safe and a destructive group", () => {
+ setup({ variant: "push" });
+ expect(screen.getByText("Keep all changes")).toBeInTheDocument();
+ expect(screen.getByText(/Permanently lose changes/)).toBeInTheDocument();
+ });
+
+ it("shows only the destructive group when every option is destructive", () => {
+ setup({ variant: "pull", isRemoteSyncReadOnly: true });
+ expect(screen.getByText(/Permanently lose changes/)).toBeInTheDocument();
+ expect(screen.queryByText("Keep all changes")).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/SyncConflictModal.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/SyncConflictModal.tsx
index 6612db533c5..f21f08249d5 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/SyncConflictModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/SyncConflictModal.tsx
@@ -18,6 +18,7 @@ import {
} from "metabase-enterprise/remote_sync/constants";
import { getIsRemoteSyncReadOnly } from "metabase-enterprise/remote_sync/selectors";
import type {
+ ForcePushCasualties,
RemoteSyncConfigurationSettings,
RemoteSyncConflictVariant,
} from "metabase-types/api";
@@ -27,6 +28,7 @@ import { CommitMessageSection } from "../PushChangesModal/CommitMessageSection";
import { BranchNameInput } from "./BranchNameInput";
import { ConflictingChangesList } from "./ConflictingChangesList";
+import { ForcePushWarning } from "./ForcePushWarning";
import { OutOfSyncOptions } from "./OutOfSyncOptions";
import { SetupConflictInfo } from "./SetupConflictInfo";
import {
@@ -51,11 +53,23 @@ interface UnsyncedWarningModalProps {
canMerge?: boolean;
/** Push variant only: labels of entities that conflict (shown when the merge isn't clean). */
conflicts?: string[];
+ /** Remote content a force push would discard; surfaced when the force-push option is selected. */
+ forcePushCasualties?: ForcePushCasualties;
+ /** Whether the remote history was rewritten (no merge base); adds context to the force-push warning. */
+ historyRewritten?: boolean;
}
export const SyncConflictModal = (props: UnsyncedWarningModalProps) => {
- const { onClose, currentBranch, nextBranch, variant, canMerge, conflicts } =
- props;
+ const {
+ onClose,
+ currentBranch,
+ nextBranch,
+ variant,
+ canMerge,
+ conflicts,
+ forcePushCasualties,
+ historyRewritten,
+ } = props;
const [optionValue, setOptionValue] = useState<OptionValue>();
const [newBranchName, setNewBranchName] = useState<string>("");
// The push variant collects a commit message here, since merge/force/new-branch all push.
@@ -198,6 +212,14 @@ export const SyncConflictModal = (props: UnsyncedWarningModalProps) => {
canMerge={canMerge}
/>
+ {optionValue === "force-push" && forcePushCasualties && (
+ <ForcePushWarning
+ casualties={forcePushCasualties}
+ branch={currentBranch}
+ historyRewritten={historyRewritten}
+ />
+ )}
+
{optionValue === "new-branch" && (
<BranchNameInput
existingBranches={existingBranches}
diff --git a/frontend/src/metabase-types/api/remote-sync.ts b/frontend/src/metabase-types/api/remote-sync.ts
index 2d7b6aec203..dc20c688856 100644
--- a/frontend/src/metabase-types/api/remote-sync.ts
+++ b/frontend/src/metabase-types/api/remote-sync.ts
@@ -73,6 +73,14 @@ export type RemoteSyncMergeSummary = {
removed: number;
};
+/** Remote content a force push would discard (vs. a merge, which folds it in). */
+export type ForcePushCasualties = {
+ /** Entities present on the remote but not in this instance's export — removed entirely. */
+ deleted: string[];
+ /** Entities whose remote-side edits since the last sync would be replaced by this instance's version. */
+ overwritten: string[];
+};
+
/** Dry-run preview of what pushing the current state would do, given the live remote branch. */
export type ExportPreflightResponse = {
/** Whether the remote branch has advanced beyond the last synced version. */
@@ -82,6 +90,8 @@ export type ExportPreflightResponse = {
/** Human-readable labels of the entities that conflict (empty when clean). */
conflicts: string[];
summary: RemoteSyncMergeSummary;
+ /** Remote content a force push would permanently discard. */
+ force_push_casualties: ForcePushCasualties;
/** "history-rewritten" when the remote was force-pushed/rebased so no merge base exists. */
reason: string | null;
};