repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseOverrideForkPointAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseOverrideForkPointAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static org.checkerframework.checker.i18nformatter.qual.I18nConversionCategory.GENERAL;
import com.intellij.openapi.actionSystem.AnActionEvent;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.OverrideForkPointBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.dialogs.OverrideForkPointDialog;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
import com.virtuslab.qual.async.ContinuesInBackground;
public abstract class BaseOverrideForkPointAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
IExpectsKeyGitMacheteRepository,
ISyncToParentStatusDependentAction {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
public @I18nFormat({}) String getActionNameForDisabledDescription() {
return getString("action.GitMachete.BaseOverrideForkPointAction.description-action-name");
}
@Override
public @Untainted @I18nFormat({GENERAL, GENERAL}) String getEnabledDescriptionFormat() {
return getNonHtmlString("action.GitMachete.BaseOverrideForkPointAction.description");
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
syncToParentStatusDependentActionUpdate(anActionEvent);
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val project = getProject(anActionEvent);
val gitRepository = getSelectedGitRepository(anActionEvent);
val branchUnderAction = getNameOfBranchUnderAction(anActionEvent);
val branch = getManagedBranchByName(anActionEvent, branchUnderAction);
if (gitRepository == null || branch == null || branch.isRoot()) {
return;
}
val nonRootBranch = branch.asNonRoot();
val selectedCommit = new OverrideForkPointDialog(project, nonRootBranch).showAndGetSelectedCommit();
new OverrideForkPointBackgroundable(gitRepository, nonRootBranch, getGraphTable(anActionEvent), selectedCommit).queue();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BasePullAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BasePullAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.vavr.collection.List;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus;
import com.virtuslab.gitmachete.frontend.actions.common.Pull;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod(GitMacheteBundle.class)
public abstract class BasePullAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
IExpectsKeyGitMacheteRepository,
ISyncToRemoteStatusDependentAction {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
public @I18nFormat({}) String getActionName() {
return getString("action.GitMachete.BasePullAction.action-name");
}
@Override
public @I18nFormat({}) String getActionNameForDescription() {
return getString("action.GitMachete.BasePullAction.description-action-name");
}
@Override
public List<SyncToRemoteStatus> getEligibleStatuses() {
return List.of(
SyncToRemoteStatus.BehindRemote,
SyncToRemoteStatus.InSyncToRemote);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
syncToRemoteStatusDependentActionUpdate(anActionEvent);
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
log().debug("Performing");
val gitRepository = getSelectedGitRepository(anActionEvent);
val localBranchName = getNameOfBranchUnderAction(anActionEvent);
val gitMacheteRepositorySnapshot = getGitMacheteRepositorySnapshot(anActionEvent);
if (localBranchName != null && gitRepository != null && gitMacheteRepositorySnapshot != null) {
val localBranch = gitMacheteRepositorySnapshot.getManagedBranchByName(localBranchName);
if (localBranch == null) {
// This is generally NOT expected, the action should never be triggered
// for an unmanaged branch in the first place.
log().warn("Branch '${localBranchName}' not found or not managed by Git Machete");
return;
}
val remoteBranch = localBranch.getRemoteTrackingBranch();
if (remoteBranch == null) {
// This is generally NOT expected, the action should never be triggered
// for an untracked branch in the first place (see `getEligibleRelations`)
log().warn("Branch '${localBranchName}' does not have a remote tracking branch");
return;
}
new Pull(gitRepository, localBranch, remoteBranch).run();
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseCompareWithParentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseCompareWithParentAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.fmt;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import java.util.Collections;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import git4idea.branch.GitBrancher;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
public abstract class BaseCompareWithParentAction extends BaseGitMacheteRepositoryReadyAction implements IBranchNameProvider {
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isEnabled()) {
return;
}
val branchName = getNameOfBranchUnderAction(anActionEvent);
val gitRepository = getSelectedGitRepository(anActionEvent);
val managedBranch = getManagedBranchByName(anActionEvent, branchName);
if (gitRepository == null || managedBranch == null) {
return;
}
if (managedBranch.isRoot()) {
presentation.setEnabled(false);
presentation.setDescription(
fmt(getNonHtmlString("action.GitMachete.BaseCompareWithParentAction.description.disabled.branch-is-root"),
managedBranch.getName()));
return;
}
val parent = managedBranch.asNonRoot().getParent();
String description = fmt(getNonHtmlString("action.GitMachete.BaseCompareWithParentAction.description.precise"),
parent.getName(),
managedBranch.getName());
presentation.setDescription(description);
}
@Override
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
FileDocumentManager.getInstance().saveAllDocuments();
val project = getProject(anActionEvent);
val branchName = getNameOfBranchUnderAction(anActionEvent);
val gitRepository = getSelectedGitRepository(anActionEvent);
val managedBranch = getManagedBranchByName(anActionEvent, branchName);
if (gitRepository == null || managedBranch == null || managedBranch.isRoot()) {
return;
}
val parent = managedBranch.asNonRoot().getParent();
GitBrancher.getInstance(project).compareAny(parent.getName(), managedBranch.getName(),
Collections.singletonList(gitRepository));
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSyncToParentByRebaseAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSyncToParentByRebaseAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.getQuotedStringOrCurrent;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.util.Arrays;
import com.intellij.dvcs.repo.Repository;
import com.intellij.openapi.actionSystem.AnActionEvent;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.RebaseOnParentBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod({Arrays.class, GitMacheteBundle.class})
public abstract class BaseSyncToParentByRebaseAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
IExpectsKeyGitMacheteRepository {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isEnabledAndVisible()) {
return;
}
val selectedGitRepo = getSelectedGitRepository(anActionEvent);
val state = selectedGitRepo != null ? selectedGitRepo.getState() : null;
val isCalledFromContextMenu = anActionEvent.getPlace().equals(ActionPlaces.CONTEXT_MENU);
if (state == null) {
presentation.setEnabled(false);
presentation.setDescription(
getNonHtmlString("action.GitMachete.BaseSyncToParentByRebaseAction.description.disabled.repository.unknown-state"));
} else if (state != Repository.State.NORMAL
&& !(isCalledFromContextMenu && state == Repository.State.DETACHED)) {
val stateName = switch (state) {
case GRAFTING -> getString(
"action.GitMachete.BaseSyncToParentByRebaseAction.description.repository.state.ongoing.cherry-pick");
case DETACHED -> getString(
"action.GitMachete.BaseSyncToParentByRebaseAction.description.repository.state.detached-head");
case MERGING -> getString(
"action.GitMachete.BaseSyncToParentByRebaseAction.description.repository.state.ongoing.merge");
case REBASING -> getString(
"action.GitMachete.BaseSyncToParentByRebaseAction.description.repository.state.ongoing.rebase");
case REVERTING -> getString(
"action.GitMachete.BaseSyncToParentByRebaseAction.description.repository.state.ongoing.revert");
case NORMAL -> throw new IllegalStateException("Unexpected value: " + state);
};
presentation.setEnabled(false);
presentation.setDescription(
getNonHtmlString("action.GitMachete.BaseSyncToParentByRebaseAction.description.disabled.repository.status")
.fmt(stateName));
} else {
val branchName = getNameOfBranchUnderAction(anActionEvent);
val branch = getManagedBranchByName(anActionEvent, branchName);
if (branch == null) {
presentation.setEnabled(false);
presentation.setDescription(getNonHtmlString("action.GitMachete.description.disabled.undefined.machete-branch")
.fmt("Rebase", getQuotedStringOrCurrent(branchName)));
} else if (branch.isRoot()) {
if (anActionEvent.getPlace().equals(ActionPlaces.TOOLBAR)) {
presentation.setEnabled(false);
presentation.setDescription(
getNonHtmlString("action.GitMachete.BaseSyncToParentByRebaseAction.description.disabled.root-branch")
.fmt(branch.getName()));
} else { //contextmenu
// in case of root branch we do not want to show this option at all
presentation.setEnabledAndVisible(false);
}
} else if (branch.isNonRoot()) {
val nonRootBranch = branch.asNonRoot();
val upstream = nonRootBranch.getParent();
presentation.setDescription(getNonHtmlString("action.GitMachete.BaseSyncToParentByRebaseAction.description")
.fmt(branch.getName(), upstream.getName()));
}
val currentBranchNameIfManaged = getCurrentBranchNameIfManaged(anActionEvent);
val isRebasingCurrent = branch != null && currentBranchNameIfManaged != null
&& currentBranchNameIfManaged.equals(branch.getName());
if (isCalledFromContextMenu && isRebasingCurrent) {
presentation.setText(getString("action.GitMachete.BaseSyncToParentByRebaseAction.text"));
}
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
log().debug("Performing");
val branchName = getNameOfBranchUnderAction(anActionEvent);
val branch = getManagedBranchByName(anActionEvent, branchName);
if (branch != null) {
if (branch.isNonRoot()) {
doRebase(anActionEvent, branch.asNonRoot());
} else {
log().warn("Skipping the action because the branch '${branch.getName()}' is a root branch");
}
}
}
@ContinuesInBackground
private void doRebase(AnActionEvent anActionEvent, INonRootManagedBranchSnapshot branchToRebase) {
val gitRepository = getSelectedGitRepository(anActionEvent);
val state = gitRepository != null ? gitRepository.getState() : null;
val isCalledFromContextMenu = anActionEvent.getPlace().equals(ActionPlaces.CONTEXT_MENU);
val shouldExplicitlyCheckout = isCalledFromContextMenu && Repository.State.DETACHED == state;
if (gitRepository != null) {
new RebaseOnParentBackgroundable(gitRepository, branchToRebase, shouldExplicitlyCheckout).queue();
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/ISyncToParentStatusDependentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/ISyncToParentStatusDependentAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.getQuotedStringOrCurrent;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.fmt;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static org.checkerframework.checker.i18nformatter.qual.I18nConversionCategory.GENERAL;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.vavr.collection.List;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
public interface ISyncToParentStatusDependentAction extends IBranchNameProvider, IExpectsKeyGitMacheteRepository {
@I18nFormat({})
String getActionNameForDisabledDescription();
/**
* @return a format string for description of action in enabled state
* where {@code {1}} corresponds to branch name as returned by {@link #getNameOfBranchUnderAction}
* and {@code {0}} corresponds to name of its parent branch
*/
@Untainted
@I18nFormat({GENERAL, GENERAL})
String getEnabledDescriptionFormat();
/**
* This method provides a list of {@link SyncToParentStatus}s for which the action should be ENABLED.
* Note that this "enability" matches actions in any place (both toolbar and context menu in particular).
* Visibility itself may be switched off (even though the action is enabled).
*
* As we want to avoid an overpopulation of the toolbar we make some actions there INVISIBLE
* but ENABLED (since they still shall be available from {@code Find Action...}).
*
* @return a list of statuses for which the action should be enabled (not necessarily visible)
*/
List<SyncToParentStatus> getEligibleStatuses();
@UIEffect
default void syncToParentStatusDependentActionUpdate(AnActionEvent anActionEvent) {
val presentation = anActionEvent.getPresentation();
if (!presentation.isEnabled()) {
return;
}
val branchName = getNameOfBranchUnderAction(anActionEvent);
val gitMacheteBranchByName = getManagedBranchByName(anActionEvent, branchName);
if (branchName == null || gitMacheteBranchByName == null) {
presentation.setEnabled(false);
presentation.setDescription(
fmt(getNonHtmlString("action.GitMachete.description.disabled.undefined.machete-branch"),
getActionNameForDisabledDescription(), getQuotedStringOrCurrent(branchName)));
return;
} else if (gitMacheteBranchByName.isRoot()) {
if (anActionEvent.getPlace().equals(ActionPlaces.TOOLBAR)) {
presentation.setEnabled(false);
presentation.setDescription(
fmt(getNonHtmlString("action.GitMachete.description.disabled.branch-is-root"),
getActionNameForDisabledDescription()));
} else { // contextmenu
// in case of root branch we do not want to show this option at all
presentation.setEnabledAndVisible(false);
}
return;
}
val gitMacheteNonRootBranch = gitMacheteBranchByName.asNonRoot();
val syncToParentStatus = gitMacheteNonRootBranch.getSyncToParentStatus();
val isStatusEligible = getEligibleStatuses().contains(syncToParentStatus);
if (isStatusEligible) {
val parentName = gitMacheteNonRootBranch.getParent().getName();
val enabledDesc = fmt(getEnabledDescriptionFormat(), parentName, branchName);
presentation.setDescription(enabledDesc);
} else {
presentation.setEnabled(false);
val desc = switch (syncToParentStatus) {
case InSync -> getString(
"action.GitMachete.ISyncToParentStatusDependentAction.description.sync-to-parent-status.in-sync");
case InSyncButForkPointOff -> getString(
"action.GitMachete.ISyncToParentStatusDependentAction.description.sync-to-parent-status.in-sync-but-fork-point-off");
case MergedToParent -> getString(
"action.GitMachete.ISyncToParentStatusDependentAction.description.sync-to-parent-status.merged-to-parent");
case OutOfSync -> getString(
"action.GitMachete.ISyncToParentStatusDependentAction.description.sync-to-parent-status.out-of-sync");
};
presentation.setDescription(
fmt(getNonHtmlString("action.GitMachete.ISyncToParentStatusDependentAction.description.disabled.branch-status"),
getActionNameForDisabledDescription(), desc));
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BasePushAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BasePushAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.AheadOfRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.DivergedFromAndNewerThanRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.DivergedFromAndOlderThanRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.Untracked;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import git4idea.GitLocalBranch;
import git4idea.config.GitSharedSettings;
import git4idea.push.GitPushSource;
import git4idea.repo.GitRepository;
import io.vavr.collection.List;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus;
import com.virtuslab.gitmachete.frontend.actions.dialogs.GitPushDialog;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod(GitMacheteBundle.class)
public abstract class BasePushAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
ISyncToRemoteStatusDependentAction {
@Override
protected boolean isSideEffecting() {
return false;
}
@Override
public @I18nFormat({}) String getActionName() {
return getString("action.GitMachete.BasePushAction.action-name");
}
@Override
public @I18nFormat({}) String getActionNameForDescription() {
return getString("action.GitMachete.BasePushAction.description-action-name");
}
@Override
public List<SyncToRemoteStatus> getEligibleStatuses() {
return List.of(
AheadOfRemote,
DivergedFromAndNewerThanRemote,
DivergedFromAndOlderThanRemote,
Untracked);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
syncToRemoteStatusDependentActionUpdate(anActionEvent);
val branchName = getNameOfBranchUnderAction(anActionEvent);
val managedBranchByName = getManagedBranchByName(anActionEvent, branchName);
val relation = managedBranchByName != null
? managedBranchByName.getRelationToRemote().getSyncToRemoteStatus()
: null;
val project = getProject(anActionEvent);
if (branchName != null && relation != null && isForcePushRequired(relation)) {
if (GitSharedSettings.getInstance(project).isBranchProtected(branchName)) {
val presentation = anActionEvent.getPresentation();
presentation.setDescription(
getNonHtmlString("action.GitMachete.BasePushAction.force-push-disabled-for-protected-branch").fmt(branchName));
presentation.setEnabled(false);
}
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val project = getProject(anActionEvent);
val gitRepository = getSelectedGitRepository(anActionEvent);
val branchName = getNameOfBranchUnderAction(anActionEvent);
val managedBranchByName = getManagedBranchByName(anActionEvent, branchName);
val relation = managedBranchByName != null ? managedBranchByName.getRelationToRemote().getSyncToRemoteStatus() : null;
if (branchName != null && gitRepository != null && relation != null) {
val isForcePushRequired = isForcePushRequired(relation);
doPush(project, gitRepository, branchName, isForcePushRequired);
}
}
private boolean isForcePushRequired(SyncToRemoteStatus syncToRemoteStatus) {
return List.of(DivergedFromAndNewerThanRemote, DivergedFromAndOlderThanRemote).contains(syncToRemoteStatus);
}
@ContinuesInBackground
@UIEffect
private void doPush(Project project,
GitRepository repository,
String branchName,
boolean isForcePushRequired) {
@Nullable GitLocalBranch localBranch = repository.getBranches().findLocalBranch(branchName);
if (localBranch != null) {
new GitPushDialog(project, repository, GitPushSource.create(localBranch), isForcePushRequired).show();
} else {
log().warn("Skipping the action because provided branch ${branchName} was not found in repository");
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/ISyncToRemoteStatusDependentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/ISyncToRemoteStatusDependentAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.getQuotedStringOrCurrent;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.fmt;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static org.checkerframework.checker.i18nformatter.qual.I18nConversionCategory.GENERAL;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.vavr.collection.List;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
public interface ISyncToRemoteStatusDependentAction extends IBranchNameProvider, IExpectsKeyGitMacheteRepository {
@I18nFormat({})
String getActionName();
@I18nFormat({})
default String getActionNameForDescription() {
return getActionName();
}
@I18nFormat({GENERAL, GENERAL})
default @Untainted String getEnabledDescriptionFormat() {
return getNonHtmlString("action.GitMachete.ISyncToRemoteStatusDependentAction.description.enabled");
}
/**
* This method provides a list of {@link SyncToRemoteStatus}es for which the action should be ENABLED.
* Note that this "enability" matches actions in any place (both toolbar and context menu in particular).
* Visibility itself may be switched off (even though the action is enabled).
*
* As we want to avoid an overpopulation of the toolbar we make some actions there INVISIBLE
* but ENABLED (since they still shall be available from {@code Find Action...}).
*
* @return a list of relations for which the action should be enabled (not necessarily visible)
*/
List<SyncToRemoteStatus> getEligibleStatuses();
@UIEffect
default void syncToRemoteStatusDependentActionUpdate(AnActionEvent anActionEvent) {
val presentation = anActionEvent.getPresentation();
if (!presentation.isEnabled()) {
return;
}
val branchName = getNameOfBranchUnderAction(anActionEvent);
val gitMacheteBranch = getManagedBranchByName(anActionEvent, branchName);
if (branchName == null || gitMacheteBranch == null) {
presentation.setEnabled(false);
presentation.setDescription(
fmt(getNonHtmlString("action.GitMachete.description.disabled.undefined.machete-branch"),
getActionNameForDescription(), getQuotedStringOrCurrent(branchName)));
return;
}
val relationToRemote = gitMacheteBranch.getRelationToRemote();
SyncToRemoteStatus status = relationToRemote.getSyncToRemoteStatus();
val isStatusEligible = getEligibleStatuses().contains(status);
if (isStatusEligible) {
// At this point `branchName` must be present, so `.getOrNull()` is here only to satisfy checker framework
val enabledDesc = fmt(getEnabledDescriptionFormat(), getActionNameForDescription(), branchName);
presentation.setDescription(enabledDesc);
} else {
presentation.setEnabled(false);
val desc = switch (status) {
case AheadOfRemote -> getString(
"action.GitMachete.ISyncToRemoteStatusDependentAction.description.sync-to-remote-status.ahead-of-remote");
case BehindRemote -> getString(
"action.GitMachete.ISyncToRemoteStatusDependentAction.description.sync-to-remote-status.behind-remote");
case DivergedFromAndNewerThanRemote -> getString(
"action.GitMachete.ISyncToRemoteStatusDependentAction.description.sync-to-remote-status.diverged-from.and-newer-than-remote");
case DivergedFromAndOlderThanRemote -> getString(
"action.GitMachete.ISyncToRemoteStatusDependentAction.description.sync-to-remote-status.diverged-from.and-older-than-remote");
case InSyncToRemote -> getString(
"action.GitMachete.ISyncToRemoteStatusDependentAction.description.sync-to-remote-status.in-sync-to-remote");
case Untracked -> getString(
"action.GitMachete.ISyncToRemoteStatusDependentAction.description.sync-to-remote-status.untracked");
case NoRemotes -> getString(
"action.GitMachete.ISyncToRemoteStatusDependentAction.description.sync-to-remote-status.no-remotes");
};
presentation.setDescription(
fmt(getNonHtmlString("action.GitMachete.ISyncToRemoteStatusDependentAction.description.disabled.branch-status"),
getActionNameForDescription(), desc));
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/IWithLogger.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/IWithLogger.java | package com.virtuslab.gitmachete.frontend.actions.base;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
public interface IWithLogger {
LambdaLogger log();
/**
* @return {@code false} if the execution on the current thread is in a context where logging should be avoided
* (because e.g. it would lead to a massive spam in the logs);
* {@code true} otherwise
*/
boolean isLoggingAcceptable();
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSlideOutAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSlideOutAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.getQuotedStringOrCurrent;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
import com.virtuslab.gitmachete.frontend.actions.common.SlideOut;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class})
public abstract class BaseSlideOutAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
IExpectsKeyGitMacheteRepository {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isEnabledAndVisible()) {
return;
}
val branchName = getNameOfBranchUnderAction(anActionEvent);
val branch = branchName != null
? getManagedBranchByName(anActionEvent, branchName)
: null;
if (branch == null) {
presentation.setEnabled(false);
presentation.setDescription(getNonHtmlString("action.GitMachete.description.disabled.undefined.machete-branch")
.fmt("Slide out", getQuotedStringOrCurrent(branchName)));
} else {
presentation
.setDescription(getNonHtmlString("action.GitMachete.BaseSlideOutAction.description").fmt(branch.getName()));
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
log().debug("Performing");
val branchName = getNameOfBranchUnderAction(anActionEvent);
val branch = getManagedBranchByName(anActionEvent, branchName);
if (branch != null) {
doSlideOut(anActionEvent, branch);
}
}
@ContinuesInBackground
@UIEffect
private void doSlideOut(AnActionEvent anActionEvent, IManagedBranchSnapshot branchToSlideOut) {
log().debug(() -> "Entering: branchToSlideOut = ${branchToSlideOut}");
log().debug("Refreshing repository state");
val branchLayout = getBranchLayout(anActionEvent);
val selectedGitRepository = getSelectedGitRepository(anActionEvent);
if (branchLayout == null) {
log().debug("branchLayout is null");
} else if (selectedGitRepository == null) {
log().debug("selectedGitRepository is null");
} else {
val graphTable = getGraphTable(anActionEvent);
new SlideOut(branchToSlideOut, selectedGitRepository, branchLayout, graphTable).run();
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseResetToRemoteAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseResetToRemoteAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.actions.backgroundables.FetchBackgroundable.LOCAL_REPOSITORY_NAME;
import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.createRefspec;
import static com.virtuslab.gitmachete.frontend.defs.PropertiesComponentKeys.SHOW_RESET_INFO;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static org.checkerframework.checker.i18nformatter.qual.I18nConversionCategory.GENERAL;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.ui.MessageDialogBuilder;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.VcsNotifier;
import git4idea.GitReference;
import git4idea.repo.GitRepository;
import io.vavr.collection.List;
import io.vavr.control.Option;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.apache.commons.text.StringEscapeUtils;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
import com.virtuslab.gitmachete.backend.api.IRemoteTrackingBranchReference;
import com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.FetchBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.ResetCurrentToRemoteBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.dialogs.DoNotAskOption;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class, StringEscapeUtils.class})
public abstract class BaseResetToRemoteAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
ISyncToRemoteStatusDependentAction {
public static final String VCS_NOTIFIER_TITLE = getString(
"action.GitMachete.BaseResetToRemoteAction.notification.title");
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
public @I18nFormat({}) String getActionName() {
return getString("action.GitMachete.BaseResetToRemoteAction.action-name");
}
@Override
public @I18nFormat({}) String getActionNameForDescription() {
return getString("action.GitMachete.BaseResetToRemoteAction.description-action-name");
}
@Override
public @Untainted @I18nFormat({GENERAL, GENERAL}) String getEnabledDescriptionFormat() {
return getNonHtmlString("action.GitMachete.BaseResetToRemoteAction.description.enabled");
}
@Override
public List<SyncToRemoteStatus> getEligibleStatuses() {
return List.of(
SyncToRemoteStatus.AheadOfRemote,
SyncToRemoteStatus.BehindRemote,
SyncToRemoteStatus.DivergedFromAndNewerThanRemote,
SyncToRemoteStatus.DivergedFromAndOlderThanRemote);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
syncToRemoteStatusDependentActionUpdate(anActionEvent);
val branch = getNameOfBranchUnderAction(anActionEvent);
if (branch != null) {
val currentBranchIfManaged = getCurrentBranchNameIfManaged(anActionEvent);
val isResettingCurrent = currentBranchIfManaged != null && currentBranchIfManaged.equals(branch);
if (anActionEvent.getPlace().equals(ActionPlaces.CONTEXT_MENU) && isResettingCurrent) {
anActionEvent.getPresentation().setText(getActionName());
}
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
log().debug("Performing");
val project = getProject(anActionEvent);
val gitRepository = getSelectedGitRepository(anActionEvent);
val branchName = getNameOfBranchUnderAction(anActionEvent);
val macheteRepository = getGitMacheteRepositorySnapshot(anActionEvent);
if (gitRepository == null) {
VcsNotifier.getInstance(project).notifyWarning(/* displayId */ null, VCS_NOTIFIER_TITLE,
"Skipping the action because no Git repository is selected");
return;
}
if (branchName == null) {
VcsNotifier.getInstance(project).notifyError(/* displayId */ null, VCS_NOTIFIER_TITLE,
"Internal error occurred. For more information see IDE log file");
return;
}
if (macheteRepository == null) {
VcsNotifier.getInstance(project).notifyError(/* displayId */ null, VCS_NOTIFIER_TITLE,
"Internal error occurred. For more information see IDE log file");
return;
}
val localBranch = getManagedBranchByName(anActionEvent, branchName);
if (localBranch == null) {
VcsNotifier.getInstance(project).notifyError(/* displayId */ null, VCS_NOTIFIER_TITLE,
"Cannot get local branch '${branchName}'");
return;
}
val remoteTrackingBranch = localBranch.getRemoteTrackingBranch();
if (remoteTrackingBranch == null) {
val message = "Branch '${localBranch.getName()}' doesn't have remote tracking branch, so cannot be reset";
log().warn(message);
VcsNotifier.getInstance(project).notifyWarning(/* displayId */ null, VCS_NOTIFIER_TITLE, message);
return;
}
if (PropertiesComponent.getInstance(project).getBoolean(SHOW_RESET_INFO, /* defaultValue */ true)) {
String currentCommitSha = localBranch.getPointedCommit().getHash();
if (currentCommitSha.length() == 40) {
currentCommitSha = currentCommitSha.substring(0, 15);
}
val content = getString("action.GitMachete.BaseResetToRemoteAction.info-dialog.message.HTML").fmt(
branchName.escapeHtml4(),
remoteTrackingBranch.getName().escapeHtml4(),
currentCommitSha);
val resetInfoDialog = MessageDialogBuilder.okCancel(
getString("action.GitMachete.BaseResetToRemoteAction.info-dialog.title"),
content).icon(Messages.getInformationIcon()).doNotAsk(new DoNotAskOption(project, SHOW_RESET_INFO));
if (!resetInfoDialog.ask(project)) {
return;
}
}
// It is required to avoid the reset with uncommitted changes and file cache conflicts.
FileDocumentManager.getInstance().saveAllDocuments();
val currentBranchName = Option.of(gitRepository.getCurrentBranch()).map(GitReference::getName).getOrNull();
if (branchName.equals(currentBranchName)) {
doResetCurrentBranchToRemoteWithKeep(gitRepository, localBranch, remoteTrackingBranch);
} else {
doResetNonCurrentBranchToRemoteWithKeep(gitRepository, localBranch, remoteTrackingBranch);
}
}
@ContinuesInBackground
private void doResetNonCurrentBranchToRemoteWithKeep(
GitRepository gitRepository,
ILocalBranchReference localBranch,
IRemoteTrackingBranchReference remoteTrackingBranch) {
String refspecFromRemoteToLocal = createRefspec(
remoteTrackingBranch.getFullName(), localBranch.getFullName(), /* allowNonFastForward */ true);
new FetchBackgroundable(
gitRepository,
LOCAL_REPOSITORY_NAME,
refspecFromRemoteToLocal,
getNonHtmlString("action.GitMachete.ResetCurrentToRemoteBackgroundable.task-title"),
getNonHtmlString("action.GitMachete.BaseResetToRemoteAction.notification.title.reset-fail")
.fmt(localBranch.getName()),
getString("action.GitMachete.BaseResetToRemoteAction.notification.title.reset-success.HTML").fmt(localBranch.getName()))
.queue();
}
@ContinuesInBackground
protected void doResetCurrentBranchToRemoteWithKeep(
GitRepository gitRepository,
ILocalBranchReference localBranch,
IRemoteTrackingBranchReference remoteTrackingBranch) {
val localBranchName = localBranch.getName();
val remoteTrackingBranchName = remoteTrackingBranch.getName();
new ResetCurrentToRemoteBackgroundable(localBranchName, remoteTrackingBranchName, gitRepository).queue();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseFastForwardMergeToParentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseFastForwardMergeToParentAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static org.checkerframework.checker.i18nformatter.qual.I18nConversionCategory.GENERAL;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.vavr.collection.List;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.common.FastForwardMerge;
import com.virtuslab.gitmachete.frontend.actions.common.MergeProps;
import com.virtuslab.qual.async.ContinuesInBackground;
public abstract class BaseFastForwardMergeToParentAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
ISyncToParentStatusDependentAction {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
public @I18nFormat({}) String getActionNameForDisabledDescription() {
return getString("action.GitMachete.BaseFastForwardMergeToParentAction.description-action-name");
}
@Override
public @Untainted @I18nFormat({GENERAL, GENERAL}) String getEnabledDescriptionFormat() {
return getNonHtmlString("action.GitMachete.BaseFastForwardMergeToParentAction.description");
}
@Override
public List<SyncToParentStatus> getEligibleStatuses() {
return List.of(SyncToParentStatus.InSync, SyncToParentStatus.InSyncButForkPointOff);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
syncToParentStatusDependentActionUpdate(anActionEvent);
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val gitRepository = getSelectedGitRepository(anActionEvent);
val stayingBranchName = getNameOfBranchUnderAction(anActionEvent);
if (gitRepository == null || stayingBranchName == null) {
return;
}
val stayingBranch = getManagedBranchByName(anActionEvent, stayingBranchName);
if (stayingBranch == null) {
return;
}
// This is guaranteed by `syncToParentStatusDependentActionUpdate` invoked from `onUpdate`.
assert stayingBranch.isNonRoot() : "Branch that would be fast-forwarded TO is a root";
val nonRootStayingBranch = stayingBranch.asNonRoot();
val mergeProps = new MergeProps(
/* movingBranch */ nonRootStayingBranch.getParent(),
/* stayingBranch */ nonRootStayingBranch);
new FastForwardMerge(gitRepository, mergeProps, /* fetchNotificationTextPrefix */ "").run();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseProjectDependentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseProjectDependentAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import git4idea.repo.GitRepository;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.frontend.actions.common.SideEffectingActionTrackingService;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.ui.api.gitrepositoryselection.IGitRepositorySelectionProvider;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable;
@ExtensionMethod({GitMacheteBundle.class})
public abstract class BaseProjectDependentAction extends DumbAwareAction implements IWithLogger {
@Override
public final ActionUpdateThread getActionUpdateThread() {
// This is questionable, as update()/onUpdate() methods are supposed to be `@UIEffect` (able to touch UI directly).
// Still, using ActionUpdateThread.EDT here led to issues like #1692, #1694, #1713:
// update() taking more than 300ms on UI thread due to loading classes and other surprisingly heavyweight operations.
// Let's instead use BGT... somehow this doesn't lead to errors so far
// (but it might cause race conditions at some point (?)).
return ActionUpdateThread.BGT;
}
@UIEffect
private boolean isUpdateInProgressOnUIThread;
@Override
public boolean isLoggingAcceptable() {
// We discourage logging while `update()` is in progress since it would lead to massive spam
// (`update` is invoked very frequently, regardless of whether `actionPerformed` is going to happen).
return !isUpdateInProgressOnUIThread;
}
protected abstract boolean isSideEffecting();
@SuppressWarnings("tainting:return")
protected static @Nullable @Untainted String getOngoingSideEffectingActions(Project project) {
val actions = project.getService(SideEffectingActionTrackingService.class).getOngoingActions();
if (actions.isEmpty()) {
return null;
}
if (actions.size() == 1) {
return actions.head();
}
val sorted = actions.toList().sorted();
return sorted.init().mkString(", ") + " and " + sorted.last();
}
@Override
@UIEffect
public final void update(AnActionEvent anActionEvent) {
// Not calling `super.update()` as `com.intellij.openapi.actionSystem.AnAction.update`
// is empty and marked as `@ApiStatus.OverrideOnly`.
isUpdateInProgressOnUIThread = true;
val project = anActionEvent.getProject();
val presentation = anActionEvent.getPresentation();
if (project == null) {
presentation.setEnabledAndVisible(false);
} else {
val ongoingSideEffectingActions = getOngoingSideEffectingActions(project);
if (isSideEffecting() && ongoingSideEffectingActions != null) {
// Note that we still need to call onUpdate to decide whether the action should remain visible.
// At the start of each `update()` call, presentation is apparently always set to visible;
// let's still call setEnabledAndVisible(true) to ensure a consistent behavior.
presentation.setEnabledAndVisible(true);
onUpdate(anActionEvent);
presentation.setEnabled(false);
presentation.setDescription(getNonHtmlString("action.GitMachete.description.disabled.another-actions-ongoing")
.fmt(ongoingSideEffectingActions));
} else {
presentation.setEnabledAndVisible(true);
onUpdate(anActionEvent);
}
}
isUpdateInProgressOnUIThread = false;
}
/**
* If overridden, {@code super.onUpdate(anActionEvent)} should always be called in the first line of overriding method.
*
* @param anActionEvent an action event
*/
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {}
@Override
public abstract LambdaLogger log();
protected Project getProject(AnActionEvent anActionEvent) {
val project = anActionEvent.getProject();
assert project != null : "Can't get project from action event";
return project;
}
protected BaseEnhancedGraphTable getGraphTable(AnActionEvent anActionEvent) {
return getProject(anActionEvent).getService(BaseEnhancedGraphTable.class);
}
protected @Nullable GitRepository getSelectedGitRepository(AnActionEvent anActionEvent) {
val gitRepository = getProject(anActionEvent).getService(IGitRepositorySelectionProvider.class)
.getSelectedGitRepository();
if (isLoggingAcceptable() && gitRepository == null) {
log().warn("No Git repository is selected");
}
return gitRepository;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSlideInBelowAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSlideInBelowAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.actions.backgroundables.FetchBackgroundable.LOCAL_REPOSITORY_NAME;
import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.createRefspec;
import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.getQuotedStringOrCurrent;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static org.apache.commons.text.StringEscapeUtils.escapeHtml4;
import java.util.Collections;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.vcs.VcsNotifier;
import git4idea.GitRemoteBranch;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import git4idea.ui.branch.GitBranchCheckoutOperation;
import git4idea.ui.branch.GitBranchPopupActions.RemoteBranchActions;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.List;
import io.vavr.control.Option;
import lombok.Value;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayoutEntry;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.FetchBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.SlideInNonRootBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.common.UiThreadUnsafeRunnable;
import com.virtuslab.gitmachete.frontend.actions.dialogs.MyGitNewBranchDialog;
import com.virtuslab.gitmachete.frontend.actions.dialogs.SlideInDialog;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod(GitMacheteBundle.class)
public abstract class BaseSlideInBelowAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
IExpectsKeyGitMacheteRepository {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isEnabledAndVisible()) {
return;
}
val branchName = getNameOfBranchUnderAction(anActionEvent);
val branch = branchName != null
? getManagedBranchByName(anActionEvent, branchName)
: null;
if (branchName == null) {
presentation.setVisible(false);
presentation
.setDescription(getNonHtmlString("action.GitMachete.BaseSlideInBelowAction.description.disabled.no-parent"));
} else if (branch == null) {
presentation.setEnabled(false);
presentation.setDescription(getNonHtmlString("action.GitMachete.description.disabled.undefined.machete-branch")
.fmt("Slide In", getQuotedStringOrCurrent(branchName)));
} else {
presentation.setDescription(
getNonHtmlString("action.GitMachete.BaseSlideInBelowAction.description").fmt(branchName));
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val project = getProject(anActionEvent);
val gitRepository = getSelectedGitRepository(anActionEvent);
val parentName = getNameOfBranchUnderAction(anActionEvent);
val branchLayout = getBranchLayout(anActionEvent);
val branchLayoutWriter = ApplicationManager.getApplication().getService(IBranchLayoutWriter.class);
if (gitRepository == null || parentName == null || branchLayout == null) {
return;
}
val slideInDialog = new SlideInDialog(project, branchLayout, parentName, gitRepository);
if (!slideInDialog.showAndGet()) {
log().debug("Options of branch to slide in is null: most likely the action has been canceled from slide-in dialog");
return;
}
val slideInOptions = slideInDialog.getSlideInOptions();
String slideInOptionsName = slideInOptions.getName();
if (parentName.equals(slideInOptionsName)) {
// @formatter:off
VcsNotifier.getInstance(project).notifyError(/* displayId */ null,
/* title */ getString("action.GitMachete.BaseSlideInBelowAction.notification.title.slide-in-fail.HTML").fmt(escapeHtml4(slideInOptionsName)),
/* message */ getString("action.GitMachete.BaseSlideInBelowAction.notification.message.slide-in-under-itself-or-its-descendant"));
// @formatter:on
return;
}
UiThreadUnsafeRunnable preSlideInRunnable = () -> {};
val localBranch = gitRepository.getBranches().findLocalBranch(slideInOptionsName);
if (localBranch == null) {
Tuple2<@Nullable String, UiThreadUnsafeRunnable> branchNameAndPreSlideInRunnable = getBranchNameAndPreSlideInRunnable(
gitRepository, parentName, slideInOptionsName);
preSlideInRunnable = branchNameAndPreSlideInRunnable._2();
val branchName = branchNameAndPreSlideInRunnable._1();
if (!slideInOptionsName.equals(branchName)) {
val branchNameFromNewBranchDialog = branchName != null ? branchName : "no name provided";
VcsNotifier.getInstance(project).notifyWeakError(/* displayId */ null,
/* title */ "",
getString("action.GitMachete.BaseSlideInBelowAction.notification.message.mismatched-names.HTML")
.fmt(escapeHtml4(slideInOptionsName), escapeHtml4(branchNameFromNewBranchDialog)));
return;
}
}
val parentEntry = branchLayout.getEntryByName(parentName);
val entryAlreadyExistsBelowGivenParent = parentEntry != null
&& parentEntry.getChildren().map(BranchLayoutEntry::getName)
.map(names -> names.contains(slideInOptionsName))
.getOrElse(false);
if (entryAlreadyExistsBelowGivenParent && slideInOptions.shouldReattach()) {
log().debug("Skipping action: Branch layout entry already exists below given parent");
return;
}
new SlideInNonRootBackgroundable(
gitRepository,
branchLayout,
branchLayoutWriter,
getGraphTable(anActionEvent),
preSlideInRunnable,
slideInOptions,
parentName).queue();
}
@ContinuesInBackground
@SuppressWarnings("KotlinInternalInJava")
private Tuple2<@Nullable String, UiThreadUnsafeRunnable> getBranchNameAndPreSlideInRunnable(
GitRepository gitRepository,
String startPoint,
String initialName) {
val repositories = java.util.Collections.singletonList(gitRepository);
val project = gitRepository.getProject();
val gitNewBranchDialog = new MyGitNewBranchDialog(project,
repositories,
/* title */ getNonHtmlString("action.GitMachete.BaseSlideInBelowAction.dialog.create-new-branch.title").fmt(startPoint),
initialName,
/* showCheckOutOption */ true,
/* showResetOption */ true,
/* showSetTrackingOption */ false);
val options = gitNewBranchDialog.showAndGetOptions();
if (options == null) {
log().debug("Name of branch to slide in is null: " +
"most likely the action has been canceled from create-new-branch dialog");
return Tuple.of(null, () -> {});
}
val branchName = options.getName();
if (!initialName.equals(branchName)) {
return Tuple.of(branchName, () -> {});
}
val remoteBranch = getGitRemoteBranch(gitRepository, branchName);
if (remoteBranch == null) {
return Tuple.of(branchName, new UiThreadUnsafeRunnable() {
@UIThreadUnsafe
@Override
public void run() {
val operation = new GitBranchCheckoutOperation(project, Collections.singletonList(gitRepository));
operation.perform(startPoint, options, /* callInAwtLater */ null);
}
});
} else if (options.shouldCheckout()) {
return Tuple.of(branchName, () -> ApplicationManager.getApplication().invokeAndWait(new @UI Runnable() {
@Override
@SuppressWarnings("removal")
@UIEffect
public void run() {
RemoteBranchActions.CheckoutRemoteBranchAction.checkoutRemoteBranch(project, repositories, remoteBranch.getName());
}
}));
} else {
val refspec = createRefspec("refs/remotes/" + remoteBranch.getName(),
"refs/heads/" + branchName, /* allowNonFastForward */ false);
return Tuple.of(branchName, () -> new FetchBackgroundable(
gitRepository,
LOCAL_REPOSITORY_NAME,
refspec,
"Fetching Remote Branch",
getNonHtmlString("action.GitMachete.Pull.notification.title.pull-fail").fmt(branchName),
getString("action.GitMachete.Pull.notification.title.pull-success.HTML").fmt(branchName)).queue());
}
}
@Value
static class RemoteAndBranch {
GitRemote remote;
GitRemoteBranch branch;
}
private static @Nullable GitRemoteBranch getGitRemoteBranch(GitRepository gitRepository, String branchName) {
val remotesWithBranch = List.ofAll(gitRepository.getRemotes())
.<RemoteAndBranch>flatMap(r -> {
val remoteBranchName = r.getName() + "/" + branchName;
GitRemoteBranch remoteBranch = gitRepository.getBranches().findRemoteBranch(remoteBranchName);
return remoteBranch != null ? Option.some(new RemoteAndBranch(r, remoteBranch)) : Option.none();
})
// Note: false < true. Hence, the pair with origin will be first (head) if exists.
.sortBy(t -> !t.remote.getName().equals("origin"));
if (remotesWithBranch.isEmpty()) {
return null;
}
val chosen = remotesWithBranch.head();
if (remotesWithBranch.size() > 1) {
val title = getString("action.GitMachete.BaseSlideInBelowAction.notification.title.multiple-remotes");
val message = getString("action.GitMachete.BaseSlideInBelowAction.notification.message.multiple-remotes")
.fmt(chosen.branch.getName(), chosen.remote.getName());
VcsNotifier.getInstance(gitRepository.getProject()).notifyInfo(/* displayId */ null, title, message);
}
return chosen.branch;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSquashAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSquashAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.InSyncButForkPointOff;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.util.Collections;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.vcs.log.VcsCommitMetadata;
import git4idea.branch.GitBranchUiHandlerImpl;
import git4idea.branch.GitBranchWorker;
import git4idea.commands.Git;
import git4idea.rebase.log.GitCommitEditingOperationResult;
import git4idea.rebase.log.squash.GitSquashOperation;
import git4idea.repo.GitRepository;
import io.vavr.collection.List;
import kotlin.Unit;
import lombok.Data;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.SideEffectingBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.common.VcsCommitMetadataAdapterForSquash;
import com.virtuslab.gitmachete.frontend.actions.dialogs.GitNewCommitMessageActionDialog;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod(GitMacheteBundle.class)
public abstract class BaseSquashAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider {
private final String NL = System.lineSeparator();
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
val branchName = getNameOfBranchUnderAction(anActionEvent);
val managedBranch = getManagedBranchByName(anActionEvent, branchName);
val nonRootBranch = managedBranch != null && managedBranch.isNonRoot()
? managedBranch.asNonRoot()
: null;
val syncToParentStatus = nonRootBranch != null ? nonRootBranch.getSyncToParentStatus() : null;
if (branchName != null) {
if (nonRootBranch == null) {
presentation.setDescription(
getNonHtmlString("action.GitMachete.BaseSquashAction.branch-is-root").fmt(branchName));
presentation.setEnabled(false);
} else {
val numberOfCommits = nonRootBranch.getUniqueCommits().length();
val description = getNonHtmlString("action.GitMachete.BaseSquashAction.not-enough-commits")
.fmt(branchName, numberOfCommits + "", numberOfCommits == 1 ? "" : "s");
if (numberOfCommits < 2) {
presentation.setDescription(description);
presentation.setEnabled(false);
} else if (syncToParentStatus == InSyncButForkPointOff) {
presentation.setEnabled(false);
presentation.setDescription(getNonHtmlString("action.GitMachete.BaseSquashAction.fork-point-off")
.fmt(branchName));
} else {
val currentBranchIfManaged = getCurrentBranchNameIfManaged(anActionEvent);
val isSquashingCurrentBranch = currentBranchIfManaged != null && currentBranchIfManaged.equals(branchName);
if (anActionEvent.getPlace().equals(ActionPlaces.CONTEXT_MENU) && isSquashingCurrentBranch) {
presentation.setText(getString("action.GitMachete.BaseSquashAction.text"));
}
}
}
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val branchName = getNameOfBranchUnderAction(anActionEvent);
val managedBranch = getManagedBranchByName(anActionEvent, branchName);
val nonRootBranch = managedBranch != null && managedBranch.isNonRoot()
? managedBranch.asNonRoot()
: null;
if (nonRootBranch != null) {
val commits = nonRootBranch.getUniqueCommits();
val parent = nonRootBranch.getForkPoint();
val syncToParentStatus = nonRootBranch.getSyncToParentStatus();
val gitRepository = getSelectedGitRepository(anActionEvent);
if (commits != null && gitRepository != null && parent != null && branchName != null
&& syncToParentStatus != InSyncButForkPointOff) {
val currentBranch = gitRepository.getCurrentBranch();
val isSquashingCurrentBranch = currentBranch != null && branchName.equals(currentBranch.getName());
doSquash(gitRepository, parent, commits, branchName, isSquashingCurrentBranch);
}
}
}
@Data
// So that Interning Checker doesn't complain about enum comparison (by `equals` and not by `==`) in Lombok-generated `equals`
@SuppressWarnings("interning:not.interned")
private static class VcsCommitMetadataAndMessage {
private final List<VcsCommitMetadata> metadata;
private final String message;
}
@ContinuesInBackground
@UIEffect
private void doSquash(
GitRepository gitRepository,
ICommitOfManagedBranch parent,
List<ICommitOfManagedBranch> commits,
String branchName,
boolean isSquashingCurrentBranch) {
val project = gitRepository.getProject();
val vcsCommitMetadataAndMessage = commits.foldLeft(
new VcsCommitMetadataAndMessage(List.empty(), ""),
(acc, commit) -> new VcsCommitMetadataAndMessage(
acc.metadata.append(new VcsCommitMetadataAdapterForSquash(parent, commit)),
"${commit.getFullMessage()}${NL}${NL}${acc.message}"));
val dialog = new GitNewCommitMessageActionDialog(
/* project */ project,
/* message */ vcsCommitMetadataAndMessage.message.stripTrailing() + NL,
/* title */ getNonHtmlString("action.GitMachete.BaseSquashAction.dialog.title"),
/* dialogLabel */ getNonHtmlString("action.GitMachete.BaseSquashAction.dialog.label"));
String taskName = isSquashingCurrentBranch
? getNonHtmlString("action.GitMachete.BaseSquashAction.task-title.current")
: getNonHtmlString("action.GitMachete.BaseSquashAction.task-title.non-current");
dialog.show(
newMessage -> {
new SideEffectingBackgroundable(project, taskName, "squash") {
@Override
@UIThreadUnsafe
public void doRun(ProgressIndicator indicator) {
log().info("Checking out '${branchName}' branch and squashing it");
if (!isSquashingCurrentBranch) {
val uiHandler = new GitBranchUiHandlerImpl(project, indicator);
new GitBranchWorker(project, Git.getInstance(), uiHandler)
.checkout(/* reference */ branchName, /* detach */ false, Collections.singletonList(gitRepository));
}
val commitsToSquash = vcsCommitMetadataAndMessage.metadata.toJavaList();
val operationResult = new GitSquashOperation(gitRepository).execute(commitsToSquash, newMessage);
if (isComplete(operationResult)) {
val title = getString("action.GitMachete.BaseSquashAction.notification.title");
val notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification(title, NotificationType.INFORMATION);
VcsNotifier.getInstance(project).notify(notification);
}
}
}.queue();
return Unit.INSTANCE;
});
}
/**
* Hackish approach to check for kotlin internal sealed class {@link git4idea.rebase.log.GitCommitEditingOperationResult.Complete}.
*/
private boolean isComplete(GitCommitEditingOperationResult operationResult) {
return operationResult.toString().contains("Complete");
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSyncToParentByMergeAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/base/BaseSyncToParentByMergeAction.java | package com.virtuslab.gitmachete.frontend.actions.base;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static org.checkerframework.checker.i18nformatter.qual.I18nConversionCategory.GENERAL;
import java.util.Collections;
import com.intellij.openapi.actionSystem.AnActionEvent;
import git4idea.GitReference;
import git4idea.branch.GitBrancher;
import git4idea.repo.GitRepository;
import io.vavr.collection.List;
import io.vavr.control.Option;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.common.MergeProps;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
import com.virtuslab.qual.async.ContinuesInBackground;
public abstract class BaseSyncToParentByMergeAction extends BaseGitMacheteRepositoryReadyAction
implements
IBranchNameProvider,
ISyncToParentStatusDependentAction {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
public @I18nFormat({}) String getActionNameForDisabledDescription() {
return getString("action.GitMachete.BaseSyncToParentByMergeAction.description-action-name");
}
@Override
public @Untainted @I18nFormat({GENERAL, GENERAL}) String getEnabledDescriptionFormat() {
return getNonHtmlString("action.GitMachete.BaseSyncToParentByMergeAction.description");
}
@Override
public List<SyncToParentStatus> getEligibleStatuses() {
return List.of(SyncToParentStatus.OutOfSync);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
syncToParentStatusDependentActionUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
val isCalledFromContextMenu = anActionEvent.getPlace().equals(ActionPlaces.CONTEXT_MENU);
val branchName = getNameOfBranchUnderAction(anActionEvent);
val branch = branchName != null
? getManagedBranchByName(anActionEvent, branchName)
: null;
val currentBranchNameIfManaged = getCurrentBranchNameIfManaged(anActionEvent);
val isMergingIntoCurrent = branch != null && currentBranchNameIfManaged != null
&& currentBranchNameIfManaged.equals(branch.getName());
if (isCalledFromContextMenu && isMergingIntoCurrent) {
presentation.setText(getString("action.GitMachete.BaseSyncToParentByMergeAction.text"));
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val gitRepository = getSelectedGitRepository(anActionEvent);
val stayingBranchName = getNameOfBranchUnderAction(anActionEvent);
if (gitRepository == null || stayingBranchName == null) {
return;
}
val movingBranch = getManagedBranchByName(anActionEvent, stayingBranchName);
if (movingBranch == null) {
return;
}
// This is guaranteed by `syncToParentStatusDependentActionUpdate` invoked from `onUpdate`.
assert movingBranch.isNonRoot() : "Branch that would be merged INTO is a root";
val currentBranchName = Option.of(gitRepository.getCurrentBranch()).map(GitReference::getName).getOrNull();
val nonRootMovingBranch = movingBranch.asNonRoot();
val mergeProps = new MergeProps(
/* movingBranch */ nonRootMovingBranch,
/* stayingBranch */ nonRootMovingBranch.getParent());
if (nonRootMovingBranch.getName().equals(currentBranchName)) {
doMergeIntoCurrentBranch(gitRepository, mergeProps);
} else {
doMergeIntoNonCurrentBranch(gitRepository, mergeProps);
}
}
@ContinuesInBackground
@UIEffect
public void doMergeIntoCurrentBranch(GitRepository gitRepository, MergeProps mergeProps) {
val stayingBranch = mergeProps.getStayingBranch().getName();
val project = gitRepository.getProject();
log().debug(() -> "Entering: project = ${project}, gitRepository = ${gitRepository}," +
" stayingBranch = ${stayingBranch}");
GitBrancher.getInstance(project)
.merge(stayingBranch, GitBrancher.DeleteOnMergeOption.NOTHING, Collections.singletonList(gitRepository));
}
@ContinuesInBackground
@UIEffect
private void doMergeIntoNonCurrentBranch(GitRepository gitRepository, MergeProps mergeProps) {
val stayingBranch = mergeProps.getStayingBranch().getName();
val movingBranch = mergeProps.getMovingBranch().getName();
log().debug(() -> "Entering: gitRepository = ${gitRepository}," +
" stayingBranch = ${stayingBranch}, movingBranch = ${movingBranch}");
val gitBrancher = GitBrancher.getInstance(gitRepository.getProject());
val repositories = Collections.singletonList(gitRepository);
Runnable callInAwtLater = () -> gitBrancher.merge(stayingBranch, GitBrancher.DeleteOnMergeOption.NOTHING, repositories);
gitBrancher.checkout(/* reference */ movingBranch, /* detach */ false, repositories, callInAwtLater);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/traverse/CheckoutAndExecute.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/traverse/CheckoutAndExecute.java | package com.virtuslab.gitmachete.frontend.actions.traverse;
import java.util.Collections;
import com.intellij.openapi.application.ModalityState;
import com.intellij.util.ModalityUiUtil;
import git4idea.branch.GitBrancher;
import git4idea.repo.GitRepository;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UI;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable;
import com.virtuslab.qual.async.ContinuesInBackground;
@CustomLog
final class CheckoutAndExecute {
private CheckoutAndExecute() {}
@ContinuesInBackground
static void checkoutAndExecuteOnUIThread(GitRepository gitRepository, BaseEnhancedGraphTable graphTable, String branchName,
@UI Runnable doOnUIThreadAfterCheckout) {
val currentBranch = gitRepository.getCurrentBranch();
if (currentBranch != null && currentBranch.getName().equals(branchName)) {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, doOnUIThreadAfterCheckout);
} else {
LOG.debug(() -> "Queuing '${branchName}' branch checkout background task");
Runnable repositoryRefreshRunnable = () -> graphTable.queueRepositoryUpdateAndModelRefresh(doOnUIThreadAfterCheckout);
val gitBrancher = GitBrancher.getInstance(gitRepository.getProject());
val repositories = Collections.singletonList(gitRepository);
gitBrancher.checkout(/* reference */ branchName, /* detach */ false, repositories, repositoryRefreshRunnable);
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/traverse/BaseTraverseAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/traverse/BaseTraverseAction.java | package com.virtuslab.gitmachete.frontend.actions.traverse;
import static com.virtuslab.gitmachete.frontend.defs.PropertiesComponentKeys.SHOW_TRAVERSE_INFO;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.MessageDialogBuilder;
import com.intellij.openapi.ui.Messages;
import git4idea.repo.GitRepository;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus;
import com.virtuslab.gitmachete.frontend.actions.base.BaseGitMacheteRepositoryReadyAction;
import com.virtuslab.gitmachete.frontend.actions.base.IBranchNameProvider;
import com.virtuslab.gitmachete.frontend.actions.dialogs.DoNotAskOption;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class})
public abstract class BaseTraverseAction extends BaseGitMacheteRepositoryReadyAction implements IBranchNameProvider {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isEnabledAndVisible()) {
return;
}
presentation.setDescription(getNonHtmlString("action.GitMachete.BaseTraverseAction.description"));
val graphTable = getGraphTable(anActionEvent);
val repositorySnapshot = graphTable.getGitMacheteRepositorySnapshot();
val branchLayout = repositorySnapshot != null ? repositorySnapshot.getBranchLayout() : null;
if (repositorySnapshot == null || branchLayout == null || branchLayout.getRootEntries().isEmpty()) {
presentation.setEnabled(false);
presentation.setDescription(getNonHtmlString("action.GitMachete.BaseTraverseAction.description.empty-layout"));
return;
}
String branchUnderAction = getNameOfBranchUnderAction(anActionEvent);
if (branchUnderAction == null) {
presentation.setEnabled(false);
presentation
.setDescription(getNonHtmlString("action.GitMachete.BaseTraverseAction.description.current-branch-unmanaged"));
return;
}
boolean anythingToBeDone = false;
for (var branch = branchUnderAction; branch != null; branch = branchLayout.findNextEntryName(branch)) {
val managedBranch = repositorySnapshot.getManagedBranchByName(branch);
if (managedBranch == null) {
continue;
}
if (managedBranch.isNonRoot() && managedBranch.asNonRoot().getSyncToParentStatus() != SyncToParentStatus.InSync) {
anythingToBeDone = true;
break;
}
val syncToRemoteStatus = managedBranch.getRelationToRemote().getSyncToRemoteStatus();
if (syncToRemoteStatus != SyncToRemoteStatus.InSyncToRemote && syncToRemoteStatus != SyncToRemoteStatus.NoRemotes) {
anythingToBeDone = true;
break;
}
}
if (!anythingToBeDone) {
presentation.setEnabled(false);
presentation.setDescription(
getNonHtmlString("action.GitMachete.BaseTraverseAction.description.nothing-to-be-done").fmt(branchUnderAction));
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val gitRepository = getSelectedGitRepository(anActionEvent);
val graphTable = getGraphTable(anActionEvent);
val repositorySnapshot = graphTable.getGitMacheteRepositorySnapshot();
val branchLayout = repositorySnapshot != null ? repositorySnapshot.getBranchLayout() : null;
val project = getProject(anActionEvent);
boolean yesNoResult = true;
if (branchLayout != null && branchLayout.getRootEntries().nonEmpty() && gitRepository != null) {
if (PropertiesComponent.getInstance(project).getBoolean(SHOW_TRAVERSE_INFO, /* defaultValue */ true)) {
val traverseInfoDialog = MessageDialogBuilder.okCancel(
getString("action.GitMachete.BaseTraverseAction.dialog.traverse-approval.title"),
getString("action.GitMachete.BaseTraverseAction.dialog.traverse-approval.text.HTML"))
.icon(Messages.getInformationIcon())
.doNotAsk(new DoNotAskOption(project, SHOW_TRAVERSE_INFO));
yesNoResult = traverseInfoDialog.ask(project);
}
if (yesNoResult) {
val initialBranchName = getNameOfBranchUnderAction(anActionEvent);
if (initialBranchName != null) {
traverseFrom(gitRepository, graphTable, initialBranchName);
} else {
log().warn("Skipping traverse action because initialBranchName is undefined");
}
}
}
}
@ContinuesInBackground
private void traverseFrom(GitRepository gitRepository, BaseEnhancedGraphTable graphTable, String branchName) {
val repositorySnapshot = graphTable.getGitMacheteRepositorySnapshot();
if (repositorySnapshot == null) {
return;
}
val branchLayout = repositorySnapshot.getBranchLayout();
val gitMacheteBranch = repositorySnapshot.getManagedBranchByName(branchName);
if (gitMacheteBranch != null) {
Runnable traverseNextEntry = () -> {
var nextBranch = branchLayout != null ? branchLayout.findNextEntry(branchName) : null;
if (nextBranch != null) {
traverseFrom(gitRepository, graphTable, nextBranch.getName());
}
};
if (gitMacheteBranch.isNonRoot()) {
new TraverseSyncToParent(gitRepository, graphTable, gitMacheteBranch, traverseNextEntry)
.execute();
} else {
new TraverseSyncToRemote(gitRepository, graphTable, gitMacheteBranch, traverseNextEntry).execute();
}
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/traverse/TraverseSyncToRemote.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/traverse/TraverseSyncToRemote.java | package com.virtuslab.gitmachete.frontend.actions.traverse;
import static com.virtuslab.gitmachete.backend.api.OngoingRepositoryOperationType.NO_OPERATION;
import static com.virtuslab.gitmachete.frontend.actions.dialogs.TraverseInfoComponentKt.pushInfo;
import static com.virtuslab.gitmachete.frontend.actions.traverse.CheckoutAndExecute.checkoutAndExecuteOnUIThread;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import javax.swing.JComponent;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.util.ModalityUiUtil;
import git4idea.GitLocalBranch;
import git4idea.push.GitPushSource;
import git4idea.repo.GitRepository;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.ResetCurrentToRemoteBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.common.Pull;
import com.virtuslab.gitmachete.frontend.actions.dialogs.GitPushDialog;
import com.virtuslab.gitmachete.frontend.actions.dialogs.TraverseStepConfirmationDialog;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable;
import com.virtuslab.qual.async.ContinuesInBackground;
@CustomLog
@ExtensionMethod(GitMacheteBundle.class)
@SuppressWarnings("MissingSwitchDefault")
public class TraverseSyncToRemote {
private final Project project;
private final GitRepository gitRepository;
private final BaseEnhancedGraphTable graphTable;
private final IBranchReference branch;
private final @UI Runnable traverseNextEntry;
public TraverseSyncToRemote(GitRepository gitRepository,
BaseEnhancedGraphTable graphTable,
IBranchReference branch,
@UI Runnable traverseNextEntry) {
this.project = gitRepository.getProject();
this.gitRepository = gitRepository;
this.graphTable = graphTable;
this.branch = branch;
this.traverseNextEntry = traverseNextEntry;
}
@ContinuesInBackground
public void execute() {
// we need to re-retrieve the gitMacheteBranch as its syncToRemote status could have changed after TraverseSyncToParent
val repositorySnapshot = graphTable.getGitMacheteRepositorySnapshot();
if (repositorySnapshot == null) {
LOG.warn("repositorySnapshot is null");
return;
}
val gitMacheteBranch = repositorySnapshot.getManagedBranchByName(branch.getName());
if (gitMacheteBranch == null) {
LOG.warn("gitMacheteBranch is null");
return;
}
val ongoingRepositoryOperationType = repositorySnapshot.getOngoingRepositoryOperation().getOperationType();
if (ongoingRepositoryOperationType != NO_OPERATION) {
VcsNotifier.getInstance(project).notifyError(/* displayId */ null,
/* title */ getString("action.GitMachete.BaseTraverseAction.notification.ongoing-operation.title"),
/* message */ getString("action.GitMachete.BaseTraverseAction.notification.ongoing-operation.message.HTML")
.fmt(ongoingRepositoryOperationType.toString()));
return;
}
val syncToRemoteStatus = gitMacheteBranch.getRelationToRemote().getSyncToRemoteStatus();
val localBranchName = gitMacheteBranch.getName();
val localBranch = gitRepository.getBranches().findLocalBranch(localBranchName);
if (localBranch == null) {
LOG.warn("localBranch is null");
return;
}
switch (syncToRemoteStatus) {
case NoRemotes, InSyncToRemote ->
// A repository refresh isn't needed here.
// Each side-effecting action like push/rebase is responsible for refreshing repository on its own,
// so we can assume that the repository is already up to date once we enter void execute().
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, traverseNextEntry);
case Untracked -> {
@UI Runnable pushUntracked = () -> handleUntracked(gitMacheteBranch, localBranch);
checkoutAndExecuteOnUIThread(gitRepository, graphTable, gitMacheteBranch.getName(), pushUntracked);
}
case AheadOfRemote -> {
@UI Runnable pushAheadOfRemote = () -> handleAheadOfRemote(gitMacheteBranch, localBranch);
checkoutAndExecuteOnUIThread(gitRepository, graphTable, gitMacheteBranch.getName(), pushAheadOfRemote);
}
case DivergedFromAndNewerThanRemote -> {
@UI Runnable pushForceDiverged = () -> handleDivergedFromAndNewerThanRemote(gitMacheteBranch, localBranch);
checkoutAndExecuteOnUIThread(gitRepository, graphTable, gitMacheteBranch.getName(), pushForceDiverged);
}
case DivergedFromAndOlderThanRemote -> {
@UI Runnable resetToRemote = () -> handleDivergedFromAndOlderThanRemote(gitMacheteBranch);
checkoutAndExecuteOnUIThread(gitRepository, graphTable, gitMacheteBranch.getName(), resetToRemote);
}
case BehindRemote -> {
@UI Runnable pullBehindRemote = () -> handleBehindRemote(gitMacheteBranch);
checkoutAndExecuteOnUIThread(gitRepository, graphTable, gitMacheteBranch.getName(), pullBehindRemote);
}
}
}
@ContinuesInBackground
@UIEffect
private void handleUntracked(IManagedBranchSnapshot gitManagedBranch, GitLocalBranch localBranch) {
JComponent traverseInfoComponent = pushInfo(
getString("action.GitMachete.BaseTraverseAction.dialog.push-approval.untracked.text.HTML")
.fmt(gitManagedBranch.getName()));
Runnable doInUIThreadWhenReady = () -> graphTable.queueRepositoryUpdateAndModelRefresh(traverseNextEntry);
String titlePrefix = getString("string.GitMachete.GitPushDialog.title-prefix");
new GitPushDialog(project, gitRepository, GitPushSource.create(localBranch), /* isForcePushRequired */ false,
traverseInfoComponent, doInUIThreadWhenReady, titlePrefix).show();
}
@ContinuesInBackground
@UIEffect
private void handleAheadOfRemote(IManagedBranchSnapshot gitMacheteBranch, GitLocalBranch localBranch) {
val remoteTrackingBranch = gitMacheteBranch.getRemoteTrackingBranch();
assert remoteTrackingBranch != null : "remoteTrackingBranch is null";
JComponent traverseInfoComponent = pushInfo(
getString("action.GitMachete.BaseTraverseAction.dialog.push-approval.ahead.text.HTML")
.fmt(gitMacheteBranch.getName(), remoteTrackingBranch.getName()));
Runnable doInUIThreadWhenReady = () -> graphTable.queueRepositoryUpdateAndModelRefresh(traverseNextEntry);
String titlePrefix = getString("string.GitMachete.GitPushDialog.title-prefix");
new GitPushDialog(project, gitRepository, GitPushSource.create(localBranch), /* isForcePushRequired */ false,
traverseInfoComponent, doInUIThreadWhenReady, titlePrefix).show();
}
@ContinuesInBackground
@UIEffect
private void handleDivergedFromAndNewerThanRemote(IManagedBranchSnapshot gitMacheteBranch, GitLocalBranch localBranch) {
val remoteTrackingBranch = gitMacheteBranch.getRemoteTrackingBranch();
assert remoteTrackingBranch != null : "remoteTrackingBranch is null";
Runnable doInUIThreadWhenReady = () -> graphTable.queueRepositoryUpdateAndModelRefresh(traverseNextEntry);
String titlePrefix = getString("string.GitMachete.GitPushDialog.title-prefix");
JComponent traverseInfoComponent = pushInfo(
getString("action.GitMachete.BaseTraverseAction.dialog.force-push-approval.text.HTML")
.fmt(gitMacheteBranch.getName(), remoteTrackingBranch.getName()));
new GitPushDialog(project, gitRepository, GitPushSource.create(localBranch), /* isForcePushRequired */ true,
traverseInfoComponent, doInUIThreadWhenReady, titlePrefix).show();
}
@ContinuesInBackground
@UIEffect
private void handleDivergedFromAndOlderThanRemote(IManagedBranchSnapshot gitMacheteBranch) {
val remoteTrackingBranch = gitMacheteBranch.getRemoteTrackingBranch();
assert remoteTrackingBranch != null : "remoteTrackingBranch is null";
val title = getString("action.GitMachete.BaseTraverseAction.dialog.reset-approval.title");
val message = getString("action.GitMachete.BaseTraverseAction.dialog.reset-approval.text.HTML")
.fmt(gitMacheteBranch.getName(), remoteTrackingBranch.getName());
val resetDialog = new TraverseStepConfirmationDialog(title, message);
switch (resetDialog.show(project)) {
case YES ->
new ResetCurrentToRemoteBackgroundable(gitMacheteBranch.getName(), remoteTrackingBranch.getName(), gitRepository) {
@Override
@ContinuesInBackground
public void onSuccess() {
graphTable.queueRepositoryUpdateAndModelRefresh(traverseNextEntry);
}
}.queue();
case YES_AND_QUIT ->
new ResetCurrentToRemoteBackgroundable(gitMacheteBranch.getName(), remoteTrackingBranch.getName(), gitRepository)
.queue();
case NO -> graphTable.queueRepositoryUpdateAndModelRefresh(traverseNextEntry);
}
}
@ContinuesInBackground
@UIEffect
private void handleBehindRemote(IManagedBranchSnapshot gitMacheteBranch) {
val remoteTrackingBranch = gitMacheteBranch.getRemoteTrackingBranch();
assert remoteTrackingBranch != null : "remoteTrackingBranch is null";
val title = getString("action.GitMachete.BaseTraverseAction.dialog.pull-approval.title");
val message = getString("action.GitMachete.BaseTraverseAction.dialog.pull-approval.text.HTML")
.fmt(gitMacheteBranch.getName(), remoteTrackingBranch.getName());
val pullDialog = new TraverseStepConfirmationDialog(title, message);
switch (pullDialog.show(project)) {
case YES -> {
Runnable doInUIThreadWhenReady = () -> graphTable.queueRepositoryUpdateAndModelRefresh(traverseNextEntry);
new Pull(gitRepository, gitMacheteBranch, remoteTrackingBranch).run(doInUIThreadWhenReady);
}
case YES_AND_QUIT -> new Pull(gitRepository, gitMacheteBranch, remoteTrackingBranch).run();
case NO -> graphTable.queueRepositoryUpdateAndModelRefresh(traverseNextEntry);
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/traverse/TraverseSyncToParent.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/traverse/TraverseSyncToParent.java | package com.virtuslab.gitmachete.frontend.actions.traverse;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.DivergedFromAndOlderThanRemote;
import static com.virtuslab.gitmachete.frontend.actions.traverse.CheckoutAndExecute.checkoutAndExecuteOnUIThread;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.util.ModalityUiUtil;
import git4idea.repo.GitRepository;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.RebaseOnParentBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.common.SlideOut;
import com.virtuslab.gitmachete.frontend.actions.dialogs.TraverseStepConfirmationDialog;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
@CustomLog
@ExtensionMethod({GitMacheteBundle.class, GitVfsUtils.class})
@SuppressWarnings("MissingSwitchDefault")
public class TraverseSyncToParent {
private final Project project;
private final GitRepository gitRepository;
private final BaseEnhancedGraphTable graphTable;
private final IBranchReference branch;
private final @UI Runnable traverseNextEntry;
public TraverseSyncToParent(GitRepository gitRepository,
BaseEnhancedGraphTable graphTable,
IBranchReference branch,
@UI Runnable traverseNextEntry) {
this.project = gitRepository.getProject();
this.gitRepository = gitRepository;
this.graphTable = graphTable;
this.branch = branch;
this.traverseNextEntry = traverseNextEntry;
}
@ContinuesInBackground
public void execute() {
val repositorySnapshot = graphTable.getGitMacheteRepositorySnapshot();
if (repositorySnapshot == null) {
LOG.warn("repositorySnapshot is null");
return;
}
val gitMacheteBranch = repositorySnapshot.getManagedBranchByName(branch.getName());
if (gitMacheteBranch == null) {
LOG.warn("gitMacheteBranch is null");
return;
}
if (gitMacheteBranch.isRoot()) {
LOG.warn("gitMacheteBranch is root");
return;
}
Runnable syncToRemoteRunnable = new TraverseSyncToRemote(gitRepository, graphTable, branch, traverseNextEntry)::execute;
val syncToParentStatus = gitMacheteBranch.asNonRoot().getSyncToParentStatus();
val syncToRemoteStatus = gitMacheteBranch.getRelationToRemote().getSyncToRemoteStatus();
switch (syncToParentStatus) {
case InSync ->
// A repository refresh isn't needed here.
// Each side-effecting action like push/rebase is responsible for refreshing repository on its own,
// so we can assume that the repository is already up to date once we enter void execute().
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, syncToRemoteRunnable);
case MergedToParent -> {
@UI Runnable slideOut = () -> handleMergedToParent(repositorySnapshot, gitMacheteBranch.asNonRoot(),
syncToRemoteRunnable);
// Note that checking out the branch to be slid out has the unfortunate side effect
// that we won't suggest deleting the branch after the slide out.
checkoutAndExecuteOnUIThread(gitRepository, graphTable, branch.getName(), slideOut);
}
case InSyncButForkPointOff, OutOfSync -> {
if (syncToRemoteStatus == DivergedFromAndOlderThanRemote) {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, syncToRemoteRunnable);
} else {
@UI Runnable rebase = () -> handleOutOfSyncOrInSyncButForkPointOff(gitMacheteBranch.asNonRoot(),
syncToRemoteRunnable);
checkoutAndExecuteOnUIThread(gitRepository, graphTable, branch.getName(), rebase);
}
}
}
}
@ContinuesInBackground
@UIEffect
private void handleMergedToParent(
IGitMacheteRepositorySnapshot repositorySnapshot,
INonRootManagedBranchSnapshot managedBranch,
Runnable syncToRemoteRunnable) {
val branchLayout = repositorySnapshot.getBranchLayout();
val title = getString("action.GitMachete.BaseTraverseAction.dialog.merged-to-parent.title");
val message = getString(
"action.GitMachete.BaseTraverseAction.dialog.merged-to-parent.text.HTML").fmt(
managedBranch.getName(),
managedBranch.getParent().getName());
val slideOutDialog = new TraverseStepConfirmationDialog(title, message);
switch (slideOutDialog.show(project)) {
case YES -> {
// For a branch merged to its parent, we're not syncing to remote.
// Let's just go straight to the next branch.
Runnable doInUIThreadWhenReady = () -> graphTable.queueRepositoryUpdateAndModelRefresh(traverseNextEntry);
new SlideOut(managedBranch, gitRepository, branchLayout, graphTable).run(doInUIThreadWhenReady);
}
case YES_AND_QUIT -> new SlideOut(managedBranch, gitRepository, branchLayout, graphTable).run();
case NO -> graphTable.queueRepositoryUpdateAndModelRefresh(syncToRemoteRunnable);
}
}
@ContinuesInBackground
@UIEffect
private void handleOutOfSyncOrInSyncButForkPointOff(
INonRootManagedBranchSnapshot managedBranch,
Runnable syncToRemoteRunnable) {
var title = getString("action.GitMachete.BaseTraverseAction.dialog.out-of-sync-to-parent.title");
var text = getString("action.GitMachete.BaseTraverseAction.dialog.out-of-sync-to-parent.text.HTML");
if (managedBranch.getSyncToParentStatus() == SyncToParentStatus.InSyncButForkPointOff) {
title = getString("action.GitMachete.BaseTraverseAction.dialog.fork-point-off.title");
text = getString("action.GitMachete.BaseTraverseAction.dialog.fork-point-off.text.HTML");
}
val message = text.fmt(managedBranch.getName(), managedBranch.getParent().getName());
val rebaseDialog = new TraverseStepConfirmationDialog(title, message);
switch (rebaseDialog.show(project)) {
case YES -> new RebaseOnParentBackgroundable(gitRepository, managedBranch, /* shouldExplicitlyCheckout */ false) {
@Override
@ContinuesInBackground
public void onSuccess() {
graphTable.queueRepositoryUpdateAndModelRefresh(syncToRemoteRunnable);
}
}.queue();
case YES_AND_QUIT -> new RebaseOnParentBackgroundable(
gitRepository, managedBranch, /* shouldExplicitlyCheckout */ false).queue();
case NO -> graphTable.queueRepositoryUpdateAndModelRefresh(syncToRemoteRunnable);
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/hooks/PreRebaseHookExecutor.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/hooks/PreRebaseHookExecutor.java | package com.virtuslab.gitmachete.frontend.actions.hooks;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import git4idea.repo.GitRepository;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import com.virtuslab.gitmachete.backend.api.IGitRebaseParameters;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
public final class PreRebaseHookExecutor extends BaseGit4IdeaHookExecutor {
private static final int EXECUTION_TIMEOUT_SECONDS = 10;
@UIThreadUnsafe
public PreRebaseHookExecutor(GitRepository gitRepository) {
super("machete-pre-rebase", gitRepository);
}
@UIThreadUnsafe
public boolean executeHookFor(IGitRebaseParameters gitRebaseParameters) {
String failureNotificationTitle = getString(
"action.GitMachete.PreRebaseHookExecutor.notification.title.abort");
return executeGit4IdeaHook(failureNotificationTitle, EXECUTION_TIMEOUT_SECONDS,
gitRebaseParameters.getNewBaseBranch().getFullName(),
gitRebaseParameters.getForkPointCommit().getHash(),
gitRebaseParameters.getCurrentBranch().getName());
}
@Override
protected LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/hooks/PostSlideOutHookExecutor.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/hooks/PostSlideOutHookExecutor.java | package com.virtuslab.gitmachete.frontend.actions.hooks;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.util.Objects;
import git4idea.repo.GitRepository;
import io.vavr.collection.List;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
@ExtensionMethod(Objects.class)
public final class PostSlideOutHookExecutor extends BaseGit4IdeaHookExecutor {
@UIThreadUnsafe
public PostSlideOutHookExecutor(GitRepository gitRepository) {
super("machete-post-slide-out", gitRepository);
}
@UIThreadUnsafe
public boolean executeHookFor(@Nullable String parentBranch, String slidOutBranch, List<String> childBranches) {
String failureNotificationTitle = getString(
"action.GitMachete.PostSlideOutHookExecutor.notification.title.fail");
int timeoutSeconds = 20 + childBranches.length() * 10;
val args = List.of(parentBranch.requireNonNullElse(""), slidOutBranch).appendAll(childBranches).toJavaArray(String[]::new);
return executeGit4IdeaHook(failureNotificationTitle, timeoutSeconds, args);
}
@Override
protected LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/hooks/BaseGit4IdeaHookExecutor.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/hooks/BaseGit4IdeaHookExecutor.java | package com.virtuslab.gitmachete.frontend.actions.hooks;
import java.util.concurrent.atomic.AtomicReference;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.VcsNotifier;
import git4idea.config.GitConfigUtil;
import git4idea.repo.GitRepository;
import git4idea.util.GitFreezingProcess;
import io.vavr.collection.HashMap;
import io.vavr.control.Try;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.hooks.BaseHookExecutor;
import com.virtuslab.gitmachete.backend.hooks.ExecutionResult;
import com.virtuslab.gitmachete.backend.hooks.OnExecutionTimeout;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod(GitVfsUtils.class)
abstract class BaseGit4IdeaHookExecutor extends BaseHookExecutor {
private final Project project;
@UIThreadUnsafe
BaseGit4IdeaHookExecutor(String name, GitRepository gitRepository) {
super(name, gitRepository.getRootDirectoryPath(), gitRepository.getMainGitDirectoryPath(),
getGitConfigCoreHooksPath(gitRepository));
this.project = gitRepository.getProject();
}
@UIThreadUnsafe
private static @Nullable String getGitConfigCoreHooksPath(GitRepository gitRepository) {
try {
return GitConfigUtil.getValue(gitRepository.getProject(), gitRepository.getRoot(), "core.hooksPath");
} catch (VcsException e) {
return null;
}
}
/**
* @return true if the flow can be continued (including when the hook is missing or non-executable),
* false if an error happened and the flow should be aborted
*/
@UIThreadUnsafe
protected boolean executeGit4IdeaHook(String failureNotificationTitle, int timeoutSeconds, String... args) {
AtomicReference<Try<@Nullable ExecutionResult>> wrapper = new AtomicReference<>(
Try.success(null));
// This operation title is solely used for error message ("Local changes are not available until ... is finished")
// that is displayed when a VCS operation (like commit) is attempted while git is frozen.
val operationTitle = "${name} hook";
new GitFreezingProcess(project, operationTitle, () -> {
log().info("Executing ${name} hook");
Try<@Nullable ExecutionResult> tryHookResult = Try
.of(() -> executeHook(timeoutSeconds, OnExecutionTimeout.THROW_EXCEPTION, /* environment */ HashMap.empty(), args));
wrapper.set(tryHookResult);
}).execute();
Try<@Nullable ExecutionResult> tryExecutionResult = wrapper.get();
assert tryExecutionResult != null : "tryExecutionResult should never be null";
if (tryExecutionResult.isFailure()) {
val e = tryExecutionResult.getCause();
val cause = e.getCause();
val message = "${name} hook failed with an exception:${NL}${cause != null ? cause.getMessage() : e.getMessage()}";
log().error(message);
VcsNotifier.getInstance(project).notifyError(/* displayId */ null, failureNotificationTitle, message);
return false;
}
val executionResult = tryExecutionResult.get();
if (executionResult != null && executionResult.getExitCode() != 0) {
val message = "${name} hook did not complete successfully (exit code ${executionResult.getExitCode()})";
log().error(message);
val stdout = executionResult.getStdout();
val stderr = executionResult.getStderr();
VcsNotifier.getInstance(project).notifyError(/* displayId */ null,
failureNotificationTitle, message
+ (!stdout.isBlank() ? NL + "stdout:" + NL + stdout : "")
+ (!stderr.isBlank() ? NL + "stderr:" + NL + stderr : ""));
return false;
}
return true;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/OverrideForkPointOfCurrentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/OverrideForkPointOfCurrentAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.vavr.collection.List;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.base.BaseOverrideForkPointAction;
@CustomLog
public class OverrideForkPointOfCurrentAction extends BaseOverrideForkPointAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
public List<SyncToParentStatus> getEligibleStatuses() {
return List.of(SyncToParentStatus.InSyncButForkPointOff);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isVisible()) {
return;
}
val managedBranchByName = getManagedBranchByName(anActionEvent, getCurrentBranchNameIfManaged(anActionEvent));
val nonRootBranch = managedBranchByName != null && managedBranchByName.isNonRoot()
? managedBranchByName.asNonRoot()
: null;
val isInSyncButForkPointOff = nonRootBranch != null
&& nonRootBranch.getSyncToParentStatus() == SyncToParentStatus.InSyncButForkPointOff;
presentation.setVisible(isInSyncButForkPointOff);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/HelpAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/HelpAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.frontend.actions.dialogs.GraphTableDialog;
public class HelpAction extends DumbAwareAction {
@Override
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
GraphTableDialog.Companion.ofDemoRepository().show();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/FastForwardMergeCurrentToParentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/FastForwardMergeCurrentToParentAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.base.BaseFastForwardMergeToParentAction;
@CustomLog
public class FastForwardMergeCurrentToParentAction extends BaseFastForwardMergeToParentAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isVisible()) {
return;
}
val currentBranchByName = getManagedBranchByName(anActionEvent, getCurrentBranchNameIfManaged(anActionEvent));
val nonRootBranch = currentBranchByName != null && currentBranchByName.isNonRoot()
? currentBranchByName.asNonRoot()
: null;
val isInSyncToParent = nonRootBranch != null && nonRootBranch.getSyncToParentStatus() == SyncToParentStatus.InSync;
presentation.setVisible(isInSyncToParent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/PushCurrentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/PushCurrentAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.AheadOfRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.DivergedFromAndNewerThanRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.Untracked;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.vavr.collection.List;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BasePushAction;
@CustomLog
public class PushCurrentAction extends BasePushAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isVisible()) {
return;
}
val managedBranchByName = getManagedBranchByName(anActionEvent, getCurrentBranchNameIfManaged(anActionEvent));
val syncToRemoteStatus = managedBranchByName != null
? managedBranchByName
.getRelationToRemote().getSyncToRemoteStatus()
: null;
val isAheadOrDivergedAndNewerOrUntracked = syncToRemoteStatus != null
&& List.of(AheadOfRemote, DivergedFromAndNewerThanRemote, Untracked).contains(syncToRemoteStatus);
presentation.setVisible(isAheadOrDivergedAndNewerOrUntracked);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/DiscoverAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/DiscoverAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import static com.intellij.openapi.application.ModalityState.NON_MODAL;
import static com.virtuslab.gitmachete.frontend.actions.toolbar.OpenMacheteFileAction.openMacheteFile;
import static com.virtuslab.gitmachete.frontend.common.WriteActionUtils.blockingRunWriteActionOnUIThread;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.util.Objects;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ModalityUiUtil;
import git4idea.repo.GitRepository;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.SneakyThrows;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositoryCache;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.SideEffectingBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseProjectDependentAction;
import com.virtuslab.gitmachete.frontend.actions.dialogs.GraphTableDialog;
import com.virtuslab.gitmachete.frontend.file.MacheteFileWriter;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.ui.api.gitrepositoryselection.IGitRepositorySelectionProvider;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod({GitMacheteBundle.class, GitVfsUtils.class, Objects.class})
@CustomLog
public class DiscoverAction extends BaseProjectDependentAction {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
public LambdaLogger log() {
return LOG;
}
@Override
@UIEffect
public void onUpdate(AnActionEvent actionEvent) {
super.onUpdate(actionEvent);
actionEvent.getPresentation().setDescription(getNonHtmlString("action.GitMachete.DiscoverAction.description"));
}
@Override
@ContinuesInBackground
public void actionPerformed(AnActionEvent anActionEvent) {
val project = getProject(anActionEvent);
val gitRepository = project.getService(IGitRepositorySelectionProvider.class).getSelectedGitRepository();
if (gitRepository == null) {
VcsNotifier.getInstance(project).notifyError(
/* displayId */ null,
/* title */ getString("action.GitMachete.DiscoverAction.notification.title.cannot-get-current-repository-error"),
/* message */ "");
return;
}
val rootDirPath = gitRepository.getRootDirectoryPath().toAbsolutePath();
val mainGitDirPath = gitRepository.getMainGitDirectoryPath().toAbsolutePath();
val worktreeGitDirPath = gitRepository.getWorktreeGitDirectoryPath().toAbsolutePath();
val branchLayoutWriter = ApplicationManager.getApplication().getService(IBranchLayoutWriter.class);
new SideEffectingBackgroundable(project, getNonHtmlString("action.GitMachete.DiscoverAction.task.title"), "discovery") {
@Override
@SneakyThrows
@UIThreadUnsafe
protected void doRun(ProgressIndicator indicator) {
val repoSnapshot = ApplicationManager.getApplication().getService(IGitMacheteRepositoryCache.class)
.getInstance(rootDirPath, mainGitDirPath, worktreeGitDirPath, ApplicationManager.getApplication()::getService)
.discoverLayoutAndCreateSnapshot();
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> GraphTableDialog.Companion.of(
repoSnapshot,
/* windowTitle */ getString("action.GitMachete.DiscoverAction.discovered-branch-tree-dialog.title"),
/* emptyTableText */ getString("action.GitMachete.DiscoverAction.discovered-branch-tree-dialog.empty-table-text"),
/* saveAction */ repo -> saveMacheteFile(repo, gitRepository, branchLayoutWriter, /* openAfterSave */ false),
/* saveAndOpenAction */ repo -> saveMacheteFile(repo, gitRepository, branchLayoutWriter, /* openAfterSave */ true),
/* okButtonText */ getString("action.GitMachete.DiscoverAction.discovered-branch-tree-dialog.save-button-text"),
/* cancelButtonVisible */ true,
/* shouldDisplayActionToolTips */ false).show());
}
@Override
public void onThrowable(Throwable error) {
VcsNotifier.getInstance(project).notifyError(
/* displayId */ null,
/* title */ getString("action.GitMachete.DiscoverAction.notification.title.repository-discover-error"),
/* message */ error.getMessage().requireNonNullElse(""));
}
}.queue();
}
private void saveMacheteFile(IGitMacheteRepositorySnapshot repositorySnapshot, GitRepository gitRepository,
IBranchLayoutWriter branchLayoutWriter, boolean openAfterSave) {
val branchLayout = repositorySnapshot.getBranchLayout();
blockingRunWriteActionOnUIThread(() -> MacheteFileWriter.writeBranchLayout(
gitRepository.getMacheteFilePath(),
branchLayoutWriter,
branchLayout,
/* backupOldLayout */ true,
/* requestor */ this));
VirtualFile macheteFile = gitRepository.getMacheteFile();
if (openAfterSave && macheteFile != null) {
VfsUtil.markDirtyAndRefresh(/* async */ false, /* recursive */ false, /* reloadChildren */ false, macheteFile);
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> openMacheteFile(gitRepository));
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/ResetCurrentToRemoteAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/ResetCurrentToRemoteAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.DivergedFromAndOlderThanRemote;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseResetToRemoteAction;
@CustomLog
public class ResetCurrentToRemoteAction extends BaseResetToRemoteAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isVisible()) {
return;
}
val managedBranchByName = getManagedBranchByName(anActionEvent, getCurrentBranchNameIfManaged(anActionEvent));
val isDivergedFromAndOlderThanRemote = managedBranchByName != null
&& managedBranchByName.getRelationToRemote().getSyncToRemoteStatus() == DivergedFromAndOlderThanRemote;
presentation.setVisible(isDivergedFromAndOlderThanRemote);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/OpenMacheteFileAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/OpenMacheteFileAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.dvcs.DvcsUtil;
import com.intellij.ide.actions.OpenFileAction;
import com.intellij.notification.NotificationAction;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.GitUtil;
import git4idea.config.GitVcsSettings;
import git4idea.repo.GitRepository;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseProjectDependentAction;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
@ExtensionMethod({GitMacheteBundle.class, GitVfsUtils.class})
@CustomLog
public class OpenMacheteFileAction extends BaseProjectDependentAction {
@Override
protected boolean isSideEffecting() {
return false;
}
@Override
public LambdaLogger log() {
return LOG;
}
@Override
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val project = getProject(anActionEvent);
// When selected Git repository is empty (due to e.g. unopened Git Machete tab)
// an attempt to guess current repository based on presently opened file
val gitRepository = getSelectedGitRepository(anActionEvent);
val repo = gitRepository != null
? gitRepository
: DvcsUtil.guessCurrentRepositoryQuick(project,
GitUtil.getRepositoryManager(project),
GitVcsSettings.getInstance(project).getRecentRootPath());
val gitDir = repo != null ? repo.getMainGitDirectory() : null;
if (repo == null || gitDir == null) {
LOG.warn("Skipping the action because Git repository directory is undefined");
return;
}
@SuppressWarnings("IllegalCatch") ThrowableComputable<@Nullable VirtualFile, RuntimeException> virtualFileRuntimeExceptionThrowableComputable = () -> {
try {
return GitVfsUtils.getMacheteFile(repo);
} catch (Throwable e) {
VcsNotifier.getInstance(project).notifyWeakError(/* displayId */ null,
/* title */ "",
/* message */ getString("action.GitMachete.OpenMacheteFileAction.notification.title.cannot-open"));
return null;
}
};
VirtualFile macheteFile = WriteAction.compute(virtualFileRuntimeExceptionThrowableComputable);
if (macheteFile == null) {
val errorWithDiscover = VcsNotifier.STANDARD_NOTIFICATION.createNotification(
/* title */ getString("action.GitMachete.OpenMacheteFileAction.notification.title.machete-file-not-found"),
/* message */ getString("action.GitMachete.OpenMacheteFileAction.notification.message.machete-file-not-found")
.fmt(gitDir.getPath()),
NotificationType.ERROR);
// Note there is no `.expire()` call, so the action remains available as long as the notification.
// It is troublesome to track the notification and cover all cases when it becomes expired.
// However, the discover action does not perform any changes directly; a dialog appears with options to accept or cancel.
// Hence, there isn't much harm in leaving this notification without the expiration.
errorWithDiscover.addAction(NotificationAction
.createSimple(getString("action.GitMachete.DiscoverAction.GitMacheteToolbar.text"),
() -> ActionManager.getInstance().getAction(DiscoverAction.class.getSimpleName())
.actionPerformed(anActionEvent)));
VcsNotifier.getInstance(project).notify(errorWithDiscover);
} else {
if (macheteFile.isDirectory()) {
VcsNotifier.getInstance(project).notifyError(/* displayId */ null,
/* title */ getString("action.GitMachete.OpenMacheteFileAction.notification.title.same-name-dir-exists"),
/* message */ "");
}
OpenFileAction.openFile(macheteFile, project);
}
}
@UIEffect
public static void openMacheteFile(GitRepository gitRepository) {
val project = gitRepository.getProject();
val file = gitRepository.getMacheteFile();
if (file != null) {
OpenFileAction.openFile(file, project);
} else {
VcsNotifier.getInstance(project).notifyError(
/* displayId */ null,
/* title */ getString("action.GitMachete.OpenMacheteFileAction.notification.title.machete-file-not-found"),
/* message */ getString("action.GitMachete.OpenMacheteFileAction.notification.message.machete-file-not-found")
.fmt(gitRepository.getRoot().getPath()));
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/FetchAllRemotesAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/FetchAllRemotesAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import git4idea.fetch.GitFetchResult;
import git4idea.fetch.GitFetchSupport;
import io.vavr.control.Option;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.SideEffectingBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseProjectDependentAction;
import com.virtuslab.gitmachete.frontend.actions.common.FetchUpToDateTimeoutStatus;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
public class FetchAllRemotesAction extends BaseProjectDependentAction {
@Override
public LambdaLogger log() {
return LOG;
}
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val project = getProject(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (GitFetchSupport.fetchSupport(project).isFetchRunning()) {
presentation.setEnabled(false);
presentation
.setDescription(getNonHtmlString("action.GitMachete.FetchAllRemotesAction.description.disabled.already-running"));
} else {
val gitRepository = getSelectedGitRepository(anActionEvent);
if (gitRepository == null) {
presentation.setEnabled(false);
presentation
.setDescription(getNonHtmlString("action.GitMachete.FetchAllRemotesAction.description.disabled.no-git-repository"));
} else if (gitRepository.getRemotes().isEmpty()) {
presentation.setEnabled(false);
presentation
.setDescription(getNonHtmlString("action.GitMachete.FetchAllRemotesAction.description.disabled.no-remotes"));
} else {
presentation.setEnabled(true);
presentation.setDescription(getNonHtmlString("action.GitMachete.FetchAllRemotesAction.description"));
}
}
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
LOG.debug("Performing");
val project = getProject(anActionEvent);
val gitRepository = getSelectedGitRepository(anActionEvent);
val title = getNonHtmlString("action.GitMachete.FetchAllRemotesAction.task-title");
new SideEffectingBackgroundable(project, title, "fetch") {
private @MonotonicNonNull GitFetchResult result = null;
@Override
@UIThreadUnsafe
public void doRun(ProgressIndicator indicator) {
result = GitFetchSupport.fetchSupport(project).fetchAllRemotes(Option.of(gitRepository).toJavaList());
if (gitRepository != null) {
val repoName = gitRepository.getRoot().getName();
FetchUpToDateTimeoutStatus.update(repoName);
}
}
@Override
@UIEffect
public void onFinished() {
val result = this.result;
if (result != null) {
result.showNotification();
}
}
}.queue();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/TraverseFromFirstAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/TraverseFromFirstAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayoutEntry;
import com.virtuslab.gitmachete.frontend.actions.traverse.BaseTraverseAction;
@CustomLog
public class TraverseFromFirstAction extends BaseTraverseAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
val branchLayout = getBranchLayout(anActionEvent);
if (branchLayout == null) {
return null;
}
return branchLayout.getRootEntries().headOption().map(BranchLayoutEntry::getName).getOrNull();
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/SyncCurrentToParentByRebaseAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/SyncCurrentToParentByRebaseAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSyncToParentByRebaseAction;
@CustomLog
public class SyncCurrentToParentByRebaseAction extends BaseSyncToParentByRebaseAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isVisible()) {
return;
}
val currentBranch = getManagedBranchByName(anActionEvent, getCurrentBranchNameIfManaged(anActionEvent));
if (currentBranch != null) {
if (currentBranch.isNonRoot()) {
val isNotMerged = currentBranch.asNonRoot().getSyncToParentStatus() != SyncToParentStatus.MergedToParent;
presentation.setVisible(isNotMerged);
} else {
presentation.setVisible(false);
}
} else {
presentation.setVisible(false);
}
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/ToggleListingCommitsAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/ToggleListingCommitsAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Toggleable;
import com.intellij.openapi.project.DumbAware;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.frontend.actions.base.BaseGitMacheteRepositoryReadyAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
import com.virtuslab.qual.async.ContinuesInBackground;
@CustomLog
public class ToggleListingCommitsAction extends BaseGitMacheteRepositoryReadyAction
implements
DumbAware,
IExpectsKeyGitMacheteRepository {
@Override
public LambdaLogger log() {
return LOG;
}
@Override
protected boolean isSideEffecting() {
return false;
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
val selected = Toggleable.isSelected(presentation);
Toggleable.setSelected(presentation, selected);
if (!presentation.isEnabledAndVisible()) {
return;
}
val branchLayout = getBranchLayout(anActionEvent);
if (branchLayout == null) {
presentation.setEnabled(false);
presentation
.setDescription(getNonHtmlString("action.GitMachete.ToggleListingCommitsAction.description.disabled.no-branches"));
return;
}
val gitMacheteRepositorySnapshot = getGitMacheteRepositorySnapshot(anActionEvent);
val managedBranches = gitMacheteRepositorySnapshot != null
? gitMacheteRepositorySnapshot.getManagedBranches()
: null;
val anyCommitExists = managedBranches != null &&
managedBranches.exists(b -> b.isNonRoot() && b.asNonRoot().getUniqueCommits().nonEmpty());
if (anyCommitExists) {
presentation.setEnabled(true);
presentation.setDescription(getNonHtmlString("action.GitMachete.ToggleListingCommitsAction.description"));
} else {
presentation.setEnabled(false);
presentation
.setDescription(getNonHtmlString("action.GitMachete.ToggleListingCommitsAction.description.disabled.no-commits"));
}
}
@Override
@ContinuesInBackground
@UIEffect
public final void actionPerformed(AnActionEvent anActionEvent) {
boolean newState = !Toggleable.isSelected(anActionEvent.getPresentation());
LOG.debug("Triggered with newState = ${newState}");
val graphTable = getGraphTable(anActionEvent);
graphTable.setListingCommits(newState);
graphTable.refreshModel();
val presentation = anActionEvent.getPresentation();
Toggleable.setSelected(presentation, newState);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/SlideInBelowCurrentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/SlideInBelowCurrentAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSlideInBelowAction;
@CustomLog
public class SlideInBelowCurrentAction extends BaseSlideInBelowAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/SquashCurrentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/SquashCurrentAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.InSyncButForkPointOff;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSquashAction;
@CustomLog
public class SquashCurrentAction extends BaseSquashAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isVisible()) {
return;
}
val branchName = getNameOfBranchUnderAction(anActionEvent);
val managedBranch = getManagedBranchByName(anActionEvent, branchName);
val nonRootBranch = managedBranch != null && managedBranch.isNonRoot()
? managedBranch.asNonRoot()
: null;
val syncToParentStatus = nonRootBranch != null ? nonRootBranch.getSyncToParentStatus() : null;
if (branchName != null) {
if (nonRootBranch == null) {
presentation.setVisible(false);
} else {
val numberOfCommits = nonRootBranch.getUniqueCommits().length();
if (numberOfCommits < 2 || syncToParentStatus == InSyncButForkPointOff) {
presentation.setVisible(false);
} else {
presentation.setText(getString("action.GitMachete.BaseSquashAction.text"));
presentation.setDescription(getNonHtmlString("action.GitMachete.SquashCurrentAction.description"));
}
}
}
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/SlideOutCurrentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/SlideOutCurrentAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSlideOutAction;
@CustomLog
public class SlideOutCurrentAction extends BaseSlideOutAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isVisible()) {
return;
}
val managedBranchByName = getManagedBranchByName(anActionEvent, getCurrentBranchNameIfManaged(anActionEvent));
val nonRootBranch = managedBranchByName != null && managedBranchByName.isNonRoot()
? managedBranchByName.asNonRoot()
: null;
val isMergedToParent = nonRootBranch != null
&& nonRootBranch.getSyncToParentStatus() == SyncToParentStatus.MergedToParent;
presentation.setVisible(isMergedToParent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/PullCurrentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/toolbar/PullCurrentAction.java | package com.virtuslab.gitmachete.frontend.actions.toolbar;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.BehindRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.InSyncToRemote;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.vavr.collection.List;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BasePullAction;
@CustomLog
public class PullCurrentAction extends BasePullAction {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getCurrentBranchNameIfManaged(anActionEvent);
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isVisible()) {
return;
}
val managedBranchByName = getManagedBranchByName(anActionEvent, getCurrentBranchNameIfManaged(anActionEvent));
val syncToRemoteStatus = managedBranchByName != null
? managedBranchByName.getRelationToRemote().getSyncToRemoteStatus()
: null;
val isBehindOrInSyncToRemote = syncToRemoteStatus != null
&& List.of(BehindRemote, InSyncToRemote).contains(syncToRemoteStatus);
presentation.setVisible(isBehindOrInSyncToRemote);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/BranchNamesCompletion.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/BranchNamesCompletion.java | package com.virtuslab.gitmachete.frontend.actions.common;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.completion.PlainPrefixMatcher;
import com.intellij.codeInsight.lookup.CharFilter;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.DumbAware;
import com.intellij.util.textCompletion.DefaultTextCompletionValueDescriptor;
import com.intellij.util.textCompletion.TextCompletionProvider;
import com.intellij.util.textCompletion.TextCompletionValueDescriptor;
import io.vavr.collection.List;
import lombok.val;
// TODO (#1604): remove this class and replace with com.intellij.util.textCompletion.TextCompletionProviderBase
public final class BranchNamesCompletion implements TextCompletionProvider, DumbAware {
private final List<String> localDirectories;
private final List<String> allSuggestions;
private final TextCompletionValueDescriptor<String> myDescriptor = new DefaultTextCompletionValueDescriptor.StringValueDescriptor();
private final InsertHandler<LookupElement> myInsertHandler = new CompletionCharInsertHandler();
public BranchNamesCompletion(List<String> localDirectories, List<String> allSuggestions) {
this.localDirectories = localDirectories;
this.allSuggestions = allSuggestions;
}
@Override
public String getAdvertisement() {
return "";
}
@Override
public String getPrefix(String text, int offset) {
@SuppressWarnings("index") String substring = text.substring(0, offset);
return substring;
}
@Override
public CompletionResultSet applyPrefixMatcher(CompletionResultSet result, String prefix) {
CompletionResultSet resultWithMatcher = result.withPrefixMatcher(new PlainPrefixMatcher(prefix));
resultWithMatcher = resultWithMatcher.caseInsensitive();
return resultWithMatcher;
}
@Override
public CharFilter.Result acceptChar(char c) {
return CharFilter.Result.ADD_TO_PREFIX;
}
@Override
public void fillCompletionVariants(CompletionParameters parameters, String prefix, CompletionResultSet result) {
val values = getValues(parameters).sorted(myDescriptor);
for (String completionVariant : values) {
result.addElement(installInsertHandler(myDescriptor.createLookupBuilder(completionVariant)));
}
result.stopHere();
}
private LookupElement installInsertHandler(LookupElementBuilder builder) {
InsertHandler<LookupElement> handler = builder.getInsertHandler();
if (handler == null) {
return builder.withInsertHandler(myInsertHandler);
}
return builder.withInsertHandler(new InsertHandler<>() {
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
myInsertHandler.handleInsert(context, item);
handler.handleInsert(context, item);
}
});
}
private List<String> getValues(CompletionParameters parameters) {
if (parameters.isAutoPopup()) {
return localDirectories;
} else {
return allSuggestions;
}
}
public static class CompletionCharInsertHandler implements InsertHandler<LookupElement> {
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
context.setAddCompletionChar(false);
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/BranchCreationUtils.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/BranchCreationUtils.java | package com.virtuslab.gitmachete.frontend.actions.common;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.openapi.vcs.VcsNotifier;
import git4idea.repo.GitRepository;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod(GitMacheteBundle.class)
public final class BranchCreationUtils {
private BranchCreationUtils() {}
/**
* @return true, when the branch has been created in the allowed time, otherwise false
*/
@UIThreadUnsafe
public static boolean waitForCreationOfLocalBranch(GitRepository gitRepository, String branchName) {
try {
// Usually just 3 attempts are enough
val MAX_SLEEP_DURATION = 16384;
var sleepDuration = 64;
while (gitRepository.getBranches().findLocalBranch(branchName) == null && sleepDuration <= MAX_SLEEP_DURATION) {
//noinspection BusyWait
Thread.sleep(sleepDuration);
sleepDuration *= 2;
}
} catch (InterruptedException e) {
VcsNotifier.getInstance(gitRepository.getProject()).notifyWeakError(/* displayId */ null,
/* title */ "",
getString("action.GitMachete.BranchCreationUtils.notification.message.wait-interrupted")
.fmt(branchName));
}
if (gitRepository.getBranches().findLocalBranch(branchName) == null) {
VcsNotifier.getInstance(gitRepository.getProject()).notifyWeakError(/* displayId */ null,
/* title */ "",
getString("action.GitMachete.BranchCreationUtils.notification.message.timeout").fmt(branchName));
return false;
}
return true;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/MergeProps.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/MergeProps.java | package com.virtuslab.gitmachete.frontend.actions.common;
import lombok.Value;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
@Value
public class MergeProps {
ILocalBranchReference movingBranch;
IBranchReference stayingBranch;
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/SlideInOptions.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/SlideInOptions.java | package com.virtuslab.gitmachete.frontend.actions.common;
import lombok.Getter;
import lombok.experimental.Accessors;
@Getter
public class SlideInOptions {
private final String name;
@Accessors(fluent = true)
private final Boolean shouldReattach;
private final String customAnnotation;
public SlideInOptions(String name, boolean shouldReattach, String customAnnotation) {
this.name = name;
this.shouldReattach = shouldReattach;
this.customAnnotation = customAnnotation;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/FetchUpToDateTimeoutStatus.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/FetchUpToDateTimeoutStatus.java | package com.virtuslab.gitmachete.frontend.actions.common;
import git4idea.repo.GitRepository;
public final class FetchUpToDateTimeoutStatus {
private FetchUpToDateTimeoutStatus() {}
public static final long FETCH_ALL_UP_TO_DATE_TIMEOUT_MILLIS = 60 * 1000;
public static final String FETCH_ALL_UP_TO_DATE_TIMEOUT_AS_STRING = "a minute";
@SuppressWarnings("ConstantName")
private static final java.util.concurrent.ConcurrentMap<String, Long> lastFetchTimeMillisByRepositoryName = new java.util.concurrent.ConcurrentHashMap<>();
public static boolean isUpToDate(GitRepository gitRepository) {
String repoName = gitRepository.getRoot().getName();
long lftm = lastFetchTimeMillisByRepositoryName.getOrDefault(repoName, 0L);
return System.currentTimeMillis() < lftm + FETCH_ALL_UP_TO_DATE_TIMEOUT_MILLIS;
}
public static void update(String repoName) {
lastFetchTimeMillisByRepositoryName.put(repoName, System.currentTimeMillis());
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/Pull.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/Pull.java | package com.virtuslab.gitmachete.frontend.actions.common;
import static com.virtuslab.gitmachete.frontend.actions.common.FetchUpToDateTimeoutStatus.FETCH_ALL_UP_TO_DATE_TIMEOUT_AS_STRING;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.fmt;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.openapi.vcs.VcsNotifier;
import git4idea.repo.GitRepository;
import lombok.RequiredArgsConstructor;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
import com.virtuslab.gitmachete.backend.api.IRemoteTrackingBranchReference;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.FetchBackgroundable;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod(GitMacheteBundle.class)
@RequiredArgsConstructor
public final class Pull {
private final GitRepository gitRepository;
private final ILocalBranchReference localBranch;
private final IRemoteTrackingBranchReference remoteBranch;
@ContinuesInBackground
public void run() {
run(() -> {});
}
@ContinuesInBackground
public void run(@UI Runnable doInUIThreadWhenReady) {
val mergeProps = new MergeProps(
/* movingBranch */ localBranch,
/* stayingBranch */ remoteBranch);
val isUpToDate = FetchUpToDateTimeoutStatus.isUpToDate(gitRepository);
val fetchNotificationPrefix = isUpToDate
? getNonHtmlString("action.GitMachete.Pull.notification.prefix.no-fetch-performed")
.fmt(FETCH_ALL_UP_TO_DATE_TIMEOUT_AS_STRING)
: getNonHtmlString("action.GitMachete.Pull.notification.prefix.fetch-performed");
val fastForwardMerge = new FastForwardMerge(gitRepository, mergeProps, fetchNotificationPrefix);
if (isUpToDate) {
fastForwardMerge.run(doInUIThreadWhenReady);
} else {
fetchAndThenFFMerge(fetchNotificationPrefix, /* onSuccessRunnable */ () -> fastForwardMerge.run(doInUIThreadWhenReady));
}
}
@ContinuesInBackground
private void fetchAndThenFFMerge(String fetchNotificationPrefix, Runnable onSuccessRunnable) {
String remoteName = remoteBranch.getRemoteName();
String remoteBranchName = remoteBranch.getName();
String taskTitle = getNonHtmlString("action.GitMachete.Pull.task-title");
new FetchBackgroundable(
gitRepository,
remoteName,
/* refspec */ null, // let's use the default refspec for the given remote, as defined in git config
taskTitle,
getNonHtmlString("action.GitMachete.Pull.notification.title.pull-fail").fmt(remoteBranchName),
getString("action.GitMachete.Pull.notification.title.pull-success.HTML").fmt(remoteBranchName)) {
@Override
@UIEffect
public void onSuccess() {
String repoName = gitRepository.getRoot().getName();
FetchUpToDateTimeoutStatus.update(repoName);
if (gitRepository.getBranches().findBranchByName(remoteBranchName) == null) {
val errorMessage = fmt(getString("action.GitMachete.Pull.notification.remote-branch-missing.text"), remoteBranchName);
val taskFailNotificationTitle = getString(
"action.GitMachete.Pull.notification.title.fast-forward-fail");
VcsNotifier.getInstance(gitRepository.getProject()).notifyError(
/* displayId */ null, taskFailNotificationTitle, fetchNotificationPrefix + " " + errorMessage);
} else {
onSuccessRunnable.run();
}
}
}.queue();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/ActionUtils.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/ActionUtils.java | package com.virtuslab.gitmachete.frontend.actions.common;
import org.checkerframework.checker.nullness.qual.Nullable;
public final class ActionUtils {
private ActionUtils() {}
public static String createRefspec(String sourceBranchFullName, String targetBranchFullName, boolean allowNonFastForward) {
return (allowNonFastForward ? "+" : "") + sourceBranchFullName + ":" + targetBranchFullName;
}
public static String getQuotedStringOrCurrent(@Nullable String string) {
return string != null ? "'${string}'" : "current";
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/SlideInUnmanagedBelowAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/SlideInUnmanagedBelowAction.java | package com.virtuslab.gitmachete.frontend.actions.common;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.branchlayout.api.BranchLayoutEntry;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.SlideInNonRootBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.SlideInRootBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseGitMacheteRepositoryReadyAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyGitMacheteRepository;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeyUnmanagedBranchName;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod(GitMacheteBundle.class)
@CustomLog
public class SlideInUnmanagedBelowAction extends BaseGitMacheteRepositoryReadyAction
implements
IExpectsKeyGitMacheteRepository,
IExpectsKeySelectedBranchName,
IExpectsKeyUnmanagedBranchName {
@Override
protected boolean isSideEffecting() {
return true;
}
@Override
public LambdaLogger log() {
return LOG;
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val gitRepository = getSelectedGitRepository(anActionEvent);
val parentName = getSelectedBranchName(anActionEvent);
val unmanagedBranch = getNameOfUnmanagedBranch(anActionEvent);
val branchLayout = getBranchLayout(anActionEvent);
val branchLayoutWriter = ApplicationManager.getApplication().getService(IBranchLayoutWriter.class);
if (gitRepository == null || branchLayout == null || unmanagedBranch == null) {
return;
}
val slideInOptions = new SlideInOptions(unmanagedBranch, /* shouldReattach */ false, /* customAnnotation */ "");
UiThreadUnsafeRunnable preSlideInRunnable = () -> {};
val parentEntry = parentName != null ? branchLayout.getEntryByName(parentName) : null;
val entryAlreadyExistsBelowGivenParent = parentEntry != null
&& parentEntry.getChildren().map(BranchLayoutEntry::getName)
.map(names -> names.contains(slideInOptions.getName()))
.getOrElse(false);
if (entryAlreadyExistsBelowGivenParent && slideInOptions.shouldReattach()) {
LOG.debug("Skipping action: Branch layout entry already exists below given parent");
return;
}
val graphTable = getGraphTable(anActionEvent);
if (parentName != null) {
new SlideInNonRootBackgroundable(
gitRepository,
branchLayout,
branchLayoutWriter,
graphTable,
preSlideInRunnable,
slideInOptions,
parentName).queue();
} else {
new SlideInRootBackgroundable(
gitRepository,
branchLayout,
branchLayoutWriter,
graphTable,
preSlideInRunnable,
slideInOptions).queue();
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/FastForwardMerge.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/FastForwardMerge.java | package com.virtuslab.gitmachete.frontend.actions.common;
import static com.virtuslab.gitmachete.frontend.actions.backgroundables.FetchBackgroundable.LOCAL_REPOSITORY_NAME;
import static com.virtuslab.gitmachete.frontend.actions.common.ActionUtils.createRefspec;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.util.Objects;
import git4idea.GitReference;
import git4idea.repo.GitRepository;
import io.vavr.control.Option;
import lombok.RequiredArgsConstructor;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.FetchBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.MergeCurrentBranchFastForwardOnlyBackgroundable;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod({GitMacheteBundle.class, Objects.class})
@RequiredArgsConstructor
public class FastForwardMerge {
private final GitRepository gitRepository;
private final MergeProps mergeProps;
private final @Untainted String notificationTextPrefix;
@ContinuesInBackground
public void run() {
run(() -> {});
}
@ContinuesInBackground
public void run(@UI Runnable doInUIThreadWhenReady) {
val currentBranchName = Option.of(gitRepository.getCurrentBranch()).map(GitReference::getName).getOrNull();
if (mergeProps.getMovingBranch().getName().equals(currentBranchName)) {
mergeCurrentBranch(doInUIThreadWhenReady);
} else {
mergeNonCurrentBranch(doInUIThreadWhenReady);
}
}
@ContinuesInBackground
private void mergeCurrentBranch(@UI Runnable doInUIThreadWhenReady) {
new MergeCurrentBranchFastForwardOnlyBackgroundable(gitRepository, mergeProps.getStayingBranch()) {
@Override
@UIEffect
public void onSuccess() {
super.onSuccess();
doInUIThreadWhenReady.run();
}
}.queue();
}
@ContinuesInBackground
private void mergeNonCurrentBranch(@UI Runnable doInUIThreadWhenReady) {
val stayingFullName = mergeProps.getStayingBranch().getFullName();
val movingFullName = mergeProps.getMovingBranch().getFullName();
val refspecFromChildToParent = createRefspec(stayingFullName, movingFullName, /* allowNonFastForward */ false);
val stayingName = mergeProps.getStayingBranch().getName();
val movingName = mergeProps.getMovingBranch().getName();
val successFFMergeNotification = getString(
"action.GitMachete.FastForwardMerge.notification.text.ff-success").fmt(stayingName, movingName);
val failFFMergeNotification = getNonHtmlString(
"action.GitMachete.FastForwardMerge.notification.text.ff-fail").fmt(stayingName, movingName);
new FetchBackgroundable(
gitRepository,
LOCAL_REPOSITORY_NAME,
refspecFromChildToParent,
getNonHtmlString("action.GitMachete.FastForwardMerge.task-title"),
notificationTextPrefix + " " + failFFMergeNotification,
notificationTextPrefix + " " + successFFMergeNotification) {
@Override
@UIEffect
public void onSuccess() {
super.onSuccess();
doInUIThreadWhenReady.run();
}
}.queue();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/VcsCommitMetadataAdapterForSquash.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/VcsCommitMetadataAdapterForSquash.java | package com.virtuslab.gitmachete.frontend.actions.common;
import java.util.Collections;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcs.log.Hash;
import com.intellij.vcs.log.VcsCommitMetadata;
import com.intellij.vcs.log.VcsUser;
import com.intellij.vcs.log.impl.HashImpl;
import io.vavr.NotImplementedError;
import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch;
public class VcsCommitMetadataAdapterForSquash implements VcsCommitMetadata {
private final java.util.List<Hash> parents;
private final Hash hash;
private final String fullMessage;
public VcsCommitMetadataAdapterForSquash(ICommitOfManagedBranch parent, ICommitOfManagedBranch commit) {
this.parents = Collections.singletonList(HashImpl.build(parent.getHash()));
this.hash = HashImpl.build(commit.getHash());
this.fullMessage = commit.getFullMessage();
}
@Override
public String getFullMessage() {
return fullMessage;
}
@Override
public VirtualFile getRoot() {
throw new NotImplementedError();
}
@Override
public String getSubject() {
throw new NotImplementedError();
}
@Override
public VcsUser getAuthor() {
throw new NotImplementedError();
}
@Override
public VcsUser getCommitter() {
throw new NotImplementedError();
}
@Override
public long getAuthorTime() {
throw new NotImplementedError();
}
@Override
public long getCommitTime() {
throw new NotImplementedError();
}
@Override
public Hash getId() {
return hash;
}
/**
* Hackish approach to use {@link git4idea.rebase.log.squash.GitSquashOperation}.
* Underneath, in {@link git4idea.rebase.log.GitCommitEditingOperation}
* it calls {@code val base = commits.last().parents.first().asString()} to retrieve the base.
*/
@Override
public java.util.List<Hash> getParents() {
return parents;
}
@Override
public long getTimestamp() {
throw new NotImplementedError();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/SlideOut.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/SlideOut.java | package com.virtuslab.gitmachete.frontend.actions.common;
import static com.virtuslab.gitmachete.frontend.defs.GitConfigKeys.DELETE_LOCAL_BRANCH_ON_SLIDE_OUT;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils.getMacheteFilePath;
import java.io.IOException;
import java.util.Collections;
import java.util.function.Consumer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ModalityUiUtil;
import git4idea.branch.GitBrancher;
import git4idea.config.GitConfigUtil;
import git4idea.repo.GitRepository;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.SideEffectingBackgroundable;
import com.virtuslab.gitmachete.frontend.actions.dialogs.DeleteBranchOnSlideOutSuggestionDialog;
import com.virtuslab.gitmachete.frontend.actions.hooks.PostSlideOutHookExecutor;
import com.virtuslab.gitmachete.frontend.common.WriteActionUtils;
import com.virtuslab.gitmachete.frontend.file.MacheteFileWriter;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
@ExtensionMethod({GitMacheteBundle.class})
public class SlideOut {
private final Project project;
private final String branchToSlideOutName;
private final BranchLayout branchLayout;
private final GitRepository gitRepository;
private final BaseEnhancedGraphTable graphTable;
public SlideOut(IManagedBranchSnapshot branchToSlideOut,
GitRepository gitRepository,
BranchLayout branchLayout,
BaseEnhancedGraphTable graphTable) {
this.project = gitRepository.getProject();
this.branchToSlideOutName = branchToSlideOut.getName();
this.branchLayout = branchLayout;
this.gitRepository = gitRepository;
this.graphTable = graphTable;
}
@ContinuesInBackground
public void run() {
run(() -> {});
}
@ContinuesInBackground
public void run(@UI Runnable doInUIThreadWhenReady) {
val branchToSlideOutIsCurrent = branchToSlideOutName.equals(gitRepository.getCurrentBranchName());
val branchToSlideOut = branchLayout.getEntryByName(branchToSlideOutName);
if (branchToSlideOut == null) {
// Unlikely, let's handle this case to calm down Checker Framework.
return;
}
// If a branch has children in machete layout,
// it's better to NOT delete it so that fork points for the children are still computed correctly.
// See the point on "too many commits taken into rebase" in https://github.com/VirtusLab/git-machete#faq
val branchToSlideOutHasChildren = branchToSlideOut.getChildren().nonEmpty();
if (branchToSlideOutIsCurrent) {
LOG.debug("Skipping (optional) local branch deletion because it is current branch");
slideOutBranchAndRunPostSlideOutHookIfPresent(() -> {
VcsNotifier.getInstance(project).notifySuccess(/* displayId */ null,
/* title */ "",
getString("action.GitMachete.SlideOut.notification.title.slide-out-success.is-current.HTML").fmt(
branchToSlideOutName));
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, doInUIThreadWhenReady);
});
} else if (branchToSlideOutHasChildren) {
LOG.debug("Skipping (optional) local branch deletion because it has children");
slideOutBranchAndRunPostSlideOutHookIfPresent(() -> {
VcsNotifier.getInstance(project).notifySuccess(/* displayId */ null,
/* title */ "",
getString("action.GitMachete.SlideOut.notification.title.slide-out-success.has-children.HTML").fmt(
branchToSlideOutName));
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, doInUIThreadWhenReady);
});
} else {
val root = gitRepository.getRoot();
getDeleteLocalBranchOnSlideOutGitConfigValueAndExecute(root, (@Nullable Boolean shouldDelete) -> {
if (shouldDelete == null) {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, () -> suggestBranchDeletion(doInUIThreadWhenReady));
} else {
handleBranchDeletionDecision(shouldDelete, doInUIThreadWhenReady);
}
});
}
}
@ContinuesInBackground
@UIEffect
private void suggestBranchDeletion(@UI Runnable doInUIThreadWhenBranchDeletionReady) {
val slideOutOptions = new DeleteBranchOnSlideOutSuggestionDialog(project, branchToSlideOutName).showAndGetSlideOutOptions();
if (slideOutOptions != null) {
handleBranchDeletionDecision(slideOutOptions.shouldDelete(), doInUIThreadWhenBranchDeletionReady);
if (slideOutOptions.shouldRemember()) {
val value = String.valueOf(slideOutOptions.shouldDelete());
setDeleteLocalBranchOnSlideOutGitConfigValue(gitRepository.getRoot(), value);
}
} else {
val title = getString("action.GitMachete.SlideOut.notification.title.slide-out-info.canceled");
val message = getString("action.GitMachete.SlideOut.notification.message.slide-out-info.canceled.HTML")
.fmt(branchToSlideOutName);
VcsNotifier.getInstance(project).notifyInfo(/* displayId */ null, title, message);
doInUIThreadWhenBranchDeletionReady.run();
}
}
@ContinuesInBackground
private void handleBranchDeletionDecision(boolean shouldDelete, @UI Runnable doInUIThreadWhenReady) {
slideOutBranchAndRunPostSlideOutHookIfPresent(() -> {
if (shouldDelete) {
graphTable.queueRepositoryUpdateAndModelRefresh(
() -> GitBrancher.getInstance(project).deleteBranches(Collections.singletonMap(branchToSlideOutName,
Collections.singletonList(gitRepository)), () -> {
VcsNotifier.getInstance(project).notifySuccess(/* displayId */ null,
/* title */ "",
getString("action.GitMachete.SlideOut.notification.title.slide-out-success.with-delete.HTML").fmt(
branchToSlideOutName));
doInUIThreadWhenReady.run();
}));
} else {
VcsNotifier.getInstance(project).notifySuccess(/* displayId */ null,
/* title */ "",
getString("action.GitMachete.SlideOut.notification.title.slide-out-success.without-delete.HTML").fmt(
branchToSlideOutName));
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, doInUIThreadWhenReady);
}
});
}
@ContinuesInBackground
private void slideOutBranchAndRunPostSlideOutHookIfPresent(Runnable doWhenReady) {
LOG.info("Sliding out '${branchToSlideOutName}' branch in memory");
val branchToSlideOut = branchLayout.getEntryByName(branchToSlideOutName);
if (branchToSlideOut == null) {
// Unlikely, let's handle this case to calm down Checker Framework.
return;
}
val parentBranch = branchToSlideOut.getParent();
val parentBranchName = parentBranch != null ? parentBranch.getName() : null;
val childBranchNames = branchToSlideOut.getChildren().map(child -> child.getName());
val newBranchLayout = branchLayout.slideOut(branchToSlideOutName);
// Let's execute the write action in a blocking way, in order to prevent branch deletion from running concurrently.
// If branch deletion completes before the new branch layout is saved, we might end up with an issue like
// https://github.com/VirtusLab/git-machete-intellij-plugin/issues/971.
WriteActionUtils.<RuntimeException>blockingRunWriteActionOnUIThread(() -> {
try {
val macheteFilePath = getMacheteFilePath(gitRepository);
val branchLayoutWriter = ApplicationManager.getApplication().getService(IBranchLayoutWriter.class);
LOG.info("Writing new branch layout into ${macheteFilePath}");
MacheteFileWriter.writeBranchLayout(macheteFilePath, branchLayoutWriter,
newBranchLayout, /* backupOldFile */ true, /* requestor */ this);
} catch (IOException e) {
val exceptionMessage = e.getMessage();
val errorMessage = "Error occurred while sliding out '${branchToSlideOutName}' branch" +
(exceptionMessage == null ? "" : ": " + exceptionMessage);
LOG.error(errorMessage);
VcsNotifier.getInstance(project).notifyError(/* displayId */ null,
getString("action.GitMachete.SlideOut.notification.title.slide-out-fail.HTML").fmt(branchToSlideOutName),
exceptionMessage == null ? "" : exceptionMessage);
}
});
new SideEffectingBackgroundable(project, getNonHtmlString("string.GitMachete.SlideOut.post-slide-out-hook-task.title"),
"machete-post-slide-out hook") {
@Override
@UIThreadUnsafe
protected void doRun(ProgressIndicator indicator) {
val postSlideOutHookExecutor = new PostSlideOutHookExecutor(gitRepository);
if (postSlideOutHookExecutor.executeHookFor(parentBranchName, branchToSlideOutName, childBranchNames)) {
doWhenReady.run();
}
}
}.queue();
}
@ContinuesInBackground
private void getDeleteLocalBranchOnSlideOutGitConfigValueAndExecute(VirtualFile root,
Consumer<@Nullable Boolean> doForConfigValue) {
new Task.Backgroundable(project, getNonHtmlString("action.GitMachete.get-git-config.task-title")) {
@Override
@UIThreadUnsafe
public void run(ProgressIndicator indicator) {
Boolean result = null;
try {
val value = GitConfigUtil.getValue(project, root, DELETE_LOCAL_BRANCH_ON_SLIDE_OUT);
if (value != null) {
Boolean booleanValue = GitConfigUtil.getBooleanValue(value);
result = booleanValue != null && booleanValue;
}
} catch (VcsException e) {
LOG.warn("Attempt to get '${DELETE_LOCAL_BRANCH_ON_SLIDE_OUT}' git config value failed", e);
}
doForConfigValue.accept(result);
}
}.queue();
}
@ContinuesInBackground
private void setDeleteLocalBranchOnSlideOutGitConfigValue(VirtualFile root, String value) {
new SideEffectingBackgroundable(project, getNonHtmlString("action.GitMachete.set-git-config.task-title"),
"setting git config") {
@Override
@UIThreadUnsafe
public void doRun(ProgressIndicator indicator) {
try {
val additionalParameters = "--local";
GitConfigUtil.setValue(project, root, DELETE_LOCAL_BRANCH_ON_SLIDE_OUT, value, additionalParameters);
} catch (VcsException e) {
LOG.error("Attempt to set '${DELETE_LOCAL_BRANCH_ON_SLIDE_OUT}' git config value failed", e);
}
}
}.queue();
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/SideEffectingActionTrackingService.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/SideEffectingActionTrackingService.java | package com.virtuslab.gitmachete.frontend.actions.common;
import com.intellij.openapi.project.Project;
import io.vavr.collection.HashSet;
import io.vavr.collection.Set;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.checkerframework.checker.tainting.qual.Untainted;
@SuppressWarnings("regexp") // to allow for `synchronized`
public final class SideEffectingActionTrackingService {
// Let's compare action ids by reference, in case there are multiple actions with the same name going on.
// We don't want that finishing one of these actions gives an impression as if all of them completed.
@RequiredArgsConstructor
public static class SideEffectiveActionId {
@Getter
private final @Untainted String name;
@Override
public String toString() {
return name;
}
}
private Set<SideEffectiveActionId> ongoingActions = HashSet.empty();
public SideEffectingActionTrackingService(Project project) {}
public synchronized SideEffectingActionClosable register(@Untainted String id) {
val actionId = new SideEffectiveActionId(id);
ongoingActions = ongoingActions.add(actionId);
return new SideEffectingActionClosable(actionId);
}
public synchronized Set<String> getOngoingActions() {
return ongoingActions.map(a -> a.toString());
}
@RequiredArgsConstructor
public class SideEffectingActionClosable implements AutoCloseable {
private final SideEffectiveActionId actionId;
@Override
public void close() {
synchronized (SideEffectingActionTrackingService.this) {
ongoingActions = ongoingActions.remove(actionId);
}
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/UiThreadUnsafeRunnable.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/common/UiThreadUnsafeRunnable.java | package com.virtuslab.gitmachete.frontend.actions.common;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public interface UiThreadUnsafeRunnable {
@UIThreadUnsafe
void run();
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/expectedkeys/IExpectsKeySelectedBranchName.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/expectedkeys/IExpectsKeySelectedBranchName.java | package com.virtuslab.gitmachete.frontend.actions.expectedkeys;
import com.intellij.openapi.actionSystem.AnActionEvent;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.IWithLogger;
import com.virtuslab.gitmachete.frontend.datakeys.DataKeys;
public interface IExpectsKeySelectedBranchName extends IWithLogger {
default @Nullable String getSelectedBranchName(AnActionEvent anActionEvent) {
val selectedBranchName = anActionEvent.getData(DataKeys.SELECTED_BRANCH_NAME);
if (isLoggingAcceptable() && selectedBranchName == null) {
log().warn("Selected branch is undefined");
}
return selectedBranchName;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/expectedkeys/IExpectsKeyUnmanagedBranchName.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/expectedkeys/IExpectsKeyUnmanagedBranchName.java | package com.virtuslab.gitmachete.frontend.actions.expectedkeys;
import com.intellij.openapi.actionSystem.AnActionEvent;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.IWithLogger;
import com.virtuslab.gitmachete.frontend.datakeys.DataKeys;
public interface IExpectsKeyUnmanagedBranchName extends IWithLogger {
default @Nullable String getNameOfUnmanagedBranch(AnActionEvent anActionEvent) {
val unmanagedBranchName = anActionEvent.getData(DataKeys.UNMANAGED_BRANCH_NAME);
if (isLoggingAcceptable() && unmanagedBranchName == null) {
log().warn("Unmanaged branch is undefined");
}
return unmanagedBranchName;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/expectedkeys/IExpectsKeyGitMacheteRepository.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/expectedkeys/IExpectsKeyGitMacheteRepository.java | package com.virtuslab.gitmachete.frontend.actions.expectedkeys;
import com.intellij.openapi.actionSystem.AnActionEvent;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
import com.virtuslab.gitmachete.frontend.actions.base.IWithLogger;
import com.virtuslab.gitmachete.frontend.datakeys.DataKeys;
public interface IExpectsKeyGitMacheteRepository extends IWithLogger {
default @Nullable IGitMacheteRepositorySnapshot getGitMacheteRepositorySnapshot(AnActionEvent anActionEvent) {
IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot = anActionEvent != null
? anActionEvent.getData(DataKeys.GIT_MACHETE_REPOSITORY_SNAPSHOT)
: null;
if (isLoggingAcceptable() && gitMacheteRepositorySnapshot == null) {
log().warn("Git Machete repository snapshot is undefined");
}
return gitMacheteRepositorySnapshot;
}
default @Nullable BranchLayout getBranchLayout(AnActionEvent anActionEvent) {
val repoSnapshot = getGitMacheteRepositorySnapshot(anActionEvent);
val branchLayout = repoSnapshot != null ? repoSnapshot.getBranchLayout() : null;
if (isLoggingAcceptable() && branchLayout == null) {
log().warn("Branch layout is undefined");
}
return branchLayout;
}
default @Nullable IManagedBranchSnapshot getCurrentMacheteBranchIfManaged(AnActionEvent anActionEvent) {
val repoSnapshot = getGitMacheteRepositorySnapshot(anActionEvent);
return repoSnapshot != null ? repoSnapshot.getCurrentBranchIfManaged() : null;
}
default @Nullable String getCurrentBranchNameIfManaged(AnActionEvent anActionEvent) {
IManagedBranchSnapshot currentMacheteBranchIfManaged = getCurrentMacheteBranchIfManaged(anActionEvent);
String currentBranchName = currentMacheteBranchIfManaged != null ? currentMacheteBranchIfManaged.getName() : null;
if (isLoggingAcceptable() && currentBranchName == null) {
log().warn("Current Git Machete branch name is undefined");
}
return currentBranchName;
}
default @Nullable IManagedBranchSnapshot getManagedBranchByName(AnActionEvent anActionEvent, @Nullable String branchName) {
IGitMacheteRepositorySnapshot repositorySnapShot = getGitMacheteRepositorySnapshot(anActionEvent);
IManagedBranchSnapshot branch = branchName != null && repositorySnapShot != null
? repositorySnapShot.getManagedBranchByName(branchName)
: null;
if (isLoggingAcceptable() && branch == null) {
log().warn(branchName + " Git Machete branch is undefined");
}
return branch;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/navigation/CheckoutPreviousAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/navigation/CheckoutPreviousAction.java | package com.virtuslab.gitmachete.frontend.actions.navigation;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.frontend.actions.base.BaseCheckoutAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
@CustomLog
@ExtensionMethod(GitMacheteBundle.class)
public class CheckoutPreviousAction extends BaseCheckoutAction
implements
IExpectsKeySelectedBranchName {
@Override
protected @Untainted String getNonExistentBranchMessage(AnActionEvent anActionEvent) {
val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent);
return currentBranchName != null
? getNonHtmlString("action.GitMachete.CheckoutPreviousAction.undefined.branch-name").fmt(currentBranchName)
: getNonHtmlString("action.GitMachete.BaseCheckoutAction.undefined.current-branch");
}
@Override
protected @Nullable String getTargetBranchName(AnActionEvent anActionEvent) {
val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent);
val branchLayout = getBranchLayout(anActionEvent);
if (branchLayout != null && currentBranchName != null) {
val previousEntry = branchLayout.findPreviousEntry(currentBranchName);
return previousEntry != null ? previousEntry.getName() : null;
}
return null;
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/navigation/CheckoutParentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/navigation/CheckoutParentAction.java | package com.virtuslab.gitmachete.frontend.actions.navigation;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.frontend.actions.base.BaseCheckoutAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
@CustomLog
@ExtensionMethod(GitMacheteBundle.class)
public class CheckoutParentAction extends BaseCheckoutAction
implements
IExpectsKeySelectedBranchName {
@Override
protected @Untainted String getNonExistentBranchMessage(AnActionEvent anActionEvent) {
val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent);
return currentBranchName != null
? getNonHtmlString("action.GitMachete.CheckoutParentAction.undefined.branch-name").fmt(currentBranchName)
: getNonHtmlString("action.GitMachete.BaseCheckoutAction.undefined.current-branch");
}
@Override
protected @Nullable String getTargetBranchName(AnActionEvent anActionEvent) {
val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent);
val currentBranch = getManagedBranchByName(anActionEvent, currentBranchName);
if (currentBranch != null && currentBranch.isNonRoot()) {
val nonRootBranch = currentBranch.asNonRoot();
return nonRootBranch.getParent().getName();
}
return null;
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/navigation/CheckoutFirstChildAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/navigation/CheckoutFirstChildAction.java | package com.virtuslab.gitmachete.frontend.actions.navigation;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.frontend.actions.base.BaseCheckoutAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
@CustomLog
@ExtensionMethod(GitMacheteBundle.class)
public class CheckoutFirstChildAction extends BaseCheckoutAction
implements
IExpectsKeySelectedBranchName {
@Override
protected @Untainted String getNonExistentBranchMessage(AnActionEvent anActionEvent) {
val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent);
return currentBranchName != null
? getNonHtmlString("action.GitMachete.CheckoutFirstChildAction.undefined.branch-name").fmt(currentBranchName)
: getNonHtmlString("action.GitMachete.BaseCheckoutAction.undefined.current-branch");
}
@Override
protected @Nullable String getTargetBranchName(AnActionEvent anActionEvent) {
val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent);
val currentBranch = getManagedBranchByName(anActionEvent, currentBranchName);
if (currentBranch != null) {
val childBranches = currentBranch.getChildren();
if (childBranches.nonEmpty()) {
val targetBranch = childBranches.get(0);
return targetBranch.getName();
}
}
return null;
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/navigation/CheckoutNextAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/navigation/CheckoutNextAction.java | package com.virtuslab.gitmachete.frontend.actions.navigation;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.frontend.actions.base.BaseCheckoutAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
@CustomLog
@ExtensionMethod(GitMacheteBundle.class)
public class CheckoutNextAction extends BaseCheckoutAction
implements
IExpectsKeySelectedBranchName {
@Override
protected @Untainted String getNonExistentBranchMessage(AnActionEvent anActionEvent) {
val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent);
return currentBranchName != null
? getNonHtmlString("action.GitMachete.CheckoutNextAction.undefined.branch-name").fmt(currentBranchName)
: getNonHtmlString("action.GitMachete.BaseCheckoutAction.undefined.current-branch");
}
@Override
protected @Nullable String getTargetBranchName(AnActionEvent anActionEvent) {
val currentBranchName = getCurrentBranchNameIfManaged(anActionEvent);
val branchLayout = getBranchLayout(anActionEvent);
if (branchLayout != null && currentBranchName != null) {
val nextEntry = branchLayout.findNextEntry(currentBranchName);
return nextEntry != null ? nextEntry.getName() : null;
}
return null;
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/dialogs/TraverseStepConfirmationDialog.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/dialogs/TraverseStepConfirmationDialog.java | package com.virtuslab.gitmachete.frontend.actions.dialogs;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.tainting.qual.Untainted;
@RequiredArgsConstructor
public class TraverseStepConfirmationDialog {
private final String title;
private final String message;
public enum Result {
YES, YES_AND_QUIT, NO, QUIT
}
@UIEffect
public Result show(Project project) {
val yesText = getNonHtmlString("action.GitMachete.BaseTraverseAction.dialog.yes");
val yesAndQuitText = getNonHtmlString("action.GitMachete.BaseTraverseAction.dialog.yes-and-quit");
val noText = getNonHtmlString("action.GitMachete.BaseTraverseAction.dialog.no");
val quitText = getNonHtmlString("action.GitMachete.BaseTraverseAction.dialog.quit");
@Untainted String[] options = {yesText, yesAndQuitText, noText, quitText};
int result = Messages.showDialog(project, message, title, options, /* defaultOptionIndex */ 0, Messages.getQuestionIcon());
return switch (result) {
case 0 -> Result.YES;
case 1 -> Result.YES_AND_QUIT;
case 2 -> Result.NO;
default -> Result.QUIT;
};
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/dialogs/GitPushDialog.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/dialogs/GitPushDialog.java | package com.virtuslab.gitmachete.frontend.actions.dialogs;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import com.intellij.dvcs.push.PushSource;
import com.intellij.dvcs.push.PushSupport;
import com.intellij.dvcs.push.VcsPushOptionValue;
import com.intellij.dvcs.push.ui.VcsPushDialog;
import com.intellij.dvcs.repo.Repository;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.backgroundables.SideEffectingBackgroundable;
import com.virtuslab.qual.async.BackgroundableQueuedElsewhere;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public final class GitPushDialog extends VcsPushDialog {
private final boolean isForcePushRequired;
private final @Nullable JComponent traverseInfoComponent;
private final @UI Runnable doInUIThreadWhenReady;
@UIEffect
public GitPushDialog(
Project project,
Repository repository,
PushSource pushSource,
boolean isForcePushRequired) {
this(project, repository, pushSource, isForcePushRequired,
/* traverseInfoComponent */ null, /* doInUIThreadWhenReady */ () -> {}, /* titlePrefix */ "");
}
@UIEffect
public GitPushDialog(
Project project,
Repository repository,
PushSource pushSource,
boolean isForcePushRequired,
@Nullable JComponent traverseInfoComponent,
@UI Runnable doInUIThreadWhenReady,
String titlePrefix) {
// Presented dialog shows commits for branches belonging to allRepositories, selectedRepositories and currentRepo.
// The second and the third one have a higher priority of loading its commits.
// From our perspective, we always have a single (pre-selected) repository, so we do not care about the priority.
super(project, /* allRepositories */ java.util.List.of(repository),
/* selectedRepositories */ java.util.List.of(repository), /* currentRepo */ null, pushSource);
this.isForcePushRequired = isForcePushRequired;
this.traverseInfoComponent = traverseInfoComponent;
this.doInUIThreadWhenReady = doInUIThreadWhenReady;
// Note: since the class is final, `this` is already @Initialized at this point.
init();
setTitle(titlePrefix + " " + this.getTitle());
}
@Override
public @Nullable JComponent createNorthPanel() {
return traverseInfoComponent;
}
@Override
@UIEffect
public void updateOkActions() {}
@Override
@UIEffect
protected void doOKAction() {
push();
}
@Override
@UIEffect
protected Action[] createActions() {
Action cancelAction = getCancelAction();
Action pushAction = new PushSwingAction();
if (traverseInfoComponent != null) {
cancelAction.putValue(Action.NAME, getNonHtmlString("action.GitMachete.BaseTraverseAction.dialog.quit"));
return new Action[]{cancelAction, new SkipSwingAction(), pushAction, new PushAndQuitSwingAction(), getHelpAction()};
} else {
return new Action[]{pushAction, cancelAction, getHelpAction()};
}
}
@Override
protected Action getOKAction() {
return new PushSwingAction();
}
@UIEffect
private void push() {
push(isForcePushRequired);
}
/**
* Overridden to provide a way to perform an action once the push is completed successfully.
* Compare to the {@link com.intellij.dvcs.push.ui.VcsPushDialog#push(boolean)}
* which doesn't implement {@code onSuccess} callback.
*/
@Override
@BackgroundableQueuedElsewhere // passed on to `executeAfterRunningPrePushHandlers`
@UIEffect
public void push(boolean forcePush) {
String title = getNonHtmlString("string.GitMachete.GitPushDialog.task-title");
executeAfterRunningPrePushHandlers(new SideEffectingBackgroundable(myProject, title, "push") {
@Override
@UIThreadUnsafe
public void doRun(ProgressIndicator indicator) {
myController.push(forcePush);
}
@Override
@UIEffect
public void onSuccess() {
doInUIThreadWhenReady.run();
}
});
}
@BackgroundableQueuedElsewhere // passed on to `executeAfterRunningPrePushHandlers`
@UIEffect
public void pushAndQuit() {
String title = getNonHtmlString("string.GitMachete.GitPushDialog.task-title");
executeAfterRunningPrePushHandlers(new SideEffectingBackgroundable(myProject, title, "push") {
@Override
@UIThreadUnsafe
public void doRun(ProgressIndicator indicator) {
myController.push(isForcePushRequired);
}
});
}
@Override
public @Nullable VcsPushOptionValue getAdditionalOptionValue(PushSupport support) {
return null;
}
private String getPushActionName(boolean hasAndQuit) {
if (hasAndQuit) {
return (isForcePushRequired ? "Force Push" : "Push") + " _and Quit";
} else {
return isForcePushRequired ? "Force _Push" : "_Push";
}
}
private class PushSwingAction extends AbstractAction {
@UIEffect
PushSwingAction() {
super(getPushActionName(/* hasAndQuit */ false));
putValue(DEFAULT_ACTION, Boolean.TRUE);
}
@Override
@UIEffect
public void actionPerformed(ActionEvent e) {
push();
}
}
private class PushAndQuitSwingAction extends AbstractAction {
@UIEffect
PushAndQuitSwingAction() {
super(getPushActionName(/* hasAndQuit */ true));
}
@Override
@UIEffect
public void actionPerformed(ActionEvent e) {
pushAndQuit();
}
}
private class SkipSwingAction extends AbstractAction {
@UIEffect
SkipSwingAction() {
super("_Skip Push");
}
@Override
@UIEffect
public void actionPerformed(ActionEvent e) {
close(OK_EXIT_CODE);
doInUIThreadWhenReady.run();
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/vcsmenu/OpenMacheteTabAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/vcsmenu/OpenMacheteTabAction.java | package com.virtuslab.gitmachete.frontend.actions.vcsmenu;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.frontend.actions.base.BaseProjectDependentAction;
@CustomLog
public class OpenMacheteTabAction extends BaseProjectDependentAction {
@Override
protected boolean isSideEffecting() {
return false;
}
@Override
public LambdaLogger log() {
return LOG;
}
@Override
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
LOG.debug("Performing");
// Getting project from event and assigning it to variable is needed to avoid exception
// because the data context is shared between Swing events (esp. with #2 VcsNotifier call - inside lambda)
val project = getProject(anActionEvent);
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
ToolWindow toolWindow = toolWindowManager.getToolWindow(ToolWindowId.VCS);
Runnable warnNoGit = () -> VcsNotifier.getInstance(project).notifyWarning(
/* displayId */ null,
getString("action.GitMachete.OpenMacheteTabAction.notification.title.could-not-open-tab.HTML"),
getString("action.GitMachete.OpenMacheteTabAction.notification.message.no-git"));
if (toolWindow == null) {
LOG.debug("VCS tool window does not exist");
warnNoGit.run();
return;
}
toolWindow.activate(() -> {
val contentManager = toolWindow.getContentManager();
val tab = contentManager.findContent("Git Machete");
if (tab == null) {
LOG.debug("Machete tab does not exist");
warnNoGit.run();
return;
}
contentManager.setSelectedContentCB(tab, /* requestFocus */ true);
});
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SlideInBelowSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SlideInBelowSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSlideInBelowAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class SlideInBelowSelectedAction extends BaseSlideInBelowAction
implements
IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/FastForwardMergeSelectedToParentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/FastForwardMergeSelectedToParentAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseFastForwardMergeToParentAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class FastForwardMergeSelectedToParentAction extends BaseFastForwardMergeToParentAction
implements
IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/OverrideForkPointOfSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/OverrideForkPointOfSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.vavr.collection.List;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.frontend.actions.base.BaseOverrideForkPointAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class OverrideForkPointOfSelectedAction extends BaseOverrideForkPointAction
implements
IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public List<SyncToParentStatus> getEligibleStatuses() {
return List.of(SyncToParentStatus.InSyncButForkPointOff, SyncToParentStatus.OutOfSync);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/PullSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/PullSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BasePullAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class PullSelectedAction extends BasePullAction
implements
IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SquashSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SquashSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSquashAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class SquashSelectedAction extends BaseSquashAction implements IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/CompareSelectedWithParentAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/CompareSelectedWithParentAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseCompareWithParentAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class CompareSelectedWithParentAction extends BaseCompareWithParentAction implements IExpectsKeySelectedBranchName {
@Override
protected boolean isSideEffecting() {
return false;
}
@Override
public LambdaLogger log() {
return LOG;
}
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/RenameSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/RenameSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseRenameAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class RenameSelectedAction extends BaseRenameAction
implements
IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SyncSelectedToParentByRebaseAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SyncSelectedToParentByRebaseAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSyncToParentByRebaseAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class SyncSelectedToParentByRebaseAction extends BaseSyncToParentByRebaseAction
implements
IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/TraverseFromSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/TraverseFromSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.gitmachete.frontend.actions.traverse.BaseTraverseAction;
@CustomLog
public class TraverseFromSelectedAction extends BaseTraverseAction
implements
IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/CheckoutSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/CheckoutSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.tainting.qual.Untainted;
import com.virtuslab.gitmachete.frontend.actions.base.BaseCheckoutAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
@ExtensionMethod({GitVfsUtils.class, GitMacheteBundle.class})
@CustomLog
public class CheckoutSelectedAction extends BaseCheckoutAction
implements
IExpectsKeySelectedBranchName {
@Override
public LambdaLogger log() {
return LOG;
}
@Override
protected @Nullable String getTargetBranchName(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
protected @Untainted String getNonExistentBranchMessage(AnActionEvent anActionEvent) {
return getNonHtmlString("action.GitMachete.CheckoutSelectedAction.undefined.branch-name");
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/ShowSelectedInGitLogAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/ShowSelectedInGitLogAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.vcs.log.Hash;
import com.intellij.vcs.log.impl.VcsLogContentUtil;
import com.intellij.vcs.log.impl.VcsProjectLog;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.frontend.actions.base.BaseGitMacheteRepositoryReadyAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod(GitMacheteBundle.class)
@CustomLog
public class ShowSelectedInGitLogAction extends BaseGitMacheteRepositoryReadyAction
implements
IExpectsKeySelectedBranchName {
@Override
protected boolean isSideEffecting() {
return false;
}
@Override
public LambdaLogger log() {
return LOG;
}
@Override
@UIEffect
protected void onUpdate(AnActionEvent anActionEvent) {
super.onUpdate(anActionEvent);
val presentation = anActionEvent.getPresentation();
if (!presentation.isEnabledAndVisible()) {
return;
}
val selectedBranchName = getSelectedBranchName(anActionEvent);
// It's very unlikely that selectedBranchName is empty at this point since it's assigned directly before invoking this
// action in GitMacheteGraphTable.GitMacheteGraphTableMouseAdapter.mouseClicked; still, it's better to be safe.
if (selectedBranchName == null || selectedBranchName.isEmpty()) {
presentation.setEnabled(false);
presentation.setDescription(getNonHtmlString("action.GitMachete.ShowSelectedInGitLogAction.undefined.branch-name"));
return;
}
presentation.setDescription(
getNonHtmlString("action.GitMachete.ShowSelectedInGitLogAction.description.precise").fmt(selectedBranchName));
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val selectedBranchName = getSelectedBranchName(anActionEvent);
if (selectedBranchName == null || selectedBranchName.isEmpty()) {
return;
}
val project = getProject(anActionEvent);
val gitRepository = getSelectedGitRepository(anActionEvent);
if (gitRepository != null) {
LOG.debug(() -> "Queuing show '${selectedBranchName}' branch in Git log background task");
val branches = gitRepository.getBranches();
val selectedBranch = branches.findBranchByName(selectedBranchName);
val selectedBranchHash = selectedBranch != null ? branches.getHash(selectedBranch) : null;
if (selectedBranchHash == null) {
LOG.error("Unable to find commit hash for branch '${selectedBranchName}'");
return;
}
VcsLogContentUtil.runInMainLog(project, logUi -> jumpToRevisionUnderProgress(project, selectedBranchHash));
}
}
@ContinuesInBackground
private void jumpToRevisionUnderProgress(Project project, Hash hash) {
val logUi = VcsProjectLog.getInstance(project).getMainLogUi();
if (logUi == null) {
LOG.error("Main VCS Log UI is null");
return;
}
logUi.getVcsLog().jumpToReference(hash.asString());
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/ResetSelectedToRemoteAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/ResetSelectedToRemoteAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseResetToRemoteAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class ResetSelectedToRemoteAction extends BaseResetToRemoteAction implements IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SyncSelectedToParentByMergeAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SyncSelectedToParentByMergeAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import static com.virtuslab.gitmachete.frontend.defs.PropertiesComponentKeys.SHOW_MERGE_WARNING;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.MessageDialogBuilder;
import com.intellij.openapi.ui.Messages;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSyncToParentByMergeAction;
import com.virtuslab.gitmachete.frontend.actions.dialogs.DoNotAskOption;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
import com.virtuslab.qual.async.ContinuesInBackground;
@CustomLog
public class SyncSelectedToParentByMergeAction extends BaseSyncToParentByMergeAction
implements
IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
@ContinuesInBackground
@UIEffect
public void actionPerformed(AnActionEvent anActionEvent) {
val project = getProject(anActionEvent);
if (PropertiesComponent.getInstance(project).getBoolean(SHOW_MERGE_WARNING, /* defaultValue */ true)) {
val dialogBuilder = MessageDialogBuilder.okCancel(
getString("action.GitMachete.SyncSelectedToParentByMergeAction.warning-dialog.title"),
getString("action.GitMachete.SyncSelectedToParentByMergeAction.warning-dialog.message.HTML"));
dialogBuilder
.icon(Messages.getWarningIcon())
.doNotAsk(new DoNotAskOption(project, SHOW_MERGE_WARNING));
val dialogResult = dialogBuilder.ask(project);
if (!dialogResult) {
return;
}
}
super.actionPerformed(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SlideOutSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/SlideOutSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BaseSlideOutAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class SlideOutSelectedAction extends BaseSlideOutAction implements IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/PushSelectedAction.java | frontend/actions/src/main/java/com/virtuslab/gitmachete/frontend/actions/contextmenu/PushSelectedAction.java | package com.virtuslab.gitmachete.frontend.actions.contextmenu;
import com.intellij.openapi.actionSystem.AnActionEvent;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.actions.base.BasePushAction;
import com.virtuslab.gitmachete.frontend.actions.expectedkeys.IExpectsKeySelectedBranchName;
@CustomLog
public class PushSelectedAction extends BasePushAction implements IExpectsKeySelectedBranchName {
@Override
public @Nullable String getNameOfBranchUnderAction(AnActionEvent anActionEvent) {
return getSelectedBranchName(anActionEvent);
}
@Override
public LambdaLogger log() {
return LOG;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/RediscoverSuggester.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/RediscoverSuggester.java | package com.virtuslab.gitmachete.frontend.ui.impl;
import static com.intellij.openapi.application.ModalityState.NON_MODAL;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.nio.file.Path;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.ui.MessageDialogBuilder;
import com.intellij.util.ModalityUiUtil;
import git4idea.GitReference;
import git4idea.repo.GitRepository;
import io.vavr.collection.List;
import lombok.CustomLog;
import lombok.RequiredArgsConstructor;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.branchlayout.api.BranchLayoutException;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutReader;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositoryCache;
import com.virtuslab.gitmachete.frontend.file.MacheteFileReader;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod(GitVfsUtils.class)
@CustomLog
@RequiredArgsConstructor
public class RediscoverSuggester {
private final GitRepository gitRepository;
private final Runnable queueDiscoverOperation;
private final IBranchLayoutReader branchLayoutReader = ApplicationManager.getApplication()
.getService(IBranchLayoutReader.class);
// TODO (#270): a candidate for custom settings tab
private final int DAYS_AFTER_WHICH_TO_SUGGEST_DISCOVER = 14;
@ContinuesInBackground
@UIEffect
public void perform() {
val macheteFilePath = gitRepository.getMacheteFilePath();
val lastModifiedTimeMillis = macheteFilePath.getFileModificationEpochMillis();
if (lastModifiedTimeMillis == null) {
LOG.warn("Cannot proceed with rediscover suggestion workflow - could not get file modification date");
return;
}
val daysDiff = daysDiffTillNow(lastModifiedTimeMillis);
LOG.info("Branch layout has not been modified within ${daysDiff} days");
if (daysDiff > DAYS_AFTER_WHICH_TO_SUGGEST_DISCOVER) {
LOG.info("Time diff above ${DAYS_AFTER_WHICH_TO_SUGGEST_DISCOVER}; Suggesting rediscover");
enqueueChecksAndSuggestIfApplicable(macheteFilePath);
} else {
LOG.info("Time diff below (or equal) ${DAYS_AFTER_WHICH_TO_SUGGEST_DISCOVER}; rediscover suggestion skipped");
}
}
@UIEffect
private void queueSuggestion(Path macheteFilePath) {
val yesNo = MessageDialogBuilder.yesNo(
getString("string.GitMachete.RediscoverSuggester.dialog.title"),
getString("string.GitMachete.RediscoverSuggester.dialog.question"));
if (yesNo.ask(gitRepository.getProject())) {
LOG.info("Enqueueing rediscover");
queueDiscoverOperation.run();
} else { // closing dialog goes here too
LOG.info("Rediscover declined from dialog");
refreshFileModificationDate(macheteFilePath);
}
}
/**
* This method sets the modification time of a file to current system time.
* It is used to state that the user has declined the suggestion, thus we should not ask again
* before {@link RediscoverSuggester#DAYS_AFTER_WHICH_TO_SUGGEST_DISCOVER} pass.
*/
private void refreshFileModificationDate(Path macheteFilePath) {
macheteFilePath.setFileModificationEpochMillis(System.currentTimeMillis());
}
private long daysDiffTillNow(long lastModifiedTimeMillis) {
val currentTimeMillis = System.currentTimeMillis();
val millisDiff = currentTimeMillis - lastModifiedTimeMillis;
return millisDiff / (24 * 60 * 60 * 1000);
}
@ContinuesInBackground
public void enqueueChecksAndSuggestIfApplicable(Path macheteFilePath) {
new Task.Backgroundable(
gitRepository.getProject(),
getNonHtmlString("string.GitMachete.RediscoverSuggester.backgroundable-check-task.title")) {
@UIThreadUnsafe
@Override
public void run(ProgressIndicator indicator) {
if (areAllLocalBranchesManaged(macheteFilePath) || isDiscoveredBranchLayoutEquivalentToCurrent(macheteFilePath)) {
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> refreshFileModificationDate(macheteFilePath));
} else {
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> queueSuggestion(macheteFilePath));
}
}
}.queue();
}
private boolean areAllLocalBranchesManaged(Path macheteFilePath) {
val localBranches = gitRepository.getBranches().getLocalBranches();
try {
val branchLayout = ReadAction
.<BranchLayout, BranchLayoutException>compute(
() -> MacheteFileReader.readBranchLayout(macheteFilePath, branchLayoutReader));
val localBranchNames = List.ofAll(localBranches)
.map(GitReference::getName);
return localBranchNames.forAll(branchLayout::hasEntry);
} catch (BranchLayoutException ignored) {}
return false;
}
@UIThreadUnsafe
private boolean isDiscoveredBranchLayoutEquivalentToCurrent(Path macheteFilePath) {
Path rootDirPath = gitRepository.getRootDirectoryPath().toAbsolutePath();
Path mainGitDirPath = gitRepository.getMainGitDirectoryPath().toAbsolutePath();
Path worktreeGitDirPath = gitRepository.getWorktreeGitDirectoryPath().toAbsolutePath();
try {
val discoverRunResult = ApplicationManager.getApplication().getService(IGitMacheteRepositoryCache.class)
.getInstance(rootDirPath, mainGitDirPath, worktreeGitDirPath, ApplicationManager.getApplication()::getService)
.discoverLayoutAndCreateSnapshot();
val currentBranchLayout = ReadAction
.<BranchLayout, BranchLayoutException>compute(
() -> MacheteFileReader.readBranchLayout(macheteFilePath, branchLayoutReader));
val discoveredBranchLayout = discoverRunResult.getBranchLayout();
return discoveredBranchLayout.equals(currentBranchLayout);
} catch (GitMacheteException | BranchLayoutException ignored) {}
return false;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/backgroundables/GitMacheteRepositoryUpdateBackgroundable.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/backgroundables/GitMacheteRepositoryUpdateBackgroundable.java | package com.virtuslab.gitmachete.frontend.ui.impl.backgroundables;
import static com.intellij.openapi.application.ModalityState.NON_MODAL;
import static com.virtuslab.gitmachete.frontend.file.MacheteFileUtils.isMacheteFileSelected;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.nio.file.Path;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.util.ModalityUiUtil;
import git4idea.repo.GitRepository;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.index.qual.Positive;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.branchlayout.api.BranchLayoutException;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutReader;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepository;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositoryCache;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.MacheteFileReaderException;
import com.virtuslab.gitmachete.frontend.file.MacheteFileReader;
import com.virtuslab.gitmachete.frontend.ui.impl.table.EnhancedGraphTable;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod({GitVfsUtils.class, Objects.class})
@CustomLog
public final class GitMacheteRepositoryUpdateBackgroundable extends Task.Backgroundable {
private final GitRepository gitRepository;
private final IBranchLayoutReader branchLayoutReader;
private final DoOnUIThreadWhenDone doOnUIThreadWhenDone;
private final AtomicReference<@Nullable IGitMacheteRepository> gitMacheteRepositoryHolder;
private final IGitMacheteRepositoryCache gitMacheteRepositoryCache;
@UI
public interface DoOnUIThreadWhenDone extends @UI Consumer<@Nullable IGitMacheteRepositorySnapshot> {}
/**
* A backgroundable task that reads the branch layout from the machete file and updates the
* repository snapshot, which is the base for the creation of the branch graph seen in the Git Machete IntelliJ tab.
*/
public GitMacheteRepositoryUpdateBackgroundable(
GitRepository gitRepository,
IBranchLayoutReader branchLayoutReader,
DoOnUIThreadWhenDone doOnUIThreadWhenDone,
AtomicReference<@Nullable IGitMacheteRepository> gitMacheteRepositoryHolder) {
super(gitRepository.getProject(),
getNonHtmlString("action.GitMachete.GitMacheteRepositoryUpdateBackgroundable.task-title"));
this.gitRepository = gitRepository;
this.branchLayoutReader = branchLayoutReader;
this.doOnUIThreadWhenDone = doOnUIThreadWhenDone;
this.gitMacheteRepositoryHolder = gitMacheteRepositoryHolder;
this.gitMacheteRepositoryCache = ApplicationManager.getApplication().getService(IGitMacheteRepositoryCache.class);
}
@UIThreadUnsafe
@Override
public void run(ProgressIndicator indicator) {
// We can't queue repository update (onto a non-UI thread) and `doOnUIThreadWhenDone` (onto the UI thread) separately
// since those two actions happen on two separate threads
// and `doOnUIThreadWhenDone` can only start once repository update is complete.
// Thus, we synchronously run repository update first...
IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot = updateRepositorySnapshot();
// ... and only once it completes, we queue `doOnUIThreadWhenDone` onto the UI thread.
LOG.debug("Queuing graph table refresh onto the UI thread");
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> doOnUIThreadWhenDone.accept(gitMacheteRepositorySnapshot));
}
/**
* Updates the repository snapshot which is the base of graph table model. The change will be seen after
* {@link EnhancedGraphTable#refreshModel()} completes.
*/
@UIThreadUnsafe
private @Nullable IGitMacheteRepositorySnapshot updateRepositorySnapshot() {
Path rootDirectoryPath = gitRepository.getRootDirectoryPath();
Path mainGitDirectoryPath = gitRepository.getMainGitDirectoryPath();
Path worktreeGitDirectoryPath = gitRepository.getWorktreeGitDirectoryPath();
Path macheteFilePath = gitRepository.getMacheteFilePath();
val macheteVFile = VirtualFileManager.getInstance().findFileByNioPath(macheteFilePath);
boolean isMacheteFilePresent = macheteVFile != null && !macheteVFile.isDirectory();
LOG.debug(() -> "Entering: rootDirectoryPath = ${rootDirectoryPath}, mainGitDirectoryPath = ${mainGitDirectoryPath}, " +
"macheteFilePath = ${macheteFilePath}, isMacheteFilePresent = ${isMacheteFilePresent}");
if (isMacheteFilePresent) {
LOG.debug("Machete file is present. Trying to create a repository snapshot");
try {
BranchLayout branchLayout = readBranchLayout(macheteFilePath);
IGitMacheteRepository gitMacheteRepository = gitMacheteRepositoryCache.getInstance(rootDirectoryPath,
mainGitDirectoryPath, worktreeGitDirectoryPath, ApplicationManager.getApplication()::getService);
gitMacheteRepositoryHolder.set(gitMacheteRepository);
return gitMacheteRepository.createSnapshotForLayout(branchLayout);
} catch (MacheteFileReaderException e) {
LOG.warn("Unable to create Git Machete repository", e);
if (!isMacheteFileSelected(getProject())) {
notifyUpdateRepositoryException(e);
}
return null;
} catch (GitMacheteException e) {
LOG.warn("Unable to create Git Machete repository", e);
notifyUpdateRepositoryException(e);
return null;
}
} else {
LOG.debug("Machete file is absent");
return null;
}
}
private BranchLayout readBranchLayout(Path path) throws MacheteFileReaderException {
try {
return ReadAction
.<BranchLayout, BranchLayoutException>compute(() -> MacheteFileReader.readBranchLayout(path, branchLayoutReader));
} catch (BranchLayoutException e) {
@Positive Integer errorLine = e.getErrorLine();
throw new MacheteFileReaderException("Error occurred while parsing machete file" +
(errorLine != null ? " in line ${errorLine}" : ""), e);
}
}
private void notifyUpdateRepositoryException(Throwable t) {
String exceptionMessage = ExceptionUtils.getRootCauseMessage(t).requireNonNullElse("");
VcsNotifier.getInstance(getProject()).notifyError(/* displayId */ null,
getString("action.GitMachete.GitMacheteRepositoryUpdateBackgroundable.notification.title.failed"),
exceptionMessage);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/backgroundables/AutodiscoverBackgroundable.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/backgroundables/AutodiscoverBackgroundable.java | package com.virtuslab.gitmachete.frontend.ui.impl.backgroundables;
import static com.virtuslab.gitmachete.frontend.common.WriteActionUtils.blockingRunWriteActionOnUIThread;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.nio.file.Path;
import java.util.Objects;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsNotifier;
import git4idea.repo.GitRepository;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepository;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositoryCache;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.frontend.file.MacheteFileWriter;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod({GitVfsUtils.class, Objects.class})
public abstract class AutodiscoverBackgroundable extends Task.Backgroundable {
private final Project project;
private final GitRepository gitRepository;
protected abstract void onDiscoverFailure();
@ContinuesInBackground
protected abstract void onDiscoverSuccess(IGitMacheteRepository repository, IGitMacheteRepositorySnapshot repositorySnapshot);
private final Path macheteFilePath;
public AutodiscoverBackgroundable(GitRepository gitRepository, Path macheteFilePath) {
super(gitRepository.getProject(),
getNonHtmlString("string.GitMachete.AutodiscoverBackgroundable.automatic-discover.task-title"));
this.project = gitRepository.getProject();
this.gitRepository = gitRepository;
this.macheteFilePath = macheteFilePath;
}
@Override
@ContinuesInBackground
@UIThreadUnsafe
public void run(ProgressIndicator indicator) {
if (gitRepository == null) {
return;
}
Path rootDirPath = gitRepository.getRootDirectoryPath().toAbsolutePath();
Path mainGitDirPath = gitRepository.getMainGitDirectoryPath().toAbsolutePath();
Path worktreeGitDirPath = gitRepository.getWorktreeGitDirectoryPath().toAbsolutePath();
IGitMacheteRepository repository;
try {
repository = ApplicationManager.getApplication().getService(IGitMacheteRepositoryCache.class)
.getInstance(rootDirPath, mainGitDirPath, worktreeGitDirPath, ApplicationManager.getApplication()::getService);
} catch (GitMacheteException e) {
VcsNotifier.getInstance(project)
.notifyError(
/* displayId */ null,
getString(
"string.GitMachete.EnhancedGraphTable.automatic-discover.notification.title.cannot-discover-layout-error"),
e.getMessage().requireNonNullElse(""));
return;
}
IGitMacheteRepositorySnapshot repositorySnapshot;
try {
repositorySnapshot = repository.discoverLayoutAndCreateSnapshot();
} catch (GitMacheteException e) {
VcsNotifier.getInstance(project)
.notifyError(
/* displayId */ null,
getString(
"string.GitMachete.EnhancedGraphTable.automatic-discover.notification.title.cannot-discover-layout-error"),
e.getMessage().requireNonNullElse(""));
return;
}
if (repositorySnapshot.getRootBranches().size() == 0) {
onDiscoverFailure();
return;
}
val branchLayoutWriter = ApplicationManager.getApplication().getService(IBranchLayoutWriter.class);
val branchLayout = repositorySnapshot.getBranchLayout();
blockingRunWriteActionOnUIThread(() -> {
MacheteFileWriter.writeBranchLayout(
macheteFilePath,
branchLayoutWriter,
branchLayout,
/* backupOldLayout */ true,
/* requestor */ this);
});
onDiscoverSuccess(repository, repositorySnapshot);
}
@Override
@UIEffect
public void onThrowable(Throwable e) {
onDiscoverFailure();
VcsNotifier.getInstance(project)
.notifyError(
/* displayId */ null,
getString(
"string.GitMachete.EnhancedGraphTable.automatic-discover.notification.title.cannot-discover-layout-error"),
e.getMessage().requireNonNullElse(""));
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/backgroundables/InferParentForUnmanagedBranchBackgroundable.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/backgroundables/InferParentForUnmanagedBranchBackgroundable.java | package com.virtuslab.gitmachete.frontend.ui.impl.backgroundables;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getNonHtmlString;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.util.Objects;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsNotifier;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod(Objects.class)
public abstract class InferParentForUnmanagedBranchBackgroundable extends Task.Backgroundable {
private final Project project;
public InferParentForUnmanagedBranchBackgroundable(Project project) {
super(project, getNonHtmlString("string.GitMachete.InferParentForUnmanagedBranchBackgroundable.task-title"));
this.project = project;
}
@UIThreadUnsafe
protected abstract @Nullable ILocalBranchReference inferParent() throws GitMacheteException;
protected abstract void onInferParentSuccess(ILocalBranchReference inferredParent);
@UIThreadUnsafe
public void run(ProgressIndicator indicator) {
try {
val inferredParent = inferParent();
if (inferredParent != null) {
onInferParentSuccess(inferredParent);
}
} catch (GitMacheteException e) {
VcsNotifier.getInstance(project)
.notifyError(
/* displayId */ null,
getString(
"string.GitMachete.EnhancedGraphTable.automatic-discover.notification.title.cannot-discover-layout-error"),
e.getMessage().requireNonNullElse(""));
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/root/GitMacheteContentProvider.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/root/GitMacheteContentProvider.java | package com.virtuslab.gitmachete.frontend.ui.impl.root;
import javax.swing.JComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentProvider;
import org.checkerframework.checker.guieffect.qual.UIEffect;
public class GitMacheteContentProvider implements ChangesViewContentProvider {
private final Project project;
public GitMacheteContentProvider(Project project) {
this.project = project;
}
@Override
@UIEffect
public JComponent initContent() {
return new GitMachetePanel(project);
}
@Override
public void disposeContent() {}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/root/GitMacheteVisibilityPredicate.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/root/GitMacheteVisibilityPredicate.java | package com.virtuslab.gitmachete.frontend.ui.impl.root;
import java.util.function.Predicate;
import com.intellij.openapi.project.Project;
import com.intellij.vcs.log.impl.VcsProjectLog;
import lombok.CustomLog;
@CustomLog
public class GitMacheteVisibilityPredicate implements Predicate<Project> {
@Override
public boolean test(Project project) {
boolean predicateResult = !VcsProjectLog.getLogProviders(project).isEmpty();
LOG.debug(() -> "Visibility predicate returned ${predicateResult}");
return predicateResult;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/root/GitMachetePanel.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/root/GitMachetePanel.java | package com.virtuslab.gitmachete.frontend.ui.impl.root;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.event.AncestorEvent;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.ui.AncestorListenerAdapter;
import com.intellij.ui.ScrollPaneFactory;
import lombok.CustomLog;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.frontend.defs.ActionGroupIds;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
import com.virtuslab.gitmachete.frontend.ui.api.gitrepositoryselection.IGitRepositorySelectionProvider;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable;
import com.virtuslab.gitmachete.frontend.ui.impl.RediscoverSuggester;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
@ExtensionMethod(GitVfsUtils.class)
@CustomLog
public final class GitMachetePanel extends SimpleToolWindowPanel {
private final Project project;
@UIEffect
public GitMachetePanel(Project project) {
super(/* vertical */ false, /* borderless */ true);
LOG.debug("Instantiating");
this.project = project;
val gitRepositorySelectionProvider = project.getService(IGitRepositorySelectionProvider.class);
val selectionComponent = gitRepositorySelectionProvider.getSelectionComponent();
val graphTable = getGraphTable();
// This class is final, so the instance is `@Initialized` at this point.
setToolbar(createGitMacheteVerticalToolbar(graphTable).getComponent());
add(createShrinkingWrapper(selectionComponent), BorderLayout.NORTH);
setContent(ScrollPaneFactory.createScrollPane(graphTable));
// The following listener executes on each opening of the Git Machete tab.
addAncestorListener(new AncestorListenerAdapter() {
@Override
@ContinuesInBackground
public void ancestorAdded(AncestorEvent event) {
val gitRepository = gitRepositorySelectionProvider.getSelectedGitRepository();
if (gitRepository != null) {
val macheteFilePath = gitRepository.getMacheteFilePath();
Runnable queueDiscoverOperation = () -> graphTable.queueDiscover(macheteFilePath, () -> {});
val rediscoverSuggester = new RediscoverSuggester(gitRepository, queueDiscoverOperation);
graphTable.queueRepositoryUpdateAndModelRefresh(rediscoverSuggester::perform);
}
}
});
}
public BaseEnhancedGraphTable getGraphTable() {
return project.getService(BaseEnhancedGraphTable.class);
}
@UIEffect
private static ActionToolbar createGitMacheteVerticalToolbar(BaseEnhancedGraphTable graphTable) {
val actionManager = ActionManager.getInstance();
val toolbarActionGroup = (ActionGroup) actionManager.getAction(ActionGroupIds.TOOLBAR);
val toolbar = actionManager.createActionToolbar(ActionPlaces.TOOLBAR, toolbarActionGroup, /* horizontal */ false);
toolbar.setTargetComponent(graphTable);
return toolbar;
}
@UIEffect
private static JComponent createShrinkingWrapper(JComponent component) {
final JPanel wrapper = new JPanel(new BorderLayout());
wrapper.add(component, BorderLayout.WEST);
wrapper.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
return wrapper;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/cell/BranchOrCommitCell.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/cell/BranchOrCommitCell.java | package com.virtuslab.gitmachete.frontend.ui.impl.cell;
import io.vavr.collection.List;
import lombok.Data;
import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem;
import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart;
@Data
public final class BranchOrCommitCell {
private final IGraphItem graphItem;
private final String text;
private final List<? extends IRenderPart> renderParts;
public BranchOrCommitCell(
IGraphItem graphItem,
List<? extends IRenderPart> renderParts) {
this.text = graphItem.getValue();
this.renderParts = renderParts;
this.graphItem = graphItem;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/cell/BranchOrCommitCellRenderer.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/cell/BranchOrCommitCellRenderer.java | package com.virtuslab.gitmachete.frontend.ui.impl.cell;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.guieffect.qual.UIEffect;
@RequiredArgsConstructor
public class BranchOrCommitCellRenderer implements TableCellRenderer {
private final boolean shouldDisplayActionToolTips;
@Override
@UIEffect
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
return new BranchOrCommitCellRendererComponent(table, value, isSelected, hasFocus, row, column,
shouldDisplayActionToolTips);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/cell/BranchOrCommitCellRendererComponent.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/cell/BranchOrCommitCellRendererComponent.java | package com.virtuslab.gitmachete.frontend.ui.impl.cell;
import static com.intellij.ui.SimpleTextAttributes.GRAY_ATTRIBUTES;
import static com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES;
import static com.intellij.ui.SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES;
import static com.intellij.ui.SimpleTextAttributes.STYLE_PLAIN;
import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.InSync;
import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.InSyncButForkPointOff;
import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.MergedToParent;
import static com.virtuslab.gitmachete.backend.api.SyncToParentStatus.OutOfSync;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.AheadOfRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.BehindRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.DivergedFromAndNewerThanRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.DivergedFromAndOlderThanRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.InSyncToRemote;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.NoRemotes;
import static com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus.Untracked;
import static com.virtuslab.gitmachete.frontend.defs.Colors.ORANGE;
import static com.virtuslab.gitmachete.frontend.defs.Colors.RED;
import static com.virtuslab.gitmachete.frontend.defs.Colors.TRANSPARENT;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.ui.JBColor;
import com.intellij.ui.SimpleColoredRenderer;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.paint.PaintUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcs.log.ui.render.LabelPainter;
import io.vavr.collection.List;
import lombok.Data;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.apache.commons.text.StringEscapeUtils;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.index.qual.Positive;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.IRootManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.OngoingRepositoryOperationType;
import com.virtuslab.gitmachete.backend.api.RelationToRemote;
import com.virtuslab.gitmachete.frontend.defs.Colors;
import com.virtuslab.gitmachete.frontend.graph.api.items.IBranchItem;
import com.virtuslab.gitmachete.frontend.graph.api.items.ICommitItem;
import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem;
import com.virtuslab.gitmachete.frontend.graph.api.paint.IGraphCellPainterFactory;
import com.virtuslab.gitmachete.frontend.graph.api.paint.PaintParameters;
import com.virtuslab.gitmachete.frontend.graph.api.render.parts.IRenderPart;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseGraphTable;
@ExtensionMethod({GitMacheteBundle.class, StringEscapeUtils.class})
public final class BranchOrCommitCellRendererComponent extends SimpleColoredRenderer {
private static final String CELL_TEXT_FRAGMENTS_SPACING = " ";
private static final String HEAVY_WIDE_HEADED_RIGHTWARDS_ARROW = "\u2794";
private final JTable graphTable;
private final BufferedImage graphImage;
private final MyTableCellRenderer myTableCellRenderer;
@UIEffect
@SuppressWarnings("keyfor:assignment")
public BranchOrCommitCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column,
boolean shouldDisplayActionToolTips) {
this.graphTable = table;
assert table instanceof BaseGraphTable : "`table` is not an instance of " + BaseGraphTable.class.getSimpleName();
val gitMacheteRepositorySnapshot = ((BaseGraphTable) graphTable).getGitMacheteRepositorySnapshot();
assert value instanceof BranchOrCommitCell : "`value` is not an instance of " + BranchOrCommitCell.class.getSimpleName();
val cell = (BranchOrCommitCell) value;
IGraphItem graphItem = cell.getGraphItem();
int maxGraphNodePositionInRow = getMaxGraphNodePositionInRow(graphItem);
List<? extends IRenderPart> renderParts;
if (graphItem.hasBulletPoint()) {
renderParts = cell.getRenderParts();
} else {
renderParts = cell.getRenderParts().filter(e -> !e.isNode());
}
this.graphImage = getGraphImage(graphTable, maxGraphNodePositionInRow);
Graphics2D g2 = graphImage.createGraphics();
val graphCellPainter = ApplicationManager.getApplication().getService(IGraphCellPainterFactory.class).create(table);
graphCellPainter.draw(g2, renderParts);
this.myTableCellRenderer = new MyTableCellRenderer();
// `this` is @Initialized at this point (since the class is final).
clear();
setPaintFocusBorder(false);
acquireState(table, isSelected, hasFocus, row, column);
getCellState().updateRenderer(this);
setBorder(null);
applyHighlighters(/* rendererComponent */ this, row, column, hasFocus, isSelected);
append(""); // appendTextPadding won't work without this
int textPadding = calculateTextPadding(graphTable, maxGraphNodePositionInRow);
appendTextPadding(textPadding);
if (gitMacheteRepositorySnapshot != null && graphItem.isBranchItem()) {
val repositoryOperation = gitMacheteRepositorySnapshot.getOngoingRepositoryOperation();
if (repositoryOperation.getOperationType() != OngoingRepositoryOperationType.NO_OPERATION) {
String ongoingOperationName = null;
val maybeOperationsBaseBranchName = repositoryOperation.getBaseBranchName();
if (maybeOperationsBaseBranchName != null
&& maybeOperationsBaseBranchName.equals(graphItem.getValue())) {
ongoingOperationName = switch (repositoryOperation.getOperationType()) {
case BISECTING -> getString("string.GitMachete.BranchOrCommitCellRendererComponent.ongoing-operation.bisecting");
case REBASING -> getString("string.GitMachete.BranchOrCommitCellRendererComponent.ongoing-operation.rebasing");
default -> null;
};
} else if (graphItem.asBranchItem().isCurrentBranch()) {
ongoingOperationName = switch (repositoryOperation.getOperationType()) {
case CHERRY_PICKING -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.ongoing-operation.cherry-picking");
case MERGING -> getString("string.GitMachete.BranchOrCommitCellRendererComponent.ongoing-operation.merging");
case REVERTING -> getString("string.GitMachete.BranchOrCommitCellRendererComponent.ongoing-operation.reverting");
case APPLYING -> getString("string.GitMachete.BranchOrCommitCellRendererComponent.ongoing-operation.applying");
default -> null;
};
}
if (ongoingOperationName != null) {
append(ongoingOperationName + CELL_TEXT_FRAGMENTS_SPACING, SimpleTextAttributes.ERROR_ATTRIBUTES);
}
}
}
SimpleTextAttributes attributes = graphItem.getAttributes();
append(cell.getText(), attributes);
if (graphItem.isBranchItem()) {
IBranchItem branchItem = graphItem.asBranchItem();
IManagedBranchSnapshot branch = branchItem.getBranch();
if (shouldDisplayActionToolTips) {
setBranchToolTipText(branch);
}
String customAnnotation = branch.getCustomAnnotation();
if (customAnnotation != null) {
append(CELL_TEXT_FRAGMENTS_SPACING + customAnnotation, GRAY_ATTRIBUTES);
}
String statusHookOutput = branch.getStatusHookOutput();
if (statusHookOutput != null) {
append(CELL_TEXT_FRAGMENTS_SPACING + statusHookOutput, GRAY_ATTRIBUTES);
}
RelationToRemote relationToRemote = branchItem.getRelationToRemote();
val textAttributes = new SimpleTextAttributes(STYLE_PLAIN, getColor(relationToRemote));
String relationToRemoteLabel = getRelationToRemoteBasedLabel(relationToRemote);
append(" " + relationToRemoteLabel, textAttributes);
} else {
ICommitItem commitItem = graphItem.asCommitItem();
INonRootManagedBranchSnapshot containingBranch = commitItem.getContainingBranch();
val forkPoint = containingBranch.getForkPoint();
if (commitItem.getCommit().equals(forkPoint)) {
append(
" ${HEAVY_WIDE_HEADED_RIGHTWARDS_ARROW} "
+ getString("string.GitMachete.BranchOrCommitCellRendererComponent.inferred-fork-point.fork-point") + " ",
new SimpleTextAttributes(STYLE_PLAIN, Colors.RED));
append(getString("string.GitMachete.BranchOrCommitCellRendererComponent.inferred-fork-point.commit") + " ",
REGULAR_ATTRIBUTES);
append(forkPoint.getShortHash(), REGULAR_BOLD_ATTRIBUTES);
append(" " + getString("string.GitMachete.BranchOrCommitCellRendererComponent.inferred-fork-point.found-in-reflog")
+ " ", REGULAR_ATTRIBUTES);
append(forkPoint.getUniqueBranchesContainingInReflog()
.map(b -> b.getName()).sorted().mkString(", "), REGULAR_BOLD_ATTRIBUTES);
}
}
}
@Override
@UIEffect
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// The image's origin (after the graphics translate is applied) is rounded by J2D with .5 coordinate ceil'd.
// This doesn't correspond to how the rectangle's origin is rounded, with .5 floor'd. As the result, there may be a gap
// b/w the background's top and the image's top (depending on the row number and the graphics translate). To avoid that,
// the graphics y-translate is aligned to int with .5-floor-bias.
AffineTransform origTx = PaintUtil.alignTxToInt(/* graphics2d */ g2d, /* offset */ null, /* alignX */ false,
/* alignY */ true, PaintUtil.RoundingMode.ROUND_FLOOR_BIAS);
UIUtil.drawImage(g, graphImage, 0, 0, null);
if (origTx != null) {
g2d.setTransform(origTx);
}
}
@Override
@UIEffect
public FontMetrics getFontMetrics(Font font) {
return graphTable.getFontMetrics(font);
}
private static @NonNegative int getMaxGraphNodePositionInRow(IGraphItem graphItem) {
// If item is a child (non-root) branch, then the text must be shifted right to make place
// for the corresponding the right edge to the left.
// If item is a commit, then the text must be shifted right to keep it horizontally aligned
// with the corresponding branch item.
boolean isRootBranch = graphItem.isBranchItem() && graphItem.asBranchItem().getBranch().isRoot();
return graphItem.getIndentLevel() + (isRootBranch ? 0 : 1);
}
@UIEffect
@SuppressWarnings("nullness:argument") // for GraphicsConfiguration param
private static BufferedImage getGraphImage(JTable table, @NonNegative int maxGraphNodePositionInRow) {
return UIUtil.createImage(table.getGraphicsConfiguration(),
/* width */ PaintParameters.getNodeWidth(table.getRowHeight()) * (maxGraphNodePositionInRow + 2),
/* height */ table.getRowHeight(),
BufferedImage.TYPE_INT_ARGB,
PaintUtil.RoundingMode.CEIL);
}
@UIEffect
private static @Positive int calculateTextPadding(JTable table, @NonNegative int maxPosition) {
int width = (maxPosition + 1) * PaintParameters.getNodeWidth(table.getRowHeight());
int padding = width + LabelPainter.RIGHT_PADDING.get();
// Our assumption here comes from the fact that we expect positive row height of graph table,
// hence non-negative width AND positive right padding from `LabelPainter.RIGHT_PADDING`.
assert padding > 0 : "Padding is not greater than 0";
return padding;
}
private static JBColor getColor(RelationToRemote relation) {
return switch (relation.getSyncToRemoteStatus()) {
case NoRemotes, InSyncToRemote -> TRANSPARENT;
case Untracked -> ORANGE;
case AheadOfRemote, BehindRemote, DivergedFromAndNewerThanRemote, DivergedFromAndOlderThanRemote -> RED;
};
}
private static String getRelationToRemoteBasedLabel(RelationToRemote relation) {
val maybeRemoteName = relation.getRemoteName();
val remoteName = maybeRemoteName != null ? maybeRemoteName : "";
return switch (relation.getSyncToRemoteStatus()) {
case NoRemotes, InSyncToRemote -> "";
case Untracked -> getString("string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-remote-status-text.untracked");
case AheadOfRemote -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-remote-status-text.ahead-of-remote")
.fmt(remoteName);
case BehindRemote -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-remote-status-text.behind-remote")
.fmt(remoteName);
case DivergedFromAndNewerThanRemote -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-remote-status-text.diverged-from-and-newer-than-remote")
.fmt(remoteName);
case DivergedFromAndOlderThanRemote -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-remote-status-text.diverged-from-and-older-than-remote")
.fmt(remoteName);
};
}
@UIEffect
private void setBranchToolTipText(IManagedBranchSnapshot branch) {
if (branch.isRoot()) {
setToolTipText(getRootToolTipText(branch.asRoot()));
} else {
setToolTipText(getSyncToParentStatusBasedToolTipText(branch.asNonRoot()));
}
}
private static String getSyncToParentStatusBasedToolTipText(INonRootManagedBranchSnapshot branch) {
val currentBranchName = branch.getName().escapeHtml4();
val parentBranchName = branch.getParent().getName().escapeHtml4();
return switch (branch.getSyncToParentStatus()) {
case InSync -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-parent-status-tooltip.in-sync.HTML")
.fmt(currentBranchName, parentBranchName);
case InSyncButForkPointOff -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-parent-status-tooltip.in-sync-but-fork-point-off.HTML")
.fmt(currentBranchName, parentBranchName);
case OutOfSync -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-parent-status-tooltip.out-of-sync.HTML")
.fmt(currentBranchName, parentBranchName);
case MergedToParent -> getString(
"string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-parent-status-tooltip.merged-to-parent.HTML")
.fmt(currentBranchName, parentBranchName);
};
}
private static String getRootToolTipText(IRootManagedBranchSnapshot branch) {
return getString("string.GitMachete.BranchOrCommitCellRendererComponent.sync-to-parent-status-tooltip.root.HTML")
.fmt(branch.getName());
}
private static class MyTableCellRenderer extends DefaultTableCellRenderer {
@Override
@UIEffect
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
val backgroundColor = isSelected ? UIUtil.getListSelectionBackground(table.hasFocus()) : UIUtil.getListBackground();
component.setBackground(backgroundColor);
return component;
}
}
@UIEffect
private void applyHighlighters(
Component rendererComponent,
int row,
int column,
boolean hasFocus,
final boolean selected) {
CellStyle style = getStyle(row, column, hasFocus, selected);
rendererComponent.setBackground(style.getBackground());
rendererComponent.setForeground(style.getForeground());
}
@UIEffect
private CellStyle getStyle(int row, int column, boolean hasFocus, boolean selected) {
Component dummyRendererComponent = myTableCellRenderer.getTableCellRendererComponent(
graphTable, /* value */ "", selected, hasFocus, row, column);
val background = dummyRendererComponent.getBackground();
val foreground = dummyRendererComponent.getForeground();
// Theoretically the result of getBackground/getForeground can be null.
// In our case, we have two factors that guarantee us non-null result.
// - DefaultTableCellRenderer::getTableCellRendererComponent sets the non-null values for us
// - both getters look for the non-null values from the parent component (for a cell this is the table)
assert background != null && foreground != null : "foreground or background color is null";
return new CellStyle(background, foreground);
}
@Data
private static final class CellStyle {
private final Color background;
private final Color foreground;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/gitrepositoryselection/GitRepositoryComboBox.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/gitrepositoryselection/GitRepositoryComboBox.java | package com.virtuslab.gitmachete.frontend.ui.impl.gitrepositoryselection;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import com.intellij.dvcs.DvcsUtil;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.dvcs.repo.VcsRepositoryMappingListener;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.ComboboxSpeedSearch;
import com.intellij.ui.MutableCollectionComboBoxModel;
import com.intellij.ui.SimpleListCellRenderer;
import com.intellij.util.ModalityUiUtil;
import com.intellij.util.SmartList;
import git4idea.GitUtil;
import git4idea.repo.GitRepository;
import io.vavr.collection.List;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.SafeEffect;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.frontend.ui.api.gitrepositoryselection.IGitRepositorySelectionChangeObserver;
import com.virtuslab.gitmachete.frontend.ui.api.gitrepositoryselection.IGitRepositorySelectionProvider;
@CustomLog
public final class GitRepositoryComboBox extends JComboBox<GitRepository>
implements
Disposable,
IGitRepositorySelectionProvider {
private final java.util.List<IGitRepositorySelectionChangeObserver> observers = new SmartList<>();
private final Project project;
@UIEffect
public GitRepositoryComboBox(Project project) {
super(new MutableCollectionComboBoxModel<>());
this.project = project;
updateRepositories();
setRenderer(SimpleListCellRenderer.create( /* nullValue */ "", DvcsUtil::getShortRepositoryName));
val messageBusConnection = project.getMessageBus().connect();
messageBusConnection
.<VcsRepositoryMappingListener>subscribe(VcsRepositoryManager.VCS_REPOSITORY_MAPPING_UPDATED, () -> {
LOG.debug("Git repository mappings changed");
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, () -> updateRepositories());
});
Disposer.register(this, messageBusConnection);
ComboboxSpeedSearch.installSpeedSearch(this, DvcsUtil::getShortRepositoryName);
}
@Override
@SafeEffect
public MutableCollectionComboBoxModel<GitRepository> getModel() {
return (MutableCollectionComboBoxModel<GitRepository>) super.getModel();
}
@UIEffect
private void updateRepositories() {
val repositories = List.ofAll(GitUtil.getRepositories(project));
LOG.debug("Git repositories:");
repositories.forEach(r -> LOG.debug("* ${r.getRoot().getName()}"));
// `com.intellij.ui.MutableCollectionComboBoxModel.getSelected` must be performed
// before `com.intellij.ui.MutableCollectionComboBoxModel.update`
// because the update method sets the selected item to null
val selected = getModel().getSelected();
if (!getModel().getItems().equals(repositories)) {
getModel().update(DvcsUtil.sortRepositories(repositories.asJavaMutable()));
}
this.setVisible(getModel().getItems().size() > 1);
val selectedItemUpdateRequired = selected == null || !getModel().getItems().contains(selected);
if (repositories.isEmpty()) {
LOG.debug("No Git repositories found");
if (selected != null) {
setSelectedItem(null);
}
} else if (selectedItemUpdateRequired) {
LOG.debug("Selecting first Git repository");
setSelectedItem(repositories.get(0));
} else {
LOG.debug("Selecting previously selected Git repository");
// GitRepositoryComboBox#setSelectedItem is omitted to avoid unnecessary observers call
getModel().setSelectedItem(selected);
}
}
@Override
public @Nullable GitRepository getSelectedGitRepository() {
return getModel().getSelected();
}
@Override
@UIEffect
public void setSelectedItem(@Nullable Object anObject) {
super.setSelectedItem(anObject);
observers.forEach(o -> o.onSelectionChanged());
}
public void addSelectionChangeObserver(IGitRepositorySelectionChangeObserver observer) {
observers.add(observer);
}
@Override
public JComponent getSelectionComponent() {
return this;
}
@Override
public void dispose() {
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/SimpleGraphTable.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/SimpleGraphTable.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import javax.swing.ListSelectionModel;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.ui.ScrollingUtil;
import com.intellij.util.ui.JBUI;
import lombok.Getter;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.NullGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraphCache;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseGraphTable;
import com.virtuslab.gitmachete.frontend.ui.impl.cell.BranchOrCommitCell;
import com.virtuslab.gitmachete.frontend.ui.impl.cell.BranchOrCommitCellRenderer;
public final class SimpleGraphTable extends BaseGraphTable {
@Getter
private final IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot = NullGitMacheteRepositorySnapshot.getInstance();
@UIEffect
public static SimpleGraphTable deriveInstance(IGitMacheteRepositorySnapshot macheteRepositorySnapshot,
boolean isListingCommitsEnabled, boolean shouldDisplayActionToolTips) {
// We can keep the data - graph table model,
// but wee need to reinstantiate the UI - demo graph table.
return new SimpleGraphTable(deriveGraphTableModel(macheteRepositorySnapshot, isListingCommitsEnabled),
shouldDisplayActionToolTips);
}
@UIEffect
private static GraphTableModel deriveGraphTableModel(IGitMacheteRepositorySnapshot macheteRepositorySnapshot,
boolean isListingCommitsEnabled) {
val repositoryGraphCache = ApplicationManager.getApplication().getService(IRepositoryGraphCache.class);
val repositoryGraph = repositoryGraphCache.getRepositoryGraph(macheteRepositorySnapshot, isListingCommitsEnabled);
return new GraphTableModel(repositoryGraph);
}
@UIEffect
private SimpleGraphTable(GraphTableModel graphTableModel, boolean shouldDisplayActionToolTips) {
super(graphTableModel);
createDefaultColumnsFromModel();
// Otherwise sizes would be recalculated after each TableColumn re-initialization
setAutoCreateColumnsFromModel(false);
setCellSelectionEnabled(false);
setColumnSelectionAllowed(false);
setRowSelectionAllowed(true);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setDefaultRenderer(BranchOrCommitCell.class, new BranchOrCommitCellRenderer(shouldDisplayActionToolTips));
setShowVerticalLines(false);
setShowHorizontalLines(false);
setIntercellSpacing(JBUI.emptySize());
setTableHeader(new InvisibleResizableHeader());
getColumnModel().setColumnSelectionAllowed(false);
ScrollingUtil.installActions(/* table */ this, /* cycleScrolling */ false);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/GraphTableModel.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/GraphTableModel.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import javax.swing.table.AbstractTableModel;
import lombok.AllArgsConstructor;
import org.checkerframework.checker.index.qual.NonNegative;
import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem;
import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraph;
import com.virtuslab.gitmachete.frontend.ui.impl.cell.BranchOrCommitCell;
@AllArgsConstructor
public class GraphTableModel extends AbstractTableModel {
private static final int BRANCH_OR_COMMIT_COLUMN = 0;
private static final int COLUMN_COUNT = BRANCH_OR_COMMIT_COLUMN + 1;
private static final String[] COLUMN_NAMES = {"Branch or Commit value"};
private final IRepositoryGraph repositoryGraph;
@Override
public @NonNegative int getRowCount() {
return repositoryGraph.getNodesCount();
}
@Override
public @NonNegative int getColumnCount() {
return COLUMN_COUNT;
}
@Override
public Object getValueAt(@NonNegative int rowIndex, @NonNegative int columnIndex) {
if (columnIndex == BRANCH_OR_COMMIT_COLUMN) {
IGraphItem graphItem = repositoryGraph.getGraphItem(rowIndex);
return new BranchOrCommitCell(graphItem, repositoryGraph.getRenderParts(rowIndex));
}
throw new IllegalArgumentException("columnIndex is ${columnIndex} > ${getColumnCount() - 1}");
}
@Override
public Class<?> getColumnClass(int column) {
if (column == BRANCH_OR_COMMIT_COLUMN) {
return BranchOrCommitCell.class;
}
throw new IllegalArgumentException("columnIndex is ${column} > ${getColumnCount() - 1}");
}
@Override
@SuppressWarnings({"index:array.access.unsafe.high", "index:array.access.unsafe.low"})
public String getColumnName(int column) {
return COLUMN_NAMES[column];
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/DemoGitMacheteRepositorySnapshot.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/DemoGitMacheteRepositorySnapshot.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import java.nio.file.Path;
import java.time.Instant;
import io.vavr.NotImplementedError;
import io.vavr.collection.List;
import io.vavr.collection.Set;
import io.vavr.collection.TreeSet;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.value.qual.ArrayLen;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.api.IForkPointCommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.IGitRebaseParameters;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.IRemoteTrackingBranchReference;
import com.virtuslab.gitmachete.backend.api.IRootManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.OngoingRepositoryOperationType;
import com.virtuslab.gitmachete.backend.api.RelationToRemote;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus;
public class DemoGitMacheteRepositorySnapshot implements IGitMacheteRepositorySnapshot {
private final List<IRootManagedBranchSnapshot> roots;
public DemoGitMacheteRepositorySnapshot() {
val nullPointedCommit = new Commit("");
val fp = new FpCommit("Fork point commit");
NonRoot[] nonRoots = {
new NonRoot(/* name */ "allow-ownership-link",
/* fullName */ "refs/heads/allow-ownership-link",
/* customAnnotation */ "# Gray edge: branch is merged to its parent branch",
nullPointedCommit,
/* forkPoint */ null,
/* childBranches */ List.empty(),
/* commits */ List.empty(),
SyncToParentStatus.MergedToParent),
new NonRoot(/* name */ "build-chain",
/* fullName */ "refs/heads/build-chain",
/* customAnnotation */ "# Green edge: branch is in sync with its parent branch",
nullPointedCommit,
/* forkPoint */ null,
/* childBranches */ List.empty(),
/* commits */ List.of(new Commit("Second commit of build-chain"),
new Commit("First commit of build-chain")),
SyncToParentStatus.InSync),
new NonRoot(/* name */ "call-ws",
/* fullName */ "refs/heads/call-ws",
/* customAnnotation */ "# Yellow edge: Branch is in sync with its parent branch but the fork point is NOT equal to parent branch",
nullPointedCommit,
/* forkPoint */ fp,
/* childBranches */ List.empty(),
/* commits */ List.of(fp),
SyncToParentStatus.InSyncButForkPointOff),
new NonRoot(/* name */ "remove-ff",
/* fullName */ "refs/heads/remove-ff",
/* customAnnotation */ "# Red edge: branch is out of sync to its parent branch",
nullPointedCommit,
/* forkPoint */ null,
/* childBranches */ List.empty(),
/* commits */ List.of(new Commit("Some commit")),
SyncToParentStatus.OutOfSync)
};
val root = new Root(/* name */ "develop",
/* fullName */ "refs/heads/develop",
/* customAnnotation */ "# This is a root branch, the underline indicates that it is the currently checked out branch",
nullPointedCommit,
/* childBranches */ List.of(nonRoots));
for (val nr : nonRoots) {
nr.setParent(root);
}
this.roots = List.of(root);
}
static RelationToRemote getRelationOfSTRS(SyncToRemoteStatus syncToRemoteStatus) {
return RelationToRemote.of(syncToRemoteStatus, "origin");
}
@Override
public Path getMainGitDirectoryPath() {
return Path.of("dummy");
}
@Override
public BranchLayout getBranchLayout() {
throw new NotImplementedError();
}
@Override
public List<IRootManagedBranchSnapshot> getRootBranches() {
return roots;
}
@Override
public @Nullable IManagedBranchSnapshot getCurrentBranchIfManaged() {
return roots.headOption().getOrNull();
}
@Override
public List<IManagedBranchSnapshot> getManagedBranches() {
throw new NotImplementedError();
}
@Override
public @Nullable IManagedBranchSnapshot getManagedBranchByName(@Nullable String branchName) {
throw new NotImplementedError();
}
@Override
public Set<String> getDuplicatedBranchNames() {
return TreeSet.empty();
}
@Override
public Set<String> getSkippedBranchNames() {
return TreeSet.empty();
}
@Getter
public final OngoingRepositoryOperation ongoingRepositoryOperation = new OngoingRepositoryOperation(
OngoingRepositoryOperationType.NO_OPERATION, null);
@AllArgsConstructor
private static class Commit implements ICommitOfManagedBranch {
private final String msg;
@Override
public String getShortMessage() {
return msg;
}
@Override
public String getFullMessage() {
throw new NotImplementedError();
}
@Override
public @ArrayLen(40) String getHash() {
throw new NotImplementedError();
}
@Override
public @ArrayLen(7) String getShortHash() {
throw new NotImplementedError();
}
@Override
public Instant getCommitTime() {
throw new NotImplementedError();
}
}
@Getter
@RequiredArgsConstructor
private static final class LocalBranchRef implements ILocalBranchReference {
private final String name;
@Override
public String getFullName() {
return "refs/heads/" + getName();
}
}
private static final class FpCommit extends Commit implements IForkPointCommitOfManagedBranch {
FpCommit(String msg) {
super(msg);
}
@Override
public @ArrayLen(7) String getShortHash() {
return "1461ce9";
}
@Override
public List<IBranchReference> getBranchesContainingInReflog() {
return List.of(new LocalBranchRef("some-other-branch"));
}
@Override
public List<IBranchReference> getUniqueBranchesContainingInReflog() {
return getBranchesContainingInReflog();
}
@Override
public boolean isOverridden() {
return false;
}
}
@Getter
@RequiredArgsConstructor
private static final class Root implements IRootManagedBranchSnapshot {
private final String name;
private final String fullName;
private final String customAnnotation;
private final Commit pointedCommit;
private final RelationToRemote relationToRemote = getRelationOfSTRS(SyncToRemoteStatus.InSyncToRemote);
private final List<INonRootManagedBranchSnapshot> children;
@Override
public @Nullable String getCustomAnnotation() {
return customAnnotation;
}
@Override
public @Nullable String getStatusHookOutput() {
return null;
}
@Override
public @Nullable IRemoteTrackingBranchReference getRemoteTrackingBranch() {
return null;
}
}
@Getter
@RequiredArgsConstructor
private static final class NonRoot implements INonRootManagedBranchSnapshot {
private final String name;
private final String fullName;
private final String customAnnotation;
private final Commit pointedCommit;
private final @Nullable IForkPointCommitOfManagedBranch forkPoint;
private final RelationToRemote relationToRemote = getRelationOfSTRS(SyncToRemoteStatus.InSyncToRemote);
private final List<INonRootManagedBranchSnapshot> children;
private final List<ICommitOfManagedBranch> uniqueCommits;
private final List<ICommitOfManagedBranch> commitsUntilParent = List.empty();
@MonotonicNonNull
private IManagedBranchSnapshot parent = null;
private final SyncToParentStatus syncToParentStatus;
@Override
public IManagedBranchSnapshot getParent() {
assert parent != null : "parentBranch hasn't been set yet";
return parent;
}
void setParent(IManagedBranchSnapshot givenParentBranch) {
assert parent == null : "parentBranch has already been set";
parent = givenParentBranch;
}
@Override
public @Nullable String getCustomAnnotation() {
return customAnnotation;
}
@Override
public @Nullable String getStatusHookOutput() {
return null;
}
@Override
public @Nullable IForkPointCommitOfManagedBranch getForkPoint() {
return forkPoint;
}
@Override
public IGitRebaseParameters getParametersForRebaseOntoParent() {
throw new NotImplementedError();
}
@Override
public @Nullable IRemoteTrackingBranchReference getRemoteTrackingBranch() {
return null;
}
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/SimpleGraphTableProvider.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/SimpleGraphTableProvider.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseGraphTable;
import com.virtuslab.gitmachete.frontend.ui.api.table.ISimpleGraphTableProvider;
public class SimpleGraphTableProvider implements ISimpleGraphTableProvider {
@Override
@UIEffect
public BaseGraphTable deriveInstance(IGitMacheteRepositorySnapshot macheteRepositorySnapshot,
boolean isListingCommitsEnabled, boolean shouldDisplayActionToolTips) {
// The reinstantiation is needed every time because without it
// the table keeps the first IDE theme despite the theme changes.
return SimpleGraphTable.deriveInstance(macheteRepositorySnapshot, isListingCommitsEnabled, shouldDisplayActionToolTips);
}
@Override
@UIEffect
public BaseGraphTable deriveDemoInstance() {
return deriveInstance(new DemoGitMacheteRepositorySnapshot(), /* isListingCommitsEnabled */ true,
/* shouldDisplayActionToolTips */ false);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/UnmanagedBranchNotification.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/UnmanagedBranchNotification.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.vcs.VcsNotifier;
import lombok.Getter;
import lombok.experimental.ExtensionMethod;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
@ExtensionMethod(GitMacheteBundle.class)
public class UnmanagedBranchNotification extends Notification {
@Getter
private final String branchName;
UnmanagedBranchNotification(String branchName) {
super(VcsNotifier.STANDARD_NOTIFICATION.getDisplayId(),
getString("action.GitMachete.EnhancedGraphTable.unmanaged-branch-notification.text").fmt(branchName),
NotificationType.INFORMATION);
this.branchName = branchName;
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/EnhancedGraphTablePopupMenuListener.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/EnhancedGraphTablePopupMenuListener.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import static com.intellij.openapi.application.ModalityState.NON_MODAL;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.event.PopupMenuEvent;
import com.intellij.ui.PopupMenuListenerAdapter;
import com.intellij.util.ModalityUiUtil;
import org.checkerframework.checker.guieffect.qual.UIEffect;
class EnhancedGraphTablePopupMenuListener extends PopupMenuListenerAdapter {
private final EnhancedGraphTable graphTable;
@UIEffect
EnhancedGraphTablePopupMenuListener(EnhancedGraphTable graphTable) {
this.graphTable = graphTable;
}
@Override
@UIEffect
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
// This delay is needed to avoid `focus transfer` effect when at the beginning row selection is light-blue,
// but when the context menu is created (in a fraction of a second),
// selection loses focus on the context menu and becomes dark blue.
// TimerTask can't be replaced by lambda because it's not a SAM (single abstract method).
// For more details see https://stackoverflow.com/a/37970821/10116324.
new Timer().schedule(new TimerTask() {
@Override
public void run() {
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> graphTable.setRowSelectionAllowed(true));
}
}, /* delay in ms */ 35);
}
@Override
@UIEffect
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
graphTable.setRowSelectionAllowed(false);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/EnhancedGraphTable.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/EnhancedGraphTable.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import static com.intellij.openapi.application.ModalityState.NON_MODAL;
import static com.virtuslab.gitmachete.frontend.datakeys.DataKeys.typeSafeCase;
import static com.virtuslab.gitmachete.frontend.defs.ActionIds.OPEN_MACHETE_FILE;
import static com.virtuslab.gitmachete.frontend.file.MacheteFileUtils.isMacheteFileSelected;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static com.virtuslab.gitmachete.frontend.ui.impl.backgroundables.GitMacheteRepositoryUpdateBackgroundable.DoOnUIThreadWhenDone;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import java.io.IOException;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.ListSelectionModel;
import com.intellij.ide.DataManager;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationAction;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.ui.ScrollingUtil;
import com.intellij.util.ModalityUiUtil;
import com.intellij.util.messages.Topic;
import com.intellij.util.ui.JBUI;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryChangeListener;
import io.vavr.collection.Set;
import io.vavr.control.Option;
import lombok.AccessLevel;
import lombok.CustomLog;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.AlwaysSafe;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutReader;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutWriter;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepository;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.NullGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.frontend.common.WriteActionUtils;
import com.virtuslab.gitmachete.frontend.datakeys.DataKeys;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
import com.virtuslab.gitmachete.frontend.defs.FileTypeIds;
import com.virtuslab.gitmachete.frontend.file.MacheteFileWriter;
import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraph;
import com.virtuslab.gitmachete.frontend.graph.api.repository.IRepositoryGraphCache;
import com.virtuslab.gitmachete.frontend.graph.api.repository.NullRepositoryGraph;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
import com.virtuslab.gitmachete.frontend.ui.api.gitrepositoryselection.IGitRepositorySelectionProvider;
import com.virtuslab.gitmachete.frontend.ui.api.table.BaseEnhancedGraphTable;
import com.virtuslab.gitmachete.frontend.ui.impl.backgroundables.AutodiscoverBackgroundable;
import com.virtuslab.gitmachete.frontend.ui.impl.backgroundables.GitMacheteRepositoryUpdateBackgroundable;
import com.virtuslab.gitmachete.frontend.ui.impl.backgroundables.InferParentForUnmanagedBranchBackgroundable;
import com.virtuslab.gitmachete.frontend.ui.impl.cell.BranchOrCommitCell;
import com.virtuslab.gitmachete.frontend.ui.impl.cell.BranchOrCommitCellRenderer;
import com.virtuslab.gitmachete.frontend.vfsutils.GitVfsUtils;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.async.DoesNotContinueInBackground;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
/**
* This class compared to {@link SimpleGraphTable} has graph table refreshing and provides
* data like last clicked branch name, opened project or {@link IGitMacheteRepositorySnapshot} of current
* repository for actions.
*/
@ExtensionMethod({GitMacheteBundle.class, GitVfsUtils.class})
@CustomLog
public final class EnhancedGraphTable extends BaseEnhancedGraphTable
implements
DataProvider,
Disposable {
private final AtomicBoolean enqueuingUpdatesEnabled = new AtomicBoolean(true);
@Getter(AccessLevel.PACKAGE)
private final Project project;
private final IBranchLayoutReader branchLayoutReader;
private final IBranchLayoutWriter branchLayoutWriter;
private final IRepositoryGraphCache repositoryGraphCache;
@Getter
@Setter
@UIEffect
private boolean isListingCommits;
@Getter
@UIEffect
private @Nullable IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot;
@Getter(AccessLevel.PACKAGE)
@Setter(AccessLevel.PACKAGE)
@UIEffect
private @Nullable String selectedBranchName;
// To accurately track the change of the current branch from the beginning, let's put something impossible
// as a branch name. This is required to detect the moment when the unmanaged branch notification should be shown.
@UIEffect
private String mostRecentlyCheckedOutBranch = "?!@#$%^&";
@UIEffect
private @MonotonicNonNull UnmanagedBranchNotification unmanagedBranchNotification;
private final AtomicReference<@Nullable IGitMacheteRepository> gitMacheteRepositoryRef = new AtomicReference<>(null);
@UIEffect
public EnhancedGraphTable(Project project) {
super(new GraphTableModel(NullRepositoryGraph.getInstance()));
this.project = project;
this.branchLayoutReader = ApplicationManager.getApplication().getService(IBranchLayoutReader.class);
this.branchLayoutWriter = ApplicationManager.getApplication().getService(IBranchLayoutWriter.class);
this.repositoryGraphCache = ApplicationManager.getApplication().getService(IRepositoryGraphCache.class);
this.isListingCommits = false;
// InitializationChecker allows us to invoke the below methods because the class is final
// and all `@NonNull` fields are already initialized. `this` is already `@Initialized` (and not just
// `@UnderInitialization(EnhancedGraphTable.class)`, as would be with a non-final class) at this point.
initColumns();
setCellSelectionEnabled(false);
setColumnSelectionAllowed(false);
setRowSelectionAllowed(false);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setDefaultRenderer(BranchOrCommitCell.class, new BranchOrCommitCellRenderer(/* shouldDisplayActionToolTips */ true));
setShowVerticalLines(false);
setShowHorizontalLines(false);
setIntercellSpacing(JBUI.emptySize());
setTableHeader(new InvisibleResizableHeader());
getColumnModel().setColumnSelectionAllowed(false);
ScrollingUtil.installActions(/* table */ this, /* cycleScrolling */ false);
addMouseListener(new EnhancedGraphTableMouseAdapter( /* outer */ this));
subscribeToGitRepositoryFilesChanges();
subscribeToSelectedGitRepositoryChange();
subscribeToMacheteFileChange();
// This is necessary since 2023.3, see https://github.com/VirtusLab/git-machete-intellij-plugin/issues/1784
getRowHeight();
}
/**
* This function is provided only for use with UiTests, to ensure that VFS notices
* the external change to the machete file made by the test.
*/
public void refreshMacheteFile() {
val gitRepositorySelectionProvider = getGitRepositorySelectionProvider();
val gitRepository = gitRepositorySelectionProvider.getSelectedGitRepository();
if (gitRepository != null) {
Path macheteFilePath = gitRepository.getMacheteFilePath();
val macheteVFile = VirtualFileManager.getInstance().findFileByNioPath(macheteFilePath);
if (macheteVFile != null) {
macheteVFile.refresh(/* asynchronous */ false, /* recursive */ false);
}
}
}
private IGitRepositorySelectionProvider getGitRepositorySelectionProvider() {
return project.getService(IGitRepositorySelectionProvider.class);
}
private void subscribeToMacheteFileChange() {
val messageBusConnection = project.getMessageBus().connect();
messageBusConnection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() {
@Override
@ContinuesInBackground
@UIEffect
public void after(java.util.List<? extends VFileEvent> events) {
for (val event : events) {
if (event instanceof VFileContentChangeEvent vfccEvent) {
if (vfccEvent.getFile().getFileType().getName().equals(FileTypeIds.NAME)) {
if (unmanagedBranchNotification != null && !unmanagedBranchNotification.isExpired()) {
unmanagedBranchNotification.expire();
}
queueRepositoryUpdateAndModelRefresh();
}
}
}
}
});
Disposer.register(this, messageBusConnection);
}
@DoesNotContinueInBackground(reason = "because the call to trackCurrentBranchChange happens in listener")
@UIEffect
private void subscribeToGitRepositoryFilesChanges() {
Topic<GitRepositoryChangeListener> topic = GitRepository.GIT_REPO_CHANGE;
// Let's explicitly mark this listener as @AlwaysSafe
// as we've checked experimentally that there is no guarantee that it'll run on UI thread.
@AlwaysSafe GitRepositoryChangeListener listener = repository -> ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL,
() -> trackCurrentBranchChange(repository));
val messageBusConnection = project.getMessageBus().connect();
messageBusConnection.subscribe(topic, listener);
Disposer.register(this, messageBusConnection);
}
@ContinuesInBackground
private void inferParentForUnmanagedBranchNotificationAndNotify(String branchName) {
if (!enqueuingUpdatesEnabled.get()) {
LOG.debug("Enqueuing updates disabled");
return;
}
val gitRepositorySelectionProvider = getGitRepositorySelectionProvider();
val gitRepository = gitRepositorySelectionProvider.getSelectedGitRepository();
if (gitRepository == null) {
LOG.warn("Selected repository is null");
return;
}
Path macheteFilePath = gitRepository.getMacheteFilePath();
val macheteVFile = VirtualFileManager.getInstance().findFileByNioPath(macheteFilePath);
boolean isMacheteFilePresent = macheteVFile != null && !macheteVFile.isDirectory();
if (!isMacheteFilePresent) {
LOG.warn("Machete file (${macheteFilePath}) is absent, so no unmanaged branch notification will show up");
return;
}
val repository = gitMacheteRepositoryRef.get();
if (repository == null) {
LOG.warn("gitMacheteRepository is null, so no unmanaged branch notification will show up");
return;
}
if (gitMacheteRepositorySnapshot == null) {
LOG.warn("gitMacheteRepositorySnapshot is null, so no unmanaged branch notification will show up");
return;
}
val eligibleLocalBranchNames = gitMacheteRepositorySnapshot.getManagedBranches().map(IManagedBranchSnapshot::getName)
.toSet();
new InferParentForUnmanagedBranchBackgroundable(project) {
@Override
@UIThreadUnsafe
protected @Nullable ILocalBranchReference inferParent() throws GitMacheteException {
return repository.inferParentForLocalBranch(eligibleLocalBranchNames, branchName);
}
@Override
protected void onInferParentSuccess(ILocalBranchReference inferredParent) {
notifyAboutUnmanagedBranch(inferredParent, branchName);
}
}.queue();
}
private void notifyAboutUnmanagedBranch(ILocalBranchReference inferredParent, String branchName) {
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> {
val showForThisProject = UnmanagedBranchNotificationFactory.shouldShowForThisProject(project);
val showForThisBranch = UnmanagedBranchNotificationFactory.shouldShowForThisBranch(project, branchName);
if (showForThisProject && showForThisBranch) {
val notification = new UnmanagedBranchNotificationFactory(project, gitMacheteRepositorySnapshot, branchName,
inferredParent).create();
VcsNotifier.getInstance(project).notify(notification);
unmanagedBranchNotification = notification;
}
});
}
// This method can only be executed on UI thread since it writes certain field(s)
// which we only ever want to write on UI thread to avoid race conditions.
@ContinuesInBackground
@UIEffect
private void trackCurrentBranchChange(GitRepository repository) {
val repositoryCurrentBranch = repository.getCurrentBranch();
if (repositoryCurrentBranch != null) {
val repositoryCurrentBranchName = repositoryCurrentBranch.getName();
if (!repositoryCurrentBranchName.equals(mostRecentlyCheckedOutBranch)) {
if (unmanagedBranchNotification != null) {
unmanagedBranchNotification.expire();
}
val snapshot = gitMacheteRepositorySnapshot;
Path mainGitDirectory = GitVfsUtils.getMainGitDirectory(repository).toNioPath();
// 1. As for now, only the snapshot of the repository selected in Git Machete panel is available
// (not all snapshots of all repositories!).
// 2. The unmanaged branch notification works on the same snapshot as the one selected in Git Machete panel.
// Hence, we must assure that the current branch changed belongs to the same repository as the given snapshot.
// TODO (#1542): Handling of all repositories (not only selected) is a subject to improvement.
if (snapshot != null && snapshot.getMainGitDirectoryPath().equals(mainGitDirectory)) {
val entry = snapshot.getBranchLayout().getEntryByName(repositoryCurrentBranchName);
if (entry == null) {
inferParentForUnmanagedBranchNotificationAndNotify(repositoryCurrentBranchName);
}
}
mostRecentlyCheckedOutBranch = repositoryCurrentBranchName;
}
}
// required to indicate the currently checked out branch after a checkout
queueRepositoryUpdateAndModelRefresh();
}
@DoesNotContinueInBackground(reason = "because the call to queueRepositoryUpdateAndModelRefresh happens in listener")
private void subscribeToSelectedGitRepositoryChange() {
// The method reference is invoked when user changes repository in the selection component menu
val gitRepositorySelectionProvider = getGitRepositorySelectionProvider();
gitRepositorySelectionProvider.addSelectionChangeObserver(() -> queueRepositoryUpdateAndModelRefresh());
}
@ContinuesInBackground
@UIEffect
private void refreshModel(
GitRepository gitRepository,
IGitMacheteRepositorySnapshot repositorySnapshot,
@UI Runnable doOnUIThreadWhenReady) {
if (!project.isInitialized() || ApplicationManager.getApplication().isUnitTestMode()) {
LOG.debug("Project is not initialized or application is in unit test mode. Returning.");
return;
}
Path macheteFilePath = gitRepository.getMacheteFilePath();
val macheteVFile = VirtualFileManager.getInstance().findFileByNioPath(macheteFilePath);
boolean isMacheteFilePresent = macheteVFile != null && !macheteVFile.isDirectory();
LOG.debug(() -> "Entering: macheteFilePath = ${macheteFilePath}, isMacheteFilePresent = ${isMacheteFilePresent}, " +
"isListingCommits = ${isListingCommits}");
IRepositoryGraph repositoryGraph;
val snapshot = gitMacheteRepositorySnapshot;
if (snapshot == null) {
repositoryGraph = NullRepositoryGraph.getInstance();
} else {
repositoryGraph = repositoryGraphCache.getRepositoryGraph(snapshot, isListingCommits);
if (snapshot.getRootBranches().isEmpty()) {
if (snapshot.getSkippedBranchNames().isEmpty()) {
LOG.info("Machete file (${macheteFilePath}) is empty");
setTextForEmptyTable(
getString("string.GitMachete.EnhancedGraphTable.empty-table-text.try-running-discover")
.fmt(macheteFilePath.toString()));
return;
} else {
setTextForEmptyTable(
getString("string.GitMachete.EnhancedGraphTable.empty-table-text.only-skipped-in-machete-file")
.fmt(macheteFilePath.toString()));
}
}
}
if (!isMacheteFilePresent) {
LOG.info("Machete file (${macheteFilePath}) is absent, so auto discover is running");
// The `doOnUIThreadWhenReady` callback must be executed once the discover task is *complete*,
// and not just when the discover task is *enqueued*.
// Otherwise, it'll most likely happen that the callback executes before the discover task is complete,
// which is undesirable.
queueDiscover(macheteFilePath, doOnUIThreadWhenReady);
return;
}
setModel(new GraphTableModel(repositoryGraph));
if (!isMacheteFileSelected(project)) {
// notify if a branch listed in the machete file does not exist
Set<String> skippedBranchNames = repositorySnapshot.getSkippedBranchNames();
if (skippedBranchNames.nonEmpty()) {
val notification = getSkippedBranchesNotification(repositorySnapshot, gitRepository);
VcsNotifier.getInstance(project).notify(notification);
}
// notify if a branch name listed in the machete file appears more than once
Set<String> duplicatedBranchNames = repositorySnapshot.getDuplicatedBranchNames();
if (duplicatedBranchNames.nonEmpty()) {
// This warning notification will not cover other error notifications (e.g. when rebase errors occur)
VcsNotifier.getInstance(project).notifyWarning(/* displayId */ null,
getString("string.GitMachete.EnhancedGraphTable.duplicated-branches-text"),
String.join(", ", duplicatedBranchNames));
}
}
repaint();
revalidate();
doOnUIThreadWhenReady.run();
}
private Notification getSkippedBranchesNotification(IGitMacheteRepositorySnapshot repositorySnapshot,
GitRepository gitRepository) {
val notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification(
getString("string.GitMachete.EnhancedGraphTable.skipped-branches-text")
.fmt(String.join(", ", repositorySnapshot.getSkippedBranchNames())),
NotificationType.WARNING);
notification.addAction(NotificationAction.createSimple(
getString("action.GitMachete.EnhancedGraphTable.automatic-discover.slide-out-skipped"), () -> {
notification.expire();
slideOutSkippedBranches(repositorySnapshot, gitRepository);
}));
notification.addAction(NotificationAction.createSimple(
getString("action.GitMachete.OpenMacheteFileAction.description"), () -> {
val actionEvent = createAnActionEvent();
ActionManager.getInstance().getAction(OPEN_MACHETE_FILE).actionPerformed(actionEvent);
}));
return notification;
}
private void slideOutSkippedBranches(IGitMacheteRepositorySnapshot repositorySnapshot, GitRepository gitRepository) {
BranchLayout newBranchLayout = repositorySnapshot.getBranchLayout();
for (val branchName : repositorySnapshot.getSkippedBranchNames()) {
newBranchLayout = newBranchLayout.slideOut(branchName);
}
val finalNewBranchLayout = newBranchLayout;
WriteActionUtils.<RuntimeException>blockingRunWriteActionOnUIThread(() -> {
try {
Path macheteFilePath = gitRepository.getMacheteFilePath();
LOG.info("Writing new branch layout into ${macheteFilePath}");
MacheteFileWriter.writeBranchLayout(
macheteFilePath,
branchLayoutWriter,
finalNewBranchLayout,
/* backupOldLayout */ true,
/* requestor */ this);
} catch (IOException e) {
String exceptionMessage = e.getMessage();
String errorMessage = "Error occurred while sliding out skipped branches" +
(exceptionMessage == null ? "" : ": " + exceptionMessage);
LOG.error(errorMessage, e);
VcsNotifier.getInstance(project).notifyError(/* displayId */ null,
getString("action.GitMachete.EnhancedGraphTable.branch-layout-write-failure"),
exceptionMessage == null ? "" : exceptionMessage);
}
});
}
@ContinuesInBackground
public void queueDiscover(Path macheteFilePath, @UI Runnable doOnUIThreadWhenReady) {
val gitRepository = getGitRepositorySelectionProvider().getSelectedGitRepository();
if (gitRepository == null) {
return;
}
new AutodiscoverBackgroundable(gitRepository, macheteFilePath) {
@Override
protected void onDiscoverFailure() {
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> setTextForEmptyTable(
getString("string.GitMachete.EnhancedGraphTable.empty-table-text.cannot-discover-layout")
.fmt(macheteFilePath.toString())));
}
@Override
@ContinuesInBackground
protected void onDiscoverSuccess(IGitMacheteRepository repository, IGitMacheteRepositorySnapshot repositorySnapshot) {
gitMacheteRepositoryRef.set(repository);
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> {
gitMacheteRepositorySnapshot = repositorySnapshot;
queueRepositoryUpdateAndModelRefresh(doOnUIThreadWhenReady);
val notifier = VcsNotifier.getInstance(project);
val notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification(
getString("string.GitMachete.EnhancedGraphTable.automatic-discover.success-message"),
NotificationType.INFORMATION);
notification.addAction(NotificationAction.createSimple(
getString("action.GitMachete.OpenMacheteFileAction.description"), () -> {
val actionEvent = createAnActionEvent();
ActionManager.getInstance().getAction(OPEN_MACHETE_FILE).actionPerformed(actionEvent);
}));
notifier.notify(notification);
});
}
}.queue();
}
private AnActionEvent createAnActionEvent() {
val dataContext = DataManager.getInstance().getDataContext(this);
@SuppressWarnings("removal") val event = AnActionEvent.createFromDataContext(ActionPlaces.VCS_NOTIFICATION,
new Presentation(), dataContext);
return event;
}
@Override
@ContinuesInBackground
@UIEffect
public void refreshModel() {
val gitRepositorySelectionProvider = getGitRepositorySelectionProvider();
val gitRepository = gitRepositorySelectionProvider.getSelectedGitRepository();
if (gitRepository != null) {
refreshModel(gitRepository,
NullGitMacheteRepositorySnapshot.getInstance(),
/* doOnUIThreadWhenReady */ () -> {});
} else {
LOG.warn("Selected git repository is undefined; unable to refresh model");
}
}
@UIEffect
private void initColumns() {
createDefaultColumnsFromModel();
// Otherwise, sizes would be recalculated after each TableColumn re-initialization
setAutoCreateColumnsFromModel(false);
}
@ContinuesInBackground
@Override
public void queueRepositoryUpdateAndModelRefresh(@UI Runnable doOnUIThreadWhenReady) {
LOG.debug("Entering");
if (!enqueuingUpdatesEnabled.get()) {
LOG.debug("Enqueuing updates disabled");
return;
}
if (project.isDisposed()) {
LOG.debug("Project is disposed");
return;
}
ModalityUiUtil.invokeLaterIfNeeded(NON_MODAL, () -> {
setTextForEmptyTable(getString("string.GitMachete.EnhancedGraphTable.empty-table-text.loading"));
});
val gitRepositorySelectionProvider = getGitRepositorySelectionProvider();
val gitRepository = gitRepositorySelectionProvider.getSelectedGitRepository();
if (gitRepository == null) {
LOG.warn("Selected repository is null");
return;
}
@UI DoOnUIThreadWhenDone doRefreshModel = newGitMacheteRepositorySnapshot -> {
this.gitMacheteRepositorySnapshot = newGitMacheteRepositorySnapshot;
if (newGitMacheteRepositorySnapshot != null) {
validateUnmanagedBranchNotification(newGitMacheteRepositorySnapshot, unmanagedBranchNotification);
refreshModel(gitRepository, newGitMacheteRepositorySnapshot, doOnUIThreadWhenReady);
} else {
refreshModel(gitRepository, NullGitMacheteRepositorySnapshot.getInstance(), doOnUIThreadWhenReady);
}
};
LOG.debug("Queuing repository update onto a non-UI thread");
new GitMacheteRepositoryUpdateBackgroundable(
gitRepository,
branchLayoutReader,
doRefreshModel,
/* gitMacheteRepositoryHolder */ gitMacheteRepositoryRef).queue();
val macheteFile = gitRepository.getMacheteFile();
if (macheteFile != null) {
VfsUtil.markDirtyAndRefresh(/* async */ true, /* recursive */ false, /* reloadChildren */ false, macheteFile);
}
}
@UIEffect
private static void validateUnmanagedBranchNotification(IGitMacheteRepositorySnapshot newGitMacheteRepositorySnapshot,
@Nullable UnmanagedBranchNotification notification) {
val branchEntryExists = Option.of(notification)
.map(UnmanagedBranchNotification::getBranchName)
.flatMap(b -> Option.of(newGitMacheteRepositorySnapshot.getBranchLayout().getEntryByName(b)))
.isDefined();
if (branchEntryExists) {
assert notification != null : "unmanagedBranchNotification is null";
notification.expire();
val balloon = notification.getBalloon();
if (balloon != null) {
balloon.hide();
}
}
}
@Override
@ContinuesInBackground
public void enableEnqueuingUpdates() {
enqueuingUpdatesEnabled.set(true);
queueRepositoryUpdateAndModelRefresh();
}
@Override
public void disableEnqueuingUpdates() {
enqueuingUpdatesEnabled.set(false);
}
@Override
public @Nullable Object getData(String dataId) {
return Match(dataId).of(
typeSafeCase(DataKeys.GIT_MACHETE_REPOSITORY_SNAPSHOT, gitMacheteRepositorySnapshot),
typeSafeCase(DataKeys.SELECTED_BRANCH_NAME, selectedBranchName),
typeSafeCase(CommonDataKeys.PROJECT, project),
Case($(), (Object) null));
}
@Override
public void dispose() {
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/EnhancedGraphTableMouseAdapter.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/EnhancedGraphTableMouseAdapter.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import static com.virtuslab.gitmachete.frontend.defs.ActionIds.CHECK_OUT_SELECTED;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.Presentation;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.frontend.defs.ActionGroupIds;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
import com.virtuslab.gitmachete.frontend.graph.api.items.IGraphItem;
import com.virtuslab.gitmachete.frontend.ui.impl.cell.BranchOrCommitCell;
class EnhancedGraphTableMouseAdapter extends MouseAdapter {
private final EnhancedGraphTable graphTable;
private final EnhancedGraphTablePopupMenuListener popupMenuListener;
@UIEffect
EnhancedGraphTableMouseAdapter(EnhancedGraphTable graphTable) {
this.graphTable = graphTable;
this.popupMenuListener = new EnhancedGraphTablePopupMenuListener(graphTable);
}
@Override
@UIEffect
public void mouseClicked(MouseEvent e) {
Point point = e.getPoint();
int row = graphTable.rowAtPoint(point);
int col = graphTable.columnAtPoint(point);
// check if we click on one of the branches
if (row < 0 || col < 0) {
return;
}
BranchOrCommitCell cell = (BranchOrCommitCell) graphTable.getModel().getValueAt(row, col);
IGraphItem graphItem = cell.getGraphItem();
if (!graphItem.isBranchItem()) {
return;
}
graphTable.setSelectedBranchName(graphItem.asBranchItem().getBranch().getName());
performActionAfterChecks(e, point);
}
@UIEffect
private void performActionAfterChecks(MouseEvent e, Point point) {
ActionManager actionManager = ActionManager.getInstance();
if (SwingUtilities.isRightMouseButton(e) || isCtrlClick(e)) {
ActionGroup contextMenuActionGroup = (ActionGroup) actionManager.getAction(ActionGroupIds.CONTEXT_MENU);
val actionPopupMenu = actionManager.createActionPopupMenu(ActionPlaces.CONTEXT_MENU, contextMenuActionGroup);
JPopupMenu popupMenu = actionPopupMenu.getComponent();
popupMenu.addPopupMenuListener(popupMenuListener);
popupMenu.show(graphTable, (int) point.getX(), (int) point.getY());
} else if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2 && !e.isConsumed()) {
val gitMacheteRepositorySnapshot = graphTable.getGitMacheteRepositorySnapshot();
if (gitMacheteRepositorySnapshot != null) {
val currentBranchIfManaged = gitMacheteRepositorySnapshot
.getCurrentBranchIfManaged();
val isSelectedEqualToCurrent = currentBranchIfManaged != null
&& currentBranchIfManaged.getName().equals(graphTable.getSelectedBranchName());
if (isSelectedEqualToCurrent) {
return;
}
}
e.consume();
DataContext dataContext = DataManager.getInstance().getDataContext(graphTable);
@SuppressWarnings("removal") val actionEvent = AnActionEvent.createFromDataContext(ActionPlaces.CONTEXT_MENU,
new Presentation(), dataContext);
actionManager.getAction(CHECK_OUT_SELECTED).actionPerformed(actionEvent);
}
}
// this method is needed as some macOS users use Ctrl + left-click as a replacement for the right-click
@UIEffect
private boolean isCtrlClick(MouseEvent e) {
return e.isControlDown() && SwingUtilities.isLeftMouseButton(e);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/UnmanagedBranchNotificationFactory.java | frontend/ui/impl/src/main/java/com/virtuslab/gitmachete/frontend/ui/impl/table/UnmanagedBranchNotificationFactory.java | package com.virtuslab.gitmachete.frontend.ui.impl.table;
import static com.virtuslab.gitmachete.frontend.datakeys.DataKeys.typeSafeCase;
import static com.virtuslab.gitmachete.frontend.defs.ActionIds.OPEN_MACHETE_FILE;
import static com.virtuslab.gitmachete.frontend.defs.ActionIds.SLIDE_IN_UNMANAGED_BELOW;
import static com.virtuslab.gitmachete.frontend.defs.PropertiesComponentKeys.SHOW_UNMANAGED_BRANCH_NOTIFICATION;
import static com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.getString;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationAction;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.CustomizedDataContext;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.Project;
import lombok.RequiredArgsConstructor;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
import com.virtuslab.gitmachete.frontend.datakeys.DataKeys;
import com.virtuslab.gitmachete.frontend.defs.ActionPlaces;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
@ExtensionMethod(GitMacheteBundle.class)
@RequiredArgsConstructor
public class UnmanagedBranchNotificationFactory {
private final Project project;
private final @Nullable IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot;
private final String branchName;
private final @Nullable ILocalBranchReference inferredParent;
public UnmanagedBranchNotification create() {
val notification = new UnmanagedBranchNotification(branchName);
val slideInAction = getSlideInAction(notification);
val openMacheteFileAction = getOpenMacheteFileAction();
val dontShowForThisBranchAction = getDontShowForThisBranchAction(notification);
val dontShowForThisProjectAction = getDontShowForThisProjectAction(notification);
notification.addAction(slideInAction);
notification.addAction(openMacheteFileAction);
notification.addAction(dontShowForThisBranchAction);
notification.addAction(dontShowForThisProjectAction);
return notification;
}
@UIEffect
public static boolean shouldShowForThisProject(Project project) {
return PropertiesComponent.getInstance(project).getBoolean(SHOW_UNMANAGED_BRANCH_NOTIFICATION, /* defaultValue */ true);
}
@UIEffect
public static boolean shouldShowForThisBranch(Project project, String aBranchName) {
String propertyKey = "${SHOW_UNMANAGED_BRANCH_NOTIFICATION}.${aBranchName}";
return PropertiesComponent.getInstance(project).getBoolean(propertyKey, /* defaultValue */ true);
}
@SuppressWarnings("removal")
private NotificationAction getSlideInAction(Notification notification) {
val title = inferredParent == null
? getString("action.GitMachete.EnhancedGraphTable.unmanaged-branch-notification.action.slide-in-as-root")
: getString("action.GitMachete.EnhancedGraphTable.unmanaged-branch-notification.action.slide-in")
.fmt(inferredParent.getName());
val nullableInferredParentName = inferredParent != null ? inferredParent.getName() : null;
val provider = new DataProvider() {
@Override
public @Nullable Object getData(String dataId) {
return Match(dataId).of(
typeSafeCase(DataKeys.GIT_MACHETE_REPOSITORY_SNAPSHOT, gitMacheteRepositorySnapshot),
typeSafeCase(DataKeys.SELECTED_BRANCH_NAME, nullableInferredParentName),
typeSafeCase(DataKeys.UNMANAGED_BRANCH_NAME, branchName),
typeSafeCase(CommonDataKeys.PROJECT, project),
Case($(), (Object) null));
}
};
return NotificationAction
.createSimple(
title,
() -> {
// TODO (#1982): replace with CustomizedDataContext.withSnapshot(..., new DataSnapshotProvider() { ... })
val dataContext = CustomizedDataContext.withProvider(DataManager.getInstance().getDataContext(), provider);
@SuppressWarnings("removal") val actionEvent = AnActionEvent.createFromDataContext(ActionPlaces.VCS_NOTIFICATION,
new Presentation(), dataContext);
ActionManager.getInstance().getAction(SLIDE_IN_UNMANAGED_BELOW).actionPerformed(actionEvent);
notification.expire();
});
}
private NotificationAction getDontShowForThisBranchAction(Notification notification) {
return NotificationAction
.createSimple(
getString("action.GitMachete.EnhancedGraphTable.unmanaged-branch-notification.action.dont-show-for-branch")
.fmt(branchName),
() -> {
String propertyKey = "${SHOW_UNMANAGED_BRANCH_NOTIFICATION}.${branchName}";
PropertiesComponent.getInstance(project).setValue(propertyKey, false, /* defaultValue */ true);
notification.expire();
});
}
private NotificationAction getDontShowForThisProjectAction(Notification notification) {
return NotificationAction
.createSimple(
getString("action.GitMachete.EnhancedGraphTable.unmanaged-branch-notification.action.dont-show-for-project"),
() -> {
PropertiesComponent.getInstance(project).setValue(SHOW_UNMANAGED_BRANCH_NOTIFICATION, false,
/* defaultValue */ true);
notification.expire();
});
}
@SuppressWarnings("removal")
private NotificationAction getOpenMacheteFileAction() {
val provider = new DataProvider() {
@Override
public @Nullable Object getData(String dataId) {
return dataId.equals(CommonDataKeys.PROJECT.getName()) ? project : null;
}
};
return NotificationAction.createSimple(
getString("action.GitMachete.OpenMacheteFileAction.description"), () -> {
// TODO (#1982): replace with CustomizedDataContext.withSnapshot(..., new DataSnapshotProvider() { ... })
val dataContext = CustomizedDataContext.withProvider(DataManager.getInstance().getDataContext(), provider);
@SuppressWarnings("removal") val actionEvent = AnActionEvent.createFromDataContext(ActionPlaces.VCS_NOTIFICATION,
new Presentation(), dataContext);
ActionManager.getInstance().getAction(OPEN_MACHETE_FILE).actionPerformed(actionEvent);
});
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/gitrepositoryselection/IGitRepositorySelectionProvider.java | frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/gitrepositoryselection/IGitRepositorySelectionProvider.java | package com.virtuslab.gitmachete.frontend.ui.api.gitrepositoryselection;
import javax.swing.JComponent;
import git4idea.repo.GitRepository;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface IGitRepositorySelectionProvider {
@Nullable
GitRepository getSelectedGitRepository();
void addSelectionChangeObserver(IGitRepositorySelectionChangeObserver observer);
JComponent getSelectionComponent();
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/gitrepositoryselection/IGitRepositorySelectionChangeObserver.java | frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/gitrepositoryselection/IGitRepositorySelectionChangeObserver.java | package com.virtuslab.gitmachete.frontend.ui.api.gitrepositoryselection;
@FunctionalInterface
public interface IGitRepositorySelectionChangeObserver {
void onSelectionChanged();
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/table/BaseEnhancedGraphTable.java | frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/table/BaseEnhancedGraphTable.java | package com.virtuslab.gitmachete.frontend.ui.api.table;
import java.nio.file.Path;
import javax.swing.table.AbstractTableModel;
import com.intellij.openapi.project.Project;
import org.checkerframework.checker.guieffect.qual.UI;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.qual.async.ContinuesInBackground;
/**
* This class compared to {@code SimpleGraphTable} has graph table refreshing.
* Also, while there may be multiple {@code SimpleGraphTable}s per {@link Project},
* there can only be a single {@code BaseEnhancedGraphTable}.
*/
public abstract class BaseEnhancedGraphTable extends BaseGraphTable {
@UIEffect
protected BaseEnhancedGraphTable(AbstractTableModel model) {
super(model);
}
@UIEffect
public abstract void setListingCommits(boolean isListingCommits);
@ContinuesInBackground
public abstract void enableEnqueuingUpdates();
public abstract void disableEnqueuingUpdates();
/**
* Refresh the model synchronously (i.e. in a blocking manner).
* Must be called from the UI thread (hence {@link UIEffect}).
*/
@ContinuesInBackground
@UIEffect
public abstract void refreshModel();
/**
* Queues repository update as a background task, which in turn itself queues model refresh onto the UI thread.
* As opposed to {@link BaseEnhancedGraphTable#refreshModel}, does not need to be called from the UI thread (i.e. is not {@link UIEffect}).
*
* @param doOnUIThreadWhenReady an action to execute on the UI thread after the model is refreshed.
*/
@ContinuesInBackground
public abstract void queueRepositoryUpdateAndModelRefresh(@UI Runnable doOnUIThreadWhenReady);
@ContinuesInBackground
public final void queueRepositoryUpdateAndModelRefresh() {
queueRepositoryUpdateAndModelRefresh(() -> {});
}
@ContinuesInBackground
public abstract void queueDiscover(Path macheteFilePath, @UI Runnable doOnUIThreadWhenReady);
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/table/BaseGraphTable.java | frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/table/BaseGraphTable.java | package com.virtuslab.gitmachete.frontend.ui.api.table;
import java.awt.Component;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import com.intellij.ui.table.JBTable;
import io.vavr.collection.List;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
public abstract class BaseGraphTable extends JBTable {
private static int GRAPH_COLUMN_RIGHT_PADDING = 25;
@UIEffect
private List<Integer> rowWidths = List.empty();
@UIEffect
@SuppressWarnings("nullness:method.invocation") // to allow for setAutoResizeMode despite the object isn't initialized yet
protected BaseGraphTable(TableModel model) {
super(model);
// Without set autoresize off column will expand to whole table width (will not fit the content size).
// This causes the branch tooltips (sync to parent status descriptions)
// to be displayed on the whole Git Machete panel width instead of just over the text.
setAutoResizeMode(JBTable.AUTO_RESIZE_OFF);
}
public abstract @Nullable IGitMacheteRepositorySnapshot getGitMacheteRepositorySnapshot();
/**
* This method that overrides {@link JBTable#prepareRenderer} is responsible for setting column size that fits the content
*/
@Override
@UIEffect
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
// In case row count is not equal the previous one, it means that the graph was changed, so we don't care
// about previous row width and we must create new list with size equals new row count.
// This is why we replace previous list with new, filled with 0.
if (getRowCount() != rowWidths.size()) {
rowWidths = List.fill(getRowCount(), 0);
}
Component component = super.prepareRenderer(renderer, row, column);
int rendererWidth = component.getPreferredSize().width;
rowWidths = rowWidths.update(row, rendererWidth);
TableColumn tableColumn = getColumnModel().getColumn(column);
tableColumn.setPreferredWidth(rowWidths.max().map(maxWidth -> maxWidth + GRAPH_COLUMN_RIGHT_PADDING).getOrElse(0));
return component;
}
@UIEffect
public void setTextForEmptyTable(String text) {
getEmptyText().setText(text);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/table/ISimpleGraphTableProvider.java | frontend/ui/api/src/main/java/com/virtuslab/gitmachete/frontend/ui/api/table/ISimpleGraphTableProvider.java | package com.virtuslab.gitmachete.frontend.ui.api.table;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
public interface ISimpleGraphTableProvider {
@UIEffect
BaseGraphTable deriveInstance(IGitMacheteRepositorySnapshot macheteRepositorySnapshot, boolean isListingCommitsEnabled,
boolean shouldDisplayActionToolTips);
@UIEffect
BaseGraphTable deriveDemoInstance();
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.