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/src/test/java/com/virtuslab/archunit/ForbiddenMethodsTestSuite.java | src/test/java/com/virtuslab/archunit/ForbiddenMethodsTestSuite.java | package com.virtuslab.archunit;
import static com.tngtech.archunit.core.domain.JavaCall.Predicates.target;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.assignableTo;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.name;
import static com.tngtech.archunit.core.domain.properties.HasOwner.Predicates.With.owner;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaMethodCall;
import lombok.val;
import org.junit.jupiter.api.Test;
import com.virtuslab.gitmachete.backend.impl.GitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle;
public class ForbiddenMethodsTestSuite extends BaseArchUnitTestSuite {
@Test
public void no_classes_should_call_AnActionEvent_getRequiredData() {
noClasses()
.should()
.callMethod(com.intellij.openapi.actionSystem.AnActionEvent.class, "getRequiredData",
com.intellij.openapi.actionSystem.DataKey.class)
.because("getRequiredData can fail in the runtime if the requested DataKey is missing; " +
"use AnActionEvent#getData instead")
.check(productionClasses);
}
@Test
public void no_classes_should_call_Application_getService_from_static_initializer() {
noClasses()
.should()
.callMethodWhere(new DescribedPredicate<JavaMethodCall>("Application#getService is called from static initializer") {
@Override
public boolean test(JavaMethodCall javaMethodCall) {
val target = javaMethodCall.getTarget();
val origin = javaMethodCall.getOrigin();
return target.getOwner().isEquivalentTo(com.intellij.openapi.application.Application.class)
&& target.getName().equals("getService")
&& origin.getName().equals("<clinit>");
}
})
.because("class initialization must not depend on services since IntelliJ 2024.2")
.check(productionClasses);
}
@Test
public void no_classes_should_call_Collections_nCopies() {
noClasses()
.should().callMethod(java.util.Collections.class, "nCopies", int.class, Object.class)
.because("it is confusing as it does not copy the objects but just copies the reference N times")
.check(productionClasses);
}
@Test
public void no_classes_should_call_File_exists() {
noClasses()
.should().callMethod(java.io.File.class, "exists")
.andShould().callMethod(com.intellij.openapi.vfs.VirtualFile.class, "exists")
.because("in most cases, the check you want to do is `isFile` rather than `exists` (what if this is a directory?)")
.check(productionClasses);
}
@Test
public void no_classes_should_call_FileContentUtil_reparseFiles() {
noClasses()
.should().callMethodWhere(
target(owner(assignableTo(com.intellij.util.FileContentUtil.class)))
.and(target(name("reparseFiles"))))
.because("com.intellij.util.FileContentUtil#reparseFiles can cause bad performance issues when called with " +
"includeOpenFiles parameter equal true. Use com.intellij.util.FileContentUtilCore#reparseFiles instead")
.check(productionClasses);
}
@Test
public void no_classes_should_call_FileContentUtil_reparseOpenedFiles() {
noClasses()
.should().callMethodWhere(
target(owner(assignableTo(com.intellij.util.FileContentUtil.class)))
.and(target(name("reparseOpenedFiles"))))
.because("com.intellij.util.FileContentUtil#reparseOpenedFiles can cause bad performance issues." +
"Use com.intellij.util.FileContentUtilCore#reparseFiles instead")
.check(productionClasses);
}
@Test
public void no_classes_should_call_GitRepository_getBranchTrackInfo_s() {
noClasses()
.should().callMethod(git4idea.repo.GitRepository.class, "getBranchTrackInfo", String.class)
.orShould().callMethod(git4idea.repo.GitRepository.class, "getBranchTrackInfos")
.because("getBranchTrackInfo(s) does not take into account inferred remote " +
"(when only branch names match but tracking data is unset); " +
" use tracking data from " + GitMacheteRepositorySnapshot.class.getName() + " instead")
.check(productionClasses);
}
@Test
public void no_classes_should_call_GitUIUtil_notifyError() {
noClasses()
.should()
.callMethodWhere(
target(owner(assignableTo(git4idea.util.GitUIUtil.class)))
.and(target(name("notifyError"))))
.because("due to the bug IDEA-258711, a valid invocation of notifyError can lead to an NPE (see issue #676)")
.check(productionClasses);
}
@Test
public void no_classes_should_call_JComponent_updateUI() {
noClasses()
.should().callMethod(javax.swing.JComponent.class, "updateUI")
.because("repaint() and revalidate() should be used instead, see docs for javax.swing.JComponent for the reasons")
.check(productionClasses);
}
@Test
public void no_classes_should_call_Link_linkSomethingColor() {
noClasses()
.should().callMethodWhere(
target(owner(assignableTo(com.intellij.util.ui.JBUI.CurrentTheme.Link.class)))
.and(target(name("link.*Color"))))
.because("links should be avoided since they are unreliable as of IDEA 2020.2")
.check(productionClasses);
}
@Test
public void no_classes_should_call_MessageFormat_format() {
noClasses()
.that().areNotAssignableTo(com.virtuslab.gitmachete.frontend.resourcebundles.GitMacheteBundle.class)
.should().callMethod(java.text.MessageFormat.class, "format", String.class, Object[].class)
.because("more restrictive " + GitMacheteBundle.class.getSimpleName() + ".format should be used instead")
.check(productionClasses);
}
@Test
public void no_classes_should_call_Option_toString() {
noClasses()
.should().callMethod(io.vavr.control.Option.class, "toString")
.because("Option#toString is sometimes mistakenly interpolated inside strings (also the user-facing ones), " +
"whereas in 90% of cases the programmer`s intention " +
"is to interpolate the contained value aka the result of `.get()` and not the Option itself")
.check(productionClasses);
}
@Test
public void no_classes_should_call_PropertiesComponent_getInstance_without_args() {
noClasses()
.should().callMethod(com.intellij.ide.util.PropertiesComponent.class, "getInstance")
.because(
"getInstance without `project` argument gives application-level persistence while we prefer project-level persistence")
.check(productionClasses);
}
@Test
public void no_classes_should_call_String_format() {
noClasses()
.should().callMethod(String.class, "format", String.class, Object[].class)
.because("string interpolation should be used instead (as provided by com.antkorwin:better-strings)")
.check(productionClasses);
}
@Test
public void no_classes_should_call_SwingUtilities_invokeLater() {
noClasses()
.should().callMethod(javax.swing.SwingUtilities.class, "invokeLater", Runnable.class)
.because("ModalityUiUtil.invokeLaterIfNeeded(...) should be used instead. " +
"See docs for " + com.intellij.openapi.application.ModalityState.class.getName() + " for the reasons")
.check(productionClasses);
}
@Test
public void no_classes_should_call_Value_collect() {
noClasses()
.should().callMethodWhere(
target(owner(assignableTo(io.vavr.Value.class)))
.and(target(name("collect"))))
.because("invocation of `collect` on a Vavr Value (including Array, List, Map, Set etc.) " +
"is almost always avoidable and in many cases indicates that a redundant conversion " +
"is being performed (like `collect`-ing a List into another List etc.). " +
"Use dedicated methods like `.toList()`, `.toJavaList()`, `.toSet()` etc. " +
"You might consider suppressing this error, however, if the Value in question is a Vavr Stream.")
.check(productionClasses);
}
@Test
public void no_classes_should_call_Value_peek() {
noClasses()
.should().callMethodWhere(
target(owner(assignableTo(io.vavr.Value.class)))
.and(target(name("peek"))))
.because("io.vavr.collection.<X>#peek and java.util.stream.Stream#peek unexpectedly differ in their behaviour. " +
"`peek` from Vavr calls the given `Consumer` only for the first element in collection, " +
"while `peek` from Java `Stream` calls the given `Consumer` for every element. " +
"To avoid possible bugs, invocation of `peek` on Vavr classes is forbidden. " +
"Usage of `java.util.stream.Stream#peek` is discouraged but not forbidden " +
"(since it is pretty useful and alternatives are cumbersome).")
.check(productionClasses);
}
@Test
public void no_classes_should_call_println() {
noClasses()
.should().callMethodWhere(name("println"))
.check(productionClasses);
}
// Note that https://checkstyle.sourceforge.io/config_coding.html#CovariantEquals doesn't cover methods defined in interfaces.
@Test
public void equals_method_should_have_object_parameter_and_boolean_return_type() {
methods()
.that()
.haveName("equals")
.should()
.haveRawParameterTypes(Object.class)
.andShould()
.haveRawReturnType(Boolean.TYPE)
.because("of the reasons outlined in https://www.artima.com/pins1ed/object-equality.html -> pitfall #1")
.check(productionClasses);
}
}
| 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/src/test/java/com/virtuslab/archunit/ForbiddenFieldsTestSuite.java | src/test/java/com/virtuslab/archunit/ForbiddenFieldsTestSuite.java | package com.virtuslab.archunit;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import org.junit.jupiter.api.Test;
public class ForbiddenFieldsTestSuite extends BaseArchUnitTestSuite {
@Test
public void no_classes_should_access_RevSort_TOPO() {
noClasses()
.should()
.accessField(org.eclipse.jgit.revwalk.RevSort.class, "TOPO")
.orShould()
.accessField(org.eclipse.jgit.revwalk.RevSort.class, "TOPO_KEEP_BRANCH_TOGETHER")
.because("as of JGit 6.4.0, these flags lead to performance problems on large repos (100,000s of commits); " +
"use RevSort#COMMIT_TIME_DESC instead")
.check(productionClasses);
}
}
| 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/src/test/java/com/virtuslab/archunit/MethodCallsTestSuite.java | src/test/java/com/virtuslab/archunit/MethodCallsTestSuite.java | package com.virtuslab.archunit;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.*;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.*;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.jupiter.api.Test;
public class MethodCallsTestSuite extends BaseArchUnitTestSuite {
@Test
public void methods_calling_a_method_throwing_RevisionSyntaxException_should_catch_it_explicitly() {
codeUnits().that(new DescribedPredicate<JavaCodeUnit>("call a code unit throwing JGit RevisionSyntaxException") {
@Override
public boolean test(JavaCodeUnit codeUnit) {
return codeUnit.getCallsFromSelf().stream().anyMatch(
call -> call.getTarget().getThrowsClause().containsType(org.eclipse.jgit.errors.RevisionSyntaxException.class));
}
})
.should(new ArchCondition<JavaCodeUnit>("catch this exception explicitly") {
@Override
public void check(JavaCodeUnit codeUnit, ConditionEvents events) {
if (codeUnit.getTryCatchBlocks().stream().noneMatch(block -> block.getCaughtThrowables().stream()
.anyMatch(javaClass -> javaClass.isEquivalentTo(org.eclipse.jgit.errors.RevisionSyntaxException.class)))) {
events.add(SimpleConditionEvent.violated(codeUnit,
"code unit ${codeUnit.getFullName()} does not catch RevisionSyntaxException; see issue #1826"));
}
}
})
.check(productionClasses);
}
@Test
public void overridden_onUpdate_methods_should_call_super_onUpdate() {
methods().that().haveName("onUpdate")
.and().areNotDeclaredIn(com.virtuslab.gitmachete.frontend.actions.base.BaseProjectDependentAction.class)
.should(callAtLeastOnceACodeUnitThat("is called onUpdate and is declared in the direct superclass",
(method, calledMethod) -> {
val superclass = method.getOwner().getSuperclass().orElse(null);
return calledMethod.getOwner().equals(superclass) && calledMethod.getName().equals("onUpdate");
}))
.check(productionClasses);
}
@Test
public void code_units_calling_MessageBusConnection_subscribe_must_later_call_Disposer_register_too() {
String subscribeMethodFullName = "com.intellij.util.messages.MessageBusConnection.subscribe(com.intellij.util.messages.Topic, java.lang.Object)";
String registerMethodFullName = "com.intellij.openapi.util.Disposer.register(com.intellij.openapi.Disposable, com.intellij.openapi.Disposable)";
codeUnits().should(new ArchCondition<>("call ${registerMethodFullName} if they call ${subscribeMethodFullName}") {
@Override
public void check(JavaCodeUnit codeUnit, ConditionEvents events) {
JavaMethodCall subscribeCall = findFirstCallTo(codeUnit, subscribeMethodFullName);
JavaMethodCall registerCall = findFirstCallTo(codeUnit, registerMethodFullName);
if (subscribeCall != null) {
if (registerCall == null) {
String message = "Method ${codeUnit.getFullName()} calls MessageBusConnection::subscribe without a following Disposer::register";
events.add(SimpleConditionEvent.violated(codeUnit, message));
} else if (registerCall.getLineNumber() < subscribeCall.getLineNumber()) {
String message = "Method ${codeUnit.getFullName()} calls MessageBusConnection::subscribe after Disposer::register";
events.add(SimpleConditionEvent.violated(codeUnit, message));
}
}
}
private @Nullable JavaMethodCall findFirstCallTo(JavaCodeUnit sourceCodeUnit, String targetMethodFullName) {
return sourceCodeUnit.getMethodCallsFromSelf().stream()
.filter(call -> call.getTarget().getFullName().equals(targetMethodFullName)).findFirst()
.orElse(null);
}
}).check(productionClasses);
}
}
| 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/src/test/java/com/virtuslab/archunit/BackgroundTaskEnqueuingTestSuite.java | src/test/java/com/virtuslab/archunit/BackgroundTaskEnqueuingTestSuite.java | package com.virtuslab.archunit;
import static com.tngtech.archunit.core.domain.JavaModifier.ABSTRACT;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noMethods;
import java.util.Arrays;
import com.intellij.dvcs.push.ui.VcsPushDialog;
import com.intellij.openapi.progress.Task;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.AccessTarget;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaMethod;
import git4idea.branch.GitBrancher;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.junit.jupiter.api.Test;
import com.virtuslab.qual.async.BackgroundableQueuedElsewhere;
import com.virtuslab.qual.async.ContinuesInBackground;
import com.virtuslab.qual.async.DoesNotContinueInBackground;
@ExtensionMethod(Arrays.class)
public class BackgroundTaskEnqueuingTestSuite extends BaseArchUnitTestSuite {
private static final String ContinuesInBackgroundName = "@" + ContinuesInBackground.class.getSimpleName();
@Test
public void methods_that_create_backgroundable_should_also_call_queue() {
methods()
.that()
.areNotAnnotatedWith(BackgroundableQueuedElsewhere.class)
.and(new DescribedPredicate<JavaMethod>("create an instance of Task.Backgroundable or its subclass") {
@Override
public boolean test(JavaMethod method) {
return method.getConstructorCallsFromSelf().stream()
.anyMatch(constructorCall -> constructorCall.getTargetOwner().isAssignableTo(Task.Backgroundable.class));
}
})
.should(callAtLeastOnceACodeUnitThat("is Task.Backgroundable#queue()",
(codeUnit, calledCodeUnit) -> calledCodeUnit.getOwner().isAssignableTo(Task.Backgroundable.class)
&& calledCodeUnit.getName().equals("queue")))
.because("otherwise it's likely that you forgot about actually scheduling the task; " +
"mark the method with ${BackgroundableQueuedElsewhere.class.getSimpleName()} if this is expected")
.check(productionClasses);
}
@Test
public void only_continues_in_background_methods_should_call_methods_that_continue_in_background() {
noMethods()
.that()
.areNotAnnotatedWith(ContinuesInBackground.class)
.and()
.areNotAnnotatedWith(DoesNotContinueInBackground.class)
.should(callAnyCodeUnitsThat("enqueue background tasks or are themselves ${ContinuesInBackgroundName}",
(codeUnit, calledCodeUnit) -> doesContinueInBackground(calledCodeUnit)))
.because("running tasks in background is inextricably linked to the increased risk of race conditions; " +
"mark the calling method as ${ContinuesInBackgroundName} to make it clear that it executes asynchronously")
.check(productionClasses);
}
private static final String[] knownMethodsOverridableAsContinuesInBackground = {
"com.intellij.codeInsight.intention.IntentionAction.invoke(com.intellij.openapi.project.Project, com.intellij.openapi.editor.Editor, com.intellij.psi.PsiFile)",
"com.intellij.openapi.actionSystem.AnAction.actionPerformed(com.intellij.openapi.actionSystem.AnActionEvent)",
"com.intellij.openapi.progress.Progressive.run(com.intellij.openapi.progress.ProgressIndicator)",
"com.intellij.openapi.progress.Task.onFinished()",
"com.intellij.openapi.progress.Task.onSuccess()",
"com.intellij.openapi.vfs.newvfs.BulkFileListener.after(java.util.List)",
"com.intellij.ui.AncestorListenerAdapter.ancestorAdded(javax.swing.event.AncestorEvent)",
com.virtuslab.gitmachete.frontend.actions.backgroundables.SideEffectingBackgroundable.class.getName()
+ ".doRun(com.intellij.openapi.progress.ProgressIndicator)",
com.virtuslab.gitmachete.frontend.actions.base.BaseGitMacheteRepositoryReadyAction.class.getName()
+ ".actionPerformed(com.intellij.openapi.actionSystem.AnActionEvent)",
"javax.swing.event.AncestorListener.ancestorAdded(javax.swing.event.AncestorEvent)",
};
@Test
public void continues_in_background_methods_should_not_override_non_continues_in_background_methods() {
noMethods()
.that()
.areAnnotatedWith(ContinuesInBackground.class)
.should(overrideAnyMethodThat("is NOT ${ContinuesInBackgroundName} itself", (method, overriddenMethod) -> {
val overriddenMethodFullName = overriddenMethod.getFullName();
if (overriddenMethod.isAnnotatedWith(ContinuesInBackground.class)) {
return false;
}
if (knownMethodsOverridableAsContinuesInBackground.asList().contains(overriddenMethodFullName)) {
return false;
}
return true;
}))
.check(productionClasses);
}
@Test
public void concrete_continues_in_background_methods_should_call_at_least_one_method_that_continues_in_background() {
methods()
.that()
.doNotHaveModifier(ABSTRACT)
.and()
.areAnnotatedWith(ContinuesInBackground.class)
.should(callAtLeastOnceACodeUnitThat("enqueue background tasks or are themselves ${ContinuesInBackgroundName}",
(codeUnit, calledCodeUnit) -> doesContinueInBackground(calledCodeUnit)))
.check(productionClasses);
}
private static boolean doesContinueInBackground(AccessTarget.CodeUnitCallTarget codeUnit) {
if (codeUnit.isAnnotatedWith(ContinuesInBackground.class)) {
return true;
}
String name = codeUnit.getName();
JavaClass owner = codeUnit.getOwner();
JavaClass returnType = codeUnit.getRawReturnType();
return owner.isAssignableTo(Task.Backgroundable.class) && name.equals("queue") ||
owner.isAssignableTo(GitBrancher.class) && !(name.equals("getInstance") || name.equals("compareAny")) ||
owner.isAssignableTo(VcsPushDialog.class) && name.equals("show") ||
returnType.isEquivalentTo(java.util.concurrent.Future.class);
}
}
| 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/src/test/java/com/virtuslab/archunit/ForbiddenClassesTestSuite.java | src/test/java/com/virtuslab/archunit/ForbiddenClassesTestSuite.java | package com.virtuslab.archunit;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import org.junit.jupiter.api.Test;
public class ForbiddenClassesTestSuite extends BaseArchUnitTestSuite {
@Test
public void no_classes_should_depend_on_java_collections() {
noClasses()
.that().resideOutsideOfPackages(
"com.virtuslab.gitmachete.backend.hooks",
"com.virtuslab.gitmachete.frontend.actions..",
"com.virtuslab.gitmachete.frontend.errorreport",
"com.virtuslab.gitmachete.frontend.file..",
"com.virtuslab..impl..")
.should()
.dependOnClassesThat().haveNameMatching("java\\.util\\.(Deque|HashMap|List|Map|Queue|Set|Stack|TreeMap|Vector)")
.because("immutable Vavr counterparts should be used instead of mutable Java collections")
.check(productionClasses);
}
@Test
public void no_classes_should_depend_on_org_apache_commons_lang_NotImplementedException() {
noClasses()
.should()
.dependOnClassesThat().areAssignableTo(org.apache.commons.lang3.NotImplementedException.class)
.because("io.vavr.NotImplementedError should be used instead of apache-commons NotImplementedException")
.check(productionClasses);
}
@Test
public void no_classes_should_depend_on_java_util_Date() {
// GitCoreReflogEntry converts a Date coming from JGit to an Instant, hence the exception
noClasses()
.that().areNotAssignableTo(com.virtuslab.gitcore.impl.jgit.GitCoreReflogEntry.class)
.should()
.dependOnClassesThat().areAssignableTo(java.util.Date.class)
.because("Date is unsafe and deprecated; ZonedDateTime or Instant should be used instead")
.check(productionClasses);
}
@Test
public void no_classes_should_depend_on_java_time_LocalDateTime() {
noClasses()
.should()
.dependOnClassesThat().areAssignableTo(java.time.LocalDateTime.class)
.because("local date-times are inherently unsafe " +
"since they give an impression of referring to a specific instant " +
"while in fact, they do not. Use ZonedDateTime or Instant instead")
.check(productionClasses);
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/integration/StatusAndDiscoverIntegrationTestSuite.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/integration/StatusAndDiscoverIntegrationTestSuite.java | package com.virtuslab.gitmachete.backend.integration;
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.testcommon.SetupScripts.ALL_SETUP_SCRIPTS;
import static com.virtuslab.gitmachete.testcommon.TestFileUtils.cleanUpDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.charset.StandardCharsets;
import io.vavr.collection.List;
import lombok.SneakyThrows;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import com.virtuslab.gitmachete.backend.api.*;
public class StatusAndDiscoverIntegrationTestSuite extends BaseIntegrationTestSuite {
public static String[] getScriptNames() {
return ALL_SETUP_SCRIPTS;
}
@ParameterizedTest
@MethodSource("getScriptNames")
@SneakyThrows
public void yieldsSameStatusAsCli(String scriptName) {
setUp(scriptName);
String gitMacheteCliStatus = gitMacheteCliStatusOutput(scriptName);
val gitMacheteRepositorySnapshot = gitMacheteRepository.createSnapshotForLayout(branchLayout);
String ourStatus = ourGitMacheteRepositorySnapshotAsString(gitMacheteRepositorySnapshot);
System.out.println("CLI OUTPUT:");
System.out.println(gitMacheteCliStatus);
System.out.println();
System.out.println("OUR OUTPUT:");
System.out.println(ourStatus);
assertEquals(gitMacheteCliStatus, ourStatus, "in " + repo.rootDirectoryPath + ", set up using " + scriptName);
// Deliberately done in the test and in not an @After method, so that the directory is retained in case of test failure.
cleanUpDir(repo.parentDirectoryPath);
}
@ParameterizedTest
@MethodSource("getScriptNames")
@SneakyThrows
public void discoversSameLayoutAsCli(String scriptName) {
setUp(scriptName);
String gitMacheteCliDiscoverOutput = gitMacheteCliDiscoverOutput(scriptName);
val gitMacheteRepositorySnapshot = gitMacheteRepository.discoverLayoutAndCreateSnapshot();
String ourDiscoverOutput = ourGitMacheteRepositorySnapshotAsString(gitMacheteRepositorySnapshot);
System.out.println("CLI OUTPUT:");
System.out.println(gitMacheteCliDiscoverOutput);
System.out.println();
System.out.println("OUR OUTPUT:");
System.out.println(ourDiscoverOutput);
assertEquals(gitMacheteCliDiscoverOutput, ourDiscoverOutput,
"in " + repo.rootDirectoryPath + ", set up using " + scriptName);
// Deliberately done in the test and in not an @After method, so that the directory is retained in case of test failure.
cleanUpDir(repo.parentDirectoryPath);
}
@SneakyThrows
private String gitMacheteCliStatusOutput(String scriptName) {
return IOUtils.resourceToString("/${scriptName}-status.txt", StandardCharsets.UTF_8);
}
@SneakyThrows
private String gitMacheteCliDiscoverOutput(String scriptName) {
return IOUtils.resourceToString("/${scriptName}-discover.txt", StandardCharsets.UTF_8);
}
private String ourGitMacheteRepositorySnapshotAsString(IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot) {
val sb = new StringBuilder();
val branches = gitMacheteRepositorySnapshot.getRootBranches();
int lastRootBranchIndex = branches.size() - 1;
for (int currentRootBranch = 0; currentRootBranch <= lastRootBranchIndex; currentRootBranch++) {
val b = branches.get(currentRootBranch);
printRootBranch(gitMacheteRepositorySnapshot, b, sb);
if (currentRootBranch < lastRootBranchIndex)
sb.append(System.lineSeparator());
}
return sb.toString();
}
private void printRootBranch(IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot, IRootManagedBranchSnapshot branch,
StringBuilder sb) {
sb.append(" ");
printCommonParts(gitMacheteRepositorySnapshot, branch, /* path */ List.empty(), sb);
}
private void printNonRootBranch(
IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot,
INonRootManagedBranchSnapshot branch,
List<INonRootManagedBranchSnapshot> path,
StringBuilder sb) {
String prefix = path.init()
.map(anc -> anc == anc.getParent().getChildren().last() ? " " : "| ")
.mkString();
sb.append(" ");
sb.append(prefix);
sb.append("|");
sb.append(System.lineSeparator());
val commits = branch.getUniqueCommits().reverse();
val forkPoint = branch.getForkPoint();
for (val c : commits) {
sb.append(" ");
sb.append(prefix);
sb.append("| ");
sb.append(c.getShortMessage());
if (c.equals(forkPoint)) {
sb.append(" -> fork point ??? commit ${forkPoint.getShortHash()} seems to be a part of the unique history of ");
List<IBranchReference> uniqueBranchesContainingInReflog = forkPoint.getUniqueBranchesContainingInReflog();
sb.append(uniqueBranchesContainingInReflog.map(IBranchReference::getName).sorted().mkString(" and "));
}
sb.append(System.lineSeparator());
}
sb.append(" ");
sb.append(prefix);
val parentStatus = branch.getSyncToParentStatus();
if (parentStatus == SyncToParentStatus.InSync)
sb.append("o");
else if (parentStatus == SyncToParentStatus.OutOfSync)
sb.append("x");
else if (parentStatus == SyncToParentStatus.InSyncButForkPointOff)
sb.append("?");
else if (parentStatus == SyncToParentStatus.MergedToParent)
sb.append("m");
sb.append("-");
printCommonParts(gitMacheteRepositorySnapshot, branch, path, sb);
}
private void printCommonParts(IGitMacheteRepositorySnapshot gitMacheteRepositorySnapshot, IManagedBranchSnapshot branch,
List<INonRootManagedBranchSnapshot> path, StringBuilder sb) {
sb.append(branch.getName());
val currBranch = gitMacheteRepositorySnapshot.getCurrentBranchIfManaged();
if (currBranch != null && currBranch == branch)
sb.append(" *");
val customAnnotation = branch.getCustomAnnotation();
if (customAnnotation != null) {
sb.append(" ");
sb.append(customAnnotation);
}
val relationToRemote = branch.getRelationToRemote();
SyncToRemoteStatus syncToRemoteStatus = relationToRemote.getSyncToRemoteStatus();
if (syncToRemoteStatus != NoRemotes && syncToRemoteStatus != InSyncToRemote) {
val remoteName = relationToRemote.getRemoteName();
sb.append(" (");
sb.append(switch (syncToRemoteStatus) {
case Untracked -> "untracked";
case AheadOfRemote -> "ahead of " + remoteName;
case BehindRemote -> "behind " + remoteName;
case DivergedFromAndNewerThanRemote -> "diverged from " + remoteName;
case DivergedFromAndOlderThanRemote -> "diverged from & older than " + remoteName;
case InSyncToRemote, NoRemotes -> throw new IllegalStateException("Unexpected value: " + syncToRemoteStatus);
});
sb.append(")");
}
val statusHookOutput = branch.getStatusHookOutput();
if (statusHookOutput != null) {
sb.append(" ");
sb.append(statusHookOutput);
}
sb.append(System.lineSeparator());
for (val childBranch : branch.getChildren()) {
printNonRootBranch(gitMacheteRepositorySnapshot, childBranch, path.append(childBranch), sb);
}
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/integration/RegenerateCliOutputs.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/integration/RegenerateCliOutputs.java | package com.virtuslab.gitmachete.backend.integration;
import static com.virtuslab.gitmachete.testcommon.SetupScripts.ALL_SETUP_SCRIPTS;
import static com.virtuslab.gitmachete.testcommon.TestFileUtils.cleanUpDir;
import static com.virtuslab.gitmachete.testcommon.TestFileUtils.copyScriptFromResources;
import static com.virtuslab.gitmachete.testcommon.TestFileUtils.prepareRepoFromScript;
import static com.virtuslab.gitmachete.testcommon.TestFileUtils.saveFile;
import static com.virtuslab.gitmachete.testcommon.TestProcessUtils.runProcessAndReturnStdout;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import io.vavr.collection.List;
import io.vavr.collection.Stream;
import lombok.SneakyThrows;
public class RegenerateCliOutputs {
@SneakyThrows
public static void main(String[] args) {
Path outputDirectory = Paths.get(args[0]);
String versionOutput = runGitMacheteCommandAndReturnStdout(/* timeoutSeconds */ 5, /* command */ "version");
saveFile(outputDirectory, "version.txt", versionOutput);
for (String scriptName : ALL_SETUP_SCRIPTS) {
System.out.println("Regenerating the output for ${scriptName}...");
Path parentDir = Files.createTempDirectory("machete-tests-");
Path repositoryMainDir = parentDir.resolve("machete-sandbox");
copyScriptFromResources("common.sh", parentDir);
copyScriptFromResources(scriptName, parentDir);
prepareRepoFromScript(scriptName, parentDir);
String statusOutput = runGitMacheteCommandAndReturnStdout(/* workingDirectory */ repositoryMainDir,
/* timeoutSeconds */ 15, /* command */ "status", "--list-commits");
saveFile(outputDirectory, "${scriptName}-status.txt", statusOutput);
String rawDiscoverOutput = runGitMacheteCommandAndReturnStdout(/* workingDirectory */ repositoryMainDir,
/* timeoutSeconds */ 15, /* command */ "discover", "--list-commits", "--yes");
String discoverOutput = Stream.of(rawDiscoverOutput.split(System.lineSeparator()))
.drop(2) // Let's skip the informational output at the beginning and at the end.
.dropRight(2)
.mkString(System.lineSeparator());
saveFile(outputDirectory, "${scriptName}-discover.txt", discoverOutput);
cleanUpDir(parentDir);
}
}
@SneakyThrows
private static String runGitMacheteCommandAndReturnStdout(Path workingDirectory, int timeoutSeconds, String... arguments) {
String[] commandAndArgs = List.of("git", "machete").appendAll(List.of(arguments)).toJavaArray(String[]::new);
return runProcessAndReturnStdout(workingDirectory, timeoutSeconds, commandAndArgs);
}
private static String runGitMacheteCommandAndReturnStdout(int timeoutSeconds, String... command) {
Path currentDir = Paths.get(".").toAbsolutePath().normalize();
return runGitMacheteCommandAndReturnStdout(currentDir, timeoutSeconds, command);
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/integration/BaseIntegrationTestSuite.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/integration/BaseIntegrationTestSuite.java | package com.virtuslab.gitmachete.backend.integration;
import java.io.FileInputStream;
import lombok.SneakyThrows;
import lombok.val;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.branchlayout.api.readwrite.IBranchLayoutReader;
import com.virtuslab.branchlayout.impl.readwrite.BranchLayoutReader;
import com.virtuslab.gitcore.api.IGitCoreRepositoryFactory;
import com.virtuslab.gitcore.impl.jgit.GitCoreRepositoryFactory;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepository;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositoryCache;
import com.virtuslab.gitmachete.backend.impl.GitMacheteRepositoryCache;
import com.virtuslab.gitmachete.testcommon.TestGitRepository;
class BaseIntegrationTestSuite {
protected static final IGitCoreRepositoryFactory gitCoreRepositoryFactory = new GitCoreRepositoryFactory();
protected static final IGitMacheteRepositoryCache gitMacheteRepositoryCache = new GitMacheteRepositoryCache();
protected static final IBranchLayoutReader branchLayoutReader = new BranchLayoutReader();
protected TestGitRepository repo;
protected IGitMacheteRepository gitMacheteRepository;
protected BranchLayout branchLayout;
@SneakyThrows
public void setUp(String scriptName) {
repo = new TestGitRepository(scriptName);
val injector = new IGitMacheteRepositoryCache.Injector() {
@Override
@SuppressWarnings("unchecked")
public <T> T inject(Class<T> clazz) {
return (T) gitCoreRepositoryFactory;
}
};
gitMacheteRepository = gitMacheteRepositoryCache.getInstance(repo.rootDirectoryPath, repo.mainGitDirectoryPath,
repo.worktreeGitDirectoryPath, injector);
branchLayout = branchLayoutReader.read(new FileInputStream(repo.mainGitDirectoryPath.resolve("machete").toFile()));
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/integration/ParentInferenceIntegrationTestSuite.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/integration/ParentInferenceIntegrationTestSuite.java | package com.virtuslab.gitmachete.backend.integration;
import static com.virtuslab.gitmachete.testcommon.SetupScripts.SETUP_FOR_OVERRIDDEN_FORK_POINT;
import static com.virtuslab.gitmachete.testcommon.SetupScripts.SETUP_FOR_YELLOW_EDGES;
import static com.virtuslab.gitmachete.testcommon.SetupScripts.SETUP_WITH_SINGLE_REMOTE;
import static com.virtuslab.gitmachete.testcommon.TestFileUtils.cleanUpDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
public class ParentInferenceIntegrationTestSuite extends BaseIntegrationTestSuite {
public static String[][] getTestData() {
return new String[][]{
// script name, for branch, expected parent
{SETUP_FOR_OVERRIDDEN_FORK_POINT, "allow-ownership-link", "develop"},
{SETUP_FOR_YELLOW_EDGES, "allow-ownership-link", "develop"},
{SETUP_FOR_YELLOW_EDGES, "drop-constraint", "call-ws"},
{SETUP_WITH_SINGLE_REMOTE, "drop-constraint", "call-ws"},
};
}
@ParameterizedTest
@MethodSource("getTestData")
@SneakyThrows
public void parentIsCorrectlyInferred(String scriptName, String forBranch, String expectedParent) {
setUp(scriptName);
val gitMacheteRepositorySnapshot = gitMacheteRepository.createSnapshotForLayout(branchLayout);
val managedBranchNames = gitMacheteRepositorySnapshot.getManagedBranches().map(IManagedBranchSnapshot::getName).toSet();
val result = gitMacheteRepository.inferParentForLocalBranch(managedBranchNames, forBranch);
assertNotNull(result);
assertEquals(expectedParent, result.getName());
// Deliberately done in the test and in not an @After method, so that the directory is retained in case of test failure.
cleanUpDir(repo.parentDirectoryPath);
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/UnitTestUtils.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/UnitTestUtils.java | package com.virtuslab.gitmachete.backend.unit;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import io.vavr.NotImplementedError;
import io.vavr.collection.List;
import lombok.SneakyThrows;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitcore.api.IGitCoreCheckoutEntry;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitcore.api.IGitCoreCommitHash;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreObjectHash;
import com.virtuslab.gitcore.api.IGitCoreReflogEntry;
import com.virtuslab.gitcore.api.IGitCoreTreeHash;
class UnitTestUtils {
private static final AtomicInteger counter = new AtomicInteger(0);
static TestGitCoreCommit createGitCoreCommit() {
return new TestGitCoreCommit();
}
@SneakyThrows
static IGitCoreLocalBranchSnapshot createGitCoreLocalBranch(IGitCoreCommit pointedCommit,
IGitCoreReflogEntry... reflogEntries) {
IGitCoreLocalBranchSnapshot mock = mock(IGitCoreLocalBranchSnapshot.class);
when(mock.getFullName()).thenReturn(String.valueOf(counter.incrementAndGet()));
when(mock.getPointedCommit()).thenReturn(pointedCommit);
when(mock.getReflogFromMostRecent()).thenReturn(List.ofAll(Stream.of(reflogEntries)));
when(mock.getRemoteTrackingBranch()).thenReturn(null);
return mock;
}
static class TestGitCoreCommitHash implements IGitCoreCommitHash {
private final int id;
TestGitCoreCommitHash() {
id = counter.incrementAndGet();
}
@Override
public String getHashString() {
return String.format("%40d", id);
}
@Override
public boolean equals(@Nullable Object other) {
return IGitCoreObjectHash.defaultEquals(this, other);
}
@Override
public int hashCode() {
return IGitCoreObjectHash.defaultHashCode(this);
}
}
static class TestGitCoreReflogEntry implements IGitCoreReflogEntry {
@Override
public String getComment() {
return "Lorem ipsum";
}
@Override
public Instant getTimestamp() {
return Instant.now();
}
@Override
public @Nullable IGitCoreCommitHash getOldCommitHash() {
return new TestGitCoreCommitHash();
}
@Override
public IGitCoreCommitHash getNewCommitHash() {
return new TestGitCoreCommitHash();
}
@Override
public @Nullable IGitCoreCheckoutEntry parseCheckout() {
return null;
}
}
static class TestGitCoreCommit implements IGitCoreCommit {
@Override
public String getShortMessage() {
return "test commit message";
}
@Override
public String getFullMessage() {
return getShortMessage();
}
@Override
public Instant getCommitTime() {
throw new NotImplementedError();
}
@Override
public IGitCoreCommitHash getHash() {
return new TestGitCoreCommitHash();
}
@Override
public IGitCoreTreeHash getTreeHash() {
throw new NotImplementedError();
}
@Override
public final boolean equals(@Nullable Object other) {
return IGitCoreCommit.defaultEquals(this, other);
}
@Override
public final int hashCode() {
return IGitCoreCommit.defaultHashCode(this);
}
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/GitMacheteRepository_deriveParentAwareForkPoint_UnitTestSuite.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/GitMacheteRepository_deriveParentAwareForkPoint_UnitTestSuite.java | package com.virtuslab.gitmachete.backend.unit;
import static com.virtuslab.gitmachete.backend.unit.UnitTestUtils.createGitCoreCommit;
import static com.virtuslab.gitmachete.backend.unit.UnitTestUtils.createGitCoreLocalBranch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
import io.vavr.collection.Stream;
import lombok.SneakyThrows;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.jupiter.api.Test;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitmachete.backend.impl.ForkPointCommitOfManagedBranch;
public class GitMacheteRepository_deriveParentAwareForkPoint_UnitTestSuite extends BaseGitMacheteRepositoryUnitTestSuite {
@SneakyThrows
private @Nullable IGitCoreCommit invokeDeriveParentAwareForkPoint(
IGitCoreLocalBranchSnapshot childBranch,
IGitCoreLocalBranchSnapshot parentBranch) {
when(gitCoreRepository.deriveConfigValue(any(), any(), any())).thenReturn(null);
ForkPointCommitOfManagedBranch forkPoint = aux(childBranch, parentBranch).deriveParentAwareForkPoint(childBranch,
parentBranch);
if (forkPoint != null) {
return forkPoint.getCoreCommit();
} else {
return null;
}
}
@Test
@SneakyThrows
public void parentAgnosticForkPointIsMissingAndParentIsNotAncestorOfChild() {
// given
IGitCoreCommit childCommit = createGitCoreCommit();
IGitCoreCommit parentCommit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(childCommit);
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(parentCommit);
when(gitCoreRepository.ancestorsOf(eq(childCommit), anyInt())).thenReturn(Stream.empty());
when(gitCoreRepository.isAncestorOrEqual(parentCommit, childCommit)).thenReturn(false);
// when
IGitCoreCommit result = invokeDeriveParentAwareForkPoint(childBranch, parentBranch);
// then
assertNull(result);
}
@Test
@SneakyThrows
public void parentAgnosticForkPointIsMissingAndParentIsAncestorOfChild() {
// given
IGitCoreCommit parentCommit = createGitCoreCommit();
IGitCoreCommit childCommit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(parentCommit);
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(childCommit);
when(gitCoreRepository.ancestorsOf(eq(childCommit), anyInt())).thenReturn(Stream.empty());
when(gitCoreRepository.isAncestorOrEqual(parentCommit, childCommit)).thenReturn(true);
// when
IGitCoreCommit result = invokeDeriveParentAwareForkPoint(childBranch, parentBranch);
// then
assertEquals(parentCommit, result);
}
@Test
@SneakyThrows
public void parentIsNotAncestorOfForkPointAndParentIsAncestorOfChild() {
// given
IGitCoreCommit forkPointCommit = createGitCoreCommit();
IGitCoreCommit parentCommit = createGitCoreCommit();
IGitCoreCommit childCommit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(parentCommit);
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(childCommit);
when(gitCoreRepository.ancestorsOf(eq(childCommit), anyInt())).thenReturn(Stream.of(forkPointCommit));
when(gitCoreRepository.isAncestorOrEqual(parentCommit, forkPointCommit)).thenReturn(false);
when(gitCoreRepository.isAncestorOrEqual(parentCommit, childCommit)).thenReturn(true);
// when
IGitCoreCommit result = invokeDeriveParentAwareForkPoint(childBranch, parentBranch);
// then
assertEquals(parentCommit, result);
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/GitMacheteRepository_deriveSyncToParentStatus_UnitTestSuite.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/GitMacheteRepository_deriveSyncToParentStatus_UnitTestSuite.java | package com.virtuslab.gitmachete.backend.unit;
import static com.virtuslab.gitmachete.backend.unit.UnitTestUtils.TestGitCoreReflogEntry;
import static com.virtuslab.gitmachete.backend.unit.UnitTestUtils.createGitCoreCommit;
import static com.virtuslab.gitmachete.backend.unit.UnitTestUtils.createGitCoreLocalBranch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import io.vavr.collection.List;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.backend.impl.ForkPointCommitOfManagedBranch;
public class GitMacheteRepository_deriveSyncToParentStatus_UnitTestSuite extends BaseGitMacheteRepositoryUnitTestSuite {
private static final IGitCoreCommit MISSING_FORK_POINT = createGitCoreCommit();
@SneakyThrows
private SyncToParentStatus invokeDeriveSyncToParentStatus(
IGitCoreLocalBranchSnapshot childBranch,
IGitCoreLocalBranchSnapshot parentBranch,
IGitCoreCommit forkPointCommit) {
return aux().deriveSyncToParentStatus(
childBranch, parentBranch,
ForkPointCommitOfManagedBranch.inferred(forkPointCommit, /* containingBranches */ List.empty()));
}
@Test
public void branchAndParentPointingSameCommitAndBranchJustCreated_inSync() {
// given
IGitCoreCommit commit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(commit);
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(commit);
// when
SyncToParentStatus syncToParentStatus = invokeDeriveSyncToParentStatus(childBranch, parentBranch, MISSING_FORK_POINT);
// then
assertEquals(SyncToParentStatus.InSync, syncToParentStatus);
}
@Test
public void branchAndParentPointingSameCommitAndBranchNotJustCreated_merged() {
// given
IGitCoreCommit commit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(commit);
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(commit, new TestGitCoreReflogEntry());
// when
SyncToParentStatus syncToParentStatus = invokeDeriveSyncToParentStatus(childBranch, parentBranch, MISSING_FORK_POINT);
// then
assertEquals(SyncToParentStatus.MergedToParent, syncToParentStatus);
}
@Test
@SneakyThrows
public void parentPointedCommitIsAncestorOfBranchPointedCommitAndItsForkPoint_inSync() {
// given
IGitCoreCommit parentCommit = createGitCoreCommit();
IGitCoreCommit childCommit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(parentCommit);
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(childCommit);
when(gitCoreRepository.isAncestorOrEqual(parentCommit, childCommit)).thenReturn(true);
// when
SyncToParentStatus syncToParentStatus = invokeDeriveSyncToParentStatus(childBranch, parentBranch, parentCommit);
// then
assertEquals(SyncToParentStatus.InSync, syncToParentStatus);
}
@Test
@SneakyThrows
public void parentPointedCommitIsAncestorOfBranchPointedCommitButNotItsForkPoint_inSyncButOffForkPoint() {
// given
IGitCoreCommit forkPointCommit = createGitCoreCommit();
IGitCoreCommit parentCommit = createGitCoreCommit();
IGitCoreCommit childCommit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(parentCommit);
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(childCommit);
when(gitCoreRepository.isAncestorOrEqual(parentCommit, childCommit)).thenReturn(true);
// when
SyncToParentStatus syncToParentStatus = invokeDeriveSyncToParentStatus(childBranch, parentBranch, forkPointCommit);
// then
assertEquals(SyncToParentStatus.InSyncButForkPointOff, syncToParentStatus);
}
@Test
@SneakyThrows
public void branchPointedCommitIsAncestorOfParentPointedCommit_merged() {
// given
IGitCoreCommit childCommit = createGitCoreCommit();
IGitCoreCommit parentCommit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(childCommit);
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(parentCommit);
when(gitCoreRepository.isAncestorOrEqual(parentCommit, childCommit)).thenReturn(false);
when(gitCoreRepository.isAncestorOrEqual(childCommit, parentCommit)).thenReturn(true);
// when
SyncToParentStatus syncToParentStatus = invokeDeriveSyncToParentStatus(childBranch, parentBranch, MISSING_FORK_POINT);
// then
assertEquals(SyncToParentStatus.OutOfSync, syncToParentStatus);
}
@Test
@SneakyThrows
public void neitherBranchPointedCommitIsAncestorOfParentPointedCommitNorTheOtherWay_outOfSync() {
// given
IGitCoreCommit parentCommit = createGitCoreCommit();
IGitCoreCommit childCommit = createGitCoreCommit();
IGitCoreLocalBranchSnapshot parentBranch = createGitCoreLocalBranch(parentCommit);
IGitCoreLocalBranchSnapshot childBranch = createGitCoreLocalBranch(childCommit);
when(gitCoreRepository.isAncestorOrEqual(parentCommit, childCommit)).thenReturn(false);
when(gitCoreRepository.isAncestorOrEqual(childCommit, parentCommit)).thenReturn(false);
when(gitCoreRepository.deriveCommitRange(parentCommit, childCommit)).thenReturn(List.empty());
// when
SyncToParentStatus syncToParentStatus = invokeDeriveSyncToParentStatus(childBranch, parentBranch, MISSING_FORK_POINT);
// then
assertEquals(SyncToParentStatus.OutOfSync, syncToParentStatus);
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/GitMacheteRepository_deriveRelationToRemote_UnitTestSuite.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/GitMacheteRepository_deriveRelationToRemote_UnitTestSuite.java | package com.virtuslab.gitmachete.backend.unit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import io.vavr.collection.List;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.Test;
import com.virtuslab.gitcore.api.GitCoreRelativeCommitCount;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreRemoteBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.RelationToRemote;
import com.virtuslab.gitmachete.backend.api.SyncToRemoteStatus;
public class GitMacheteRepository_deriveRelationToRemote_UnitTestSuite extends BaseGitMacheteRepositoryUnitTestSuite {
private static final String ORIGIN = "origin";
private final IGitCoreLocalBranchSnapshot coreLocalBranch = mock(IGitCoreLocalBranchSnapshot.class);
private final IGitCoreRemoteBranchSnapshot coreRemoteBranch = mock(IGitCoreRemoteBranchSnapshot.class);
private final IGitCoreCommit coreLocalBranchCommit = mock(IGitCoreCommit.class);
private final IGitCoreCommit coreRemoteBranchCommit = mock(IGitCoreCommit.class);
@SneakyThrows
private RelationToRemote invokeDeriveRelationToRemote(IGitCoreLocalBranchSnapshot coreLocalBranch) {
return aux().deriveRelationToRemote(coreLocalBranch);
}
@Test
@SneakyThrows
public void deriveRelationToRemote_NoRemotes() {
// given
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.empty());
// when
RelationToRemote relationToRemote = invokeDeriveRelationToRemote(coreLocalBranch);
// then
assertEquals(SyncToRemoteStatus.NoRemotes, relationToRemote.getSyncToRemoteStatus());
}
@Test
@SneakyThrows
public void deriveRelationToRemote_Untracked() {
// given
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.of(ORIGIN));
when(coreLocalBranch.getRemoteTrackingBranch()).thenReturn(null);
// when
RelationToRemote relationToRemote = invokeDeriveRelationToRemote(coreLocalBranch);
// then
assertEquals(SyncToRemoteStatus.Untracked, relationToRemote.getSyncToRemoteStatus());
}
@Test
@SneakyThrows
public void deriveRelationToRemote_DivergedAndNewerThan() {
// given
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.of(ORIGIN));
when(coreLocalBranch.getRemoteTrackingBranch()).thenReturn(coreRemoteBranch);
when(coreLocalBranch.getPointedCommit()).thenReturn(coreLocalBranchCommit);
when(coreRemoteBranch.getPointedCommit()).thenReturn(coreRemoteBranchCommit);
val relativeCommitCount = GitCoreRelativeCommitCount.of(1, 1);
when(gitCoreRepository
.deriveRelativeCommitCount(coreLocalBranchCommit, coreRemoteBranchCommit)).thenReturn(relativeCommitCount);
Instant newerInstant = Instant.parse("2000-05-01T10:00:00Z");
Instant olderInstant = newerInstant.minus(10, ChronoUnit.MINUTES);
when(coreLocalBranchCommit.getCommitTime()).thenReturn(newerInstant);
when(coreRemoteBranchCommit.getCommitTime()).thenReturn(olderInstant);
// when
RelationToRemote relationToRemote = invokeDeriveRelationToRemote(coreLocalBranch);
// then
assertEquals(SyncToRemoteStatus.DivergedFromAndNewerThanRemote, relationToRemote.getSyncToRemoteStatus());
}
@Test
@SneakyThrows
public void deriveRelationToRemote_DivergedAndOlderThan() {
// given
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.of(ORIGIN));
when(coreLocalBranch.getRemoteTrackingBranch()).thenReturn(coreRemoteBranch);
when(coreLocalBranch.getPointedCommit()).thenReturn(coreLocalBranchCommit);
when(coreRemoteBranch.getPointedCommit()).thenReturn(coreRemoteBranchCommit);
val relativeCommitCount = GitCoreRelativeCommitCount.of(1, 2);
when(gitCoreRepository
.deriveRelativeCommitCount(coreLocalBranchCommit, coreRemoteBranchCommit)).thenReturn(relativeCommitCount);
Instant olderInstant = Instant.parse("2000-05-01T10:00:00Z");
Instant newerInstant = olderInstant.plus(10, ChronoUnit.MINUTES);
when(coreLocalBranchCommit.getCommitTime()).thenReturn(olderInstant);
when(coreRemoteBranchCommit.getCommitTime()).thenReturn(newerInstant);
// when
RelationToRemote relationToRemote = invokeDeriveRelationToRemote(coreLocalBranch);
// then
assertEquals(SyncToRemoteStatus.DivergedFromAndOlderThanRemote, relationToRemote.getSyncToRemoteStatus());
}
@Test
@SneakyThrows
public void deriveRelationToRemote_DivergedAndNewerThan_theSameDates() {
// given
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.of(ORIGIN));
when(coreLocalBranch.getRemoteTrackingBranch()).thenReturn(coreRemoteBranch);
when(coreLocalBranch.getPointedCommit()).thenReturn(coreLocalBranchCommit);
when(coreRemoteBranch.getPointedCommit()).thenReturn(coreRemoteBranchCommit);
val relativeCommitCount = GitCoreRelativeCommitCount.of(2, 1);
when(gitCoreRepository
.deriveRelativeCommitCount(coreLocalBranchCommit, coreRemoteBranchCommit)).thenReturn(relativeCommitCount);
Instant instant = Instant.parse("2000-05-01T10:00:00Z");
when(coreLocalBranchCommit.getCommitTime()).thenReturn(instant);
when(coreRemoteBranchCommit.getCommitTime()).thenReturn(instant);
// when
RelationToRemote relationToRemote = invokeDeriveRelationToRemote(coreLocalBranch);
// then
assertEquals(SyncToRemoteStatus.DivergedFromAndNewerThanRemote, relationToRemote.getSyncToRemoteStatus());
}
@Test
@SneakyThrows
public void deriveRelationToRemote_Ahead() {
// given
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.of(ORIGIN));
when(coreLocalBranch.getRemoteTrackingBranch()).thenReturn(coreRemoteBranch);
when(coreLocalBranch.getPointedCommit()).thenReturn(coreLocalBranchCommit);
when(coreRemoteBranch.getPointedCommit()).thenReturn(coreRemoteBranchCommit);
val relativeCommitCount = GitCoreRelativeCommitCount.of(3, 0);
when(gitCoreRepository
.deriveRelativeCommitCount(coreLocalBranchCommit, coreRemoteBranchCommit)).thenReturn(relativeCommitCount);
// when
RelationToRemote relationToRemote = invokeDeriveRelationToRemote(coreLocalBranch);
// then
assertEquals(SyncToRemoteStatus.AheadOfRemote, relationToRemote.getSyncToRemoteStatus());
}
@Test
@SneakyThrows
public void deriveRelationToRemote_Behind() {
// given
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.of(ORIGIN));
when(coreLocalBranch.getRemoteTrackingBranch()).thenReturn(coreRemoteBranch);
when(coreLocalBranch.getPointedCommit()).thenReturn(coreLocalBranchCommit);
when(coreRemoteBranch.getPointedCommit()).thenReturn(coreRemoteBranchCommit);
val relativeCommitCount = GitCoreRelativeCommitCount.of(0, 3);
when(gitCoreRepository
.deriveRelativeCommitCount(coreLocalBranchCommit, coreRemoteBranchCommit)).thenReturn(relativeCommitCount);
// when
RelationToRemote relationToRemote = invokeDeriveRelationToRemote(coreLocalBranch);
// then
assertEquals(SyncToRemoteStatus.BehindRemote, relationToRemote.getSyncToRemoteStatus());
}
@Test
@SneakyThrows
public void deriveRelationToRemote_InSync() {
// given
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.of(ORIGIN));
when(coreLocalBranch.getRemoteTrackingBranch()).thenReturn(coreRemoteBranch);
when(coreLocalBranch.getPointedCommit()).thenReturn(coreLocalBranchCommit);
when(coreRemoteBranch.getPointedCommit()).thenReturn(coreRemoteBranchCommit);
val relativeCommitCount = GitCoreRelativeCommitCount.of(0, 0);
when(gitCoreRepository
.deriveRelativeCommitCount(coreLocalBranchCommit, coreRemoteBranchCommit)).thenReturn(relativeCommitCount);
// when
RelationToRemote relationToRemote = invokeDeriveRelationToRemote(coreLocalBranch);
// then
assertEquals(SyncToRemoteStatus.InSyncToRemote, relationToRemote.getSyncToRemoteStatus());
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/BaseGitMacheteRepositoryUnitTestSuite.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/BaseGitMacheteRepositoryUnitTestSuite.java | package com.virtuslab.gitmachete.backend.unit;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.nio.file.Paths;
import java.util.Arrays;
import io.vavr.collection.List;
import lombok.SneakyThrows;
import lombok.val;
import com.virtuslab.gitcore.api.IGitCoreHeadSnapshot;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreRepository;
import com.virtuslab.gitmachete.backend.impl.StatusBranchHookExecutor;
import com.virtuslab.gitmachete.backend.impl.helper.CreateGitMacheteRepositoryHelper;
public class BaseGitMacheteRepositoryUnitTestSuite {
protected final IGitCoreRepository gitCoreRepository = mock(IGitCoreRepository.class);
@SneakyThrows
protected CreateGitMacheteRepositoryHelper aux(IGitCoreLocalBranchSnapshot... localCoreBranches) {
when(gitCoreRepository.deriveAllLocalBranches()).thenReturn(List.ofAll(Arrays.stream(localCoreBranches)));
val iGitCoreHeadSnapshot = mock(IGitCoreHeadSnapshot.class);
when(iGitCoreHeadSnapshot.getTargetBranch()).thenReturn(null);
when(gitCoreRepository.deriveHead()).thenReturn(iGitCoreHeadSnapshot);
when(gitCoreRepository.deriveConfigValue("core", "hooksPath")).thenReturn(null);
when(gitCoreRepository.getRootDirectoryPath()).thenReturn(Paths.get("void"));
when(gitCoreRepository.getMainGitDirectoryPath()).thenReturn(Paths.get("void"));
// cannot be mocked as it is final
val statusBranchHookExecutor = new StatusBranchHookExecutor(gitCoreRepository);
return new CreateGitMacheteRepositoryHelper(gitCoreRepository, statusBranchHookExecutor);
}
}
| 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/backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/GitMacheteRepository_deriveCreatedAndDuplicatedAndSkippedBranches_UnitTestSuite.java | backend/impl/src/test/java/com/virtuslab/gitmachete/backend/unit/GitMacheteRepository_deriveCreatedAndDuplicatedAndSkippedBranches_UnitTestSuite.java | package com.virtuslab.gitmachete.backend.unit;
import static com.virtuslab.gitmachete.backend.unit.UnitTestUtils.createGitCoreCommit;
import static com.virtuslab.gitmachete.backend.unit.UnitTestUtils.createGitCoreLocalBranch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import io.vavr.collection.List;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.Test;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.branchlayout.api.BranchLayoutEntry;
import com.virtuslab.gitcore.api.GitCoreRepositoryState;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
public class GitMacheteRepository_deriveCreatedAndDuplicatedAndSkippedBranches_UnitTestSuite
extends
BaseGitMacheteRepositoryUnitTestSuite {
@SneakyThrows
private IGitMacheteRepositorySnapshot invokeCreateSnapshot(
BranchLayout branchLayout, IGitCoreLocalBranchSnapshot... localBranchSnapshots) {
when(gitCoreRepository.deriveAllRemoteNames()).thenReturn(List.empty());
when(gitCoreRepository.deriveRepositoryState()).thenReturn(GitCoreRepositoryState.NO_OPERATION);
return aux(localBranchSnapshots).createSnapshot(branchLayout);
}
@Test
public void singleBranch() {
// given
val branchAndEntry = createBranchAndEntry("main", List.empty());
val branchLayout = new BranchLayout(List.of(branchAndEntry.entry));
// when
val repositorySnapshot = invokeCreateSnapshot(branchLayout, branchAndEntry.branch);
// then
assertEquals(List.of(branchAndEntry.entry).map(BranchLayoutEntry::getName),
repositorySnapshot.getManagedBranches().map(IManagedBranchSnapshot::getName));
assertTrue(repositorySnapshot.getDuplicatedBranchNames().isEmpty());
assertTrue(repositorySnapshot.getSkippedBranchNames().isEmpty());
}
@Test
public void duplicatedBranch() {
// given
val mainBranchName = "main";
val duplicatedEntry = createEntry(mainBranchName, List.empty());
val branchAndEntry = createBranchAndEntry(mainBranchName, List.of(duplicatedEntry));
val branchLayout = new BranchLayout(List.of(branchAndEntry.entry));
// when
val repositorySnapshot = invokeCreateSnapshot(branchLayout, branchAndEntry.branch);
// then
assertEquals(List.of(branchAndEntry.entry).map(BranchLayoutEntry::getName),
repositorySnapshot.getManagedBranches().map(IManagedBranchSnapshot::getName));
assertEquals(List.of(mainBranchName).toSet(), repositorySnapshot.getDuplicatedBranchNames());
assertTrue(repositorySnapshot.getSkippedBranchNames().isEmpty());
}
@Test
public void skippedBranch() {
// given
val skippedBranchName = "skipped";
val skippedEntry = createEntry(skippedBranchName, List.empty());
val branchAndEntry = createBranchAndEntry("main", List.of(skippedEntry));
val branchLayout = new BranchLayout(List.of(branchAndEntry.entry));
// when
val repositorySnapshot = invokeCreateSnapshot(branchLayout, branchAndEntry.branch);
// then
assertEquals(List.of(branchAndEntry.entry).map(BranchLayoutEntry::getName),
repositorySnapshot.getManagedBranches().map(IManagedBranchSnapshot::getName));
assertTrue(repositorySnapshot.getDuplicatedBranchNames().isEmpty());
assertEquals(List.of(skippedBranchName).toSet(), repositorySnapshot.getSkippedBranchNames());
}
@Test
public void sameBranchDuplicatedAndSkipped() {
// given
val duplicatedAndSkippedBranchName = "duplicatedAndSkipped";
val duplicatedAndSkippedBranchName2 = createEntry(duplicatedAndSkippedBranchName, List.empty());
val duplicatedAndSkippedBranchName1 = createEntry(duplicatedAndSkippedBranchName, List.of(duplicatedAndSkippedBranchName2));
val branchAndEntry = createBranchAndEntry("main", List.of(duplicatedAndSkippedBranchName1));
val branchLayout = new BranchLayout(List.of(branchAndEntry.entry));
// when
val repositorySnapshot = invokeCreateSnapshot(branchLayout, branchAndEntry.branch);
// then
assertEquals(List.of(branchAndEntry.entry).map(BranchLayoutEntry::getName),
repositorySnapshot.getManagedBranches().map(IManagedBranchSnapshot::getName));
assertTrue(repositorySnapshot.getDuplicatedBranchNames().isEmpty());
assertEquals(List.of(duplicatedAndSkippedBranchName).toSet(), repositorySnapshot.getSkippedBranchNames());
}
private BranchAndEntry createBranchAndEntry(String name, List<BranchLayoutEntry> childEntries) {
val entry = createEntry(name, childEntries);
val commit = createGitCoreCommit();
val branch = createGitCoreLocalBranch(commit);
when(branch.getName()).thenReturn(name);
return new BranchAndEntry(branch, entry);
}
private BranchLayoutEntry createEntry(String name, List<BranchLayoutEntry> childEntries) {
return new BranchLayoutEntry(name, /* customAnnotation */ null, childEntries);
}
}
@AllArgsConstructor
class BranchAndEntry {
IGitCoreLocalBranchSnapshot branch;
BranchLayoutEntry entry;
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/StatusBranchHookExecutor.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/StatusBranchHookExecutor.java | package com.virtuslab.gitmachete.backend.impl;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ConcurrentHashMap;
import io.vavr.Tuple;
import io.vavr.Tuple3;
import io.vavr.collection.HashMap;
import io.vavr.control.Option;
import io.vavr.control.Try;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitcore.api.IGitCoreRepository;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.hooks.BaseHookExecutor;
import com.virtuslab.gitmachete.backend.hooks.OnExecutionTimeout;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
public final class StatusBranchHookExecutor extends BaseHookExecutor {
private static final int EXECUTION_TIMEOUT_SECONDS = 5;
// We're cheating a bit here: we're assuming that the hook's output is fixed
// for the given (branch-name, commit-hash, hook-script-hash) tuple.
// machete-status-branch hook spec doesn't impose any requirements like that, but:
// 1. it's pretty unlikely that any practically useful hook won't conform to this assumption,
// 2. this kind of caching is pretty useful wrt. performance.
private final java.util.Map<Tuple3<String, String, String>, Option<String>> hookOutputByBranchNameCommitHashAndHookHash = new ConcurrentHashMap<>();
@UIThreadUnsafe
public StatusBranchHookExecutor(IGitCoreRepository gitCoreRepository) {
super("machete-status-branch",
gitCoreRepository.getRootDirectoryPath(),
gitCoreRepository.getMainGitDirectoryPath(),
gitCoreRepository.deriveConfigValue("core", "hooksPath"));
}
/**
* @param branchName branch name
* @return stdout of the hook if it has been successfully executed.
* Null when the hook has not been executed (because it's absent or non-executable),
* or when the hook has been executed but exited with non-zero status code,
* or when the hook timed out.
* @throws GitMacheteException when an I/O exception occurs
*/
@UIThreadUnsafe
private @Nullable String executeHookFor(String branchName) throws GitMacheteException {
// According to machete-status-branch hook spec (`git machete help hooks`),
// the hook should receive `ASCII_ONLY=true` in its environment if only ASCII characters are expected in the output
// (so that the hook knows not to output any ANSI escape codes etc.).
HashMap<String, String> environment = HashMap.of("ASCII_ONLY", "true");
val result = executeHook(EXECUTION_TIMEOUT_SECONDS, OnExecutionTimeout.RETURN_NULL, environment, branchName);
if (result == null) {
return null;
}
if (result.getExitCode() != 0) {
LOG.warn("${name} hook for ${branchName} " +
"returned with a non-zero (${result.getExitCode()}) exit code; ignoring the output");
return null;
}
return result.getStdout();
}
@UIThreadUnsafe
public static String hashFile(String algorithm, File f) throws IOException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
DigestOutputStream out = new DigestOutputStream(OutputStream.nullOutputStream(), md)) {
in.transferTo(out);
}
return new BigInteger(/* signum */ 1, md.digest()).toString(16);
}
@UIThreadUnsafe
public @Nullable String deriveHookOutputFor(String branchName, CommitOfManagedBranch pointedCommit) {
var hookContentMD5Hash = "";
try {
hookContentMD5Hash = hashFile("MD5", hookFile);
} catch (IOException | NoSuchAlgorithmException ignored) {
// We are using the constant empty String as a neutral value, so that the functionality would
// fall back to not using the contents of the hookFile.
}
Tuple3<String, String, String> key = Tuple.of(branchName, pointedCommit.getHash(), hookContentMD5Hash);
return hookOutputByBranchNameCommitHashAndHookHash.computeIfAbsent(key,
k -> Try.of(() -> executeHookFor(k._1)).toOption()).getOrNull();
}
@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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/NonRootManagedBranchSnapshot.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/NonRootManagedBranchSnapshot.java | package com.virtuslab.gitmachete.backend.impl;
import io.vavr.collection.List;
import lombok.CustomLog;
import lombok.Getter;
import lombok.ToString;
import lombok.val;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.GitMacheteMissingForkPointException;
import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.api.IForkPointCommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.api.IGitRebaseParameters;
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.RelationToRemote;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
@CustomLog
@Getter
@ToString
public final class NonRootManagedBranchSnapshot extends BaseManagedBranchSnapshot implements INonRootManagedBranchSnapshot {
private @MonotonicNonNull IManagedBranchSnapshot parent = null;
private final @Nullable IForkPointCommitOfManagedBranch forkPoint;
private final List<ICommitOfManagedBranch> uniqueCommits;
private final List<ICommitOfManagedBranch> commitsUntilParent;
private final SyncToParentStatus syncToParentStatus;
@ToString.Include(name = "parent") // avoid recursive `toString` call on parent branch to avoid stack overflow
private @Nullable String getParentName() {
return parent != null ? parent.getName() : null;
}
public NonRootManagedBranchSnapshot(
String name,
String fullName,
List<NonRootManagedBranchSnapshot> children,
ICommitOfManagedBranch pointedCommit,
@Nullable IRemoteTrackingBranchReference remoteTrackingBranch,
RelationToRemote relationToRemote,
@Nullable String customAnnotation,
@Nullable String statusHookOutput,
@Nullable IForkPointCommitOfManagedBranch forkPoint,
List<ICommitOfManagedBranch> uniqueCommits,
List<ICommitOfManagedBranch> commitsUntilParent,
SyncToParentStatus syncToParentStatus) {
super(name, fullName, children, pointedCommit, remoteTrackingBranch, relationToRemote, customAnnotation, statusHookOutput);
this.forkPoint = forkPoint;
this.uniqueCommits = uniqueCommits;
this.commitsUntilParent = commitsUntilParent;
this.syncToParentStatus = syncToParentStatus;
LOG.debug("Creating ${this}");
// Note: since the class is final, `this` is already @Initialized at this point.
setParentForChildren();
}
@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 IForkPointCommitOfManagedBranch getForkPoint() {
return forkPoint;
}
@Override
public IGitRebaseParameters getParametersForRebaseOntoParent() throws GitMacheteMissingForkPointException {
LOG.debug(() -> "Entering: branch = '${getName()}'");
if (forkPoint == null) {
throw new GitMacheteMissingForkPointException("Cannot get fork point for branch '${getName()}'");
}
val newBaseBranch = getParent();
LOG.debug(() -> "Inferred rebase parameters: currentBranch = ${getName()}, " +
"newBaseCommit = ${newBaseBranch.getPointedCommit().getHash()}, " +
"forkPointCommit = ${forkPoint != null ? forkPoint.getHash() : null}");
return new GitRebaseParameters(/* currentBranch */ this, newBaseBranch, forkPoint);
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/GitRebaseParameters.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/GitRebaseParameters.java | package com.virtuslab.gitmachete.backend.impl;
import lombok.Data;
import lombok.ToString;
import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.api.IGitRebaseParameters;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
@Data
public class GitRebaseParameters implements IGitRebaseParameters {
private final IManagedBranchSnapshot currentBranch;
private final IManagedBranchSnapshot newBaseBranch;
private final ICommitOfManagedBranch forkPointCommit;
@ToString.Include(name = "currentBranch")
private String getCurrentBranchName() {
return currentBranch.getName();
}
@ToString.Include(name = "newBaseBranch")
private String getNewBaseBranchName() {
return newBaseBranch.getName();
}
@ToString.Include(name = "forkPointCommit")
private String getForkPointCommitShortHash() {
return forkPointCommit.getShortHash();
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/CommitOfManagedBranch.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/CommitOfManagedBranch.java | package com.virtuslab.gitmachete.backend.impl;
import java.time.Instant;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.value.qual.ArrayLen;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch;
@RequiredArgsConstructor
@ToString(onlyExplicitlyIncluded = true)
public class CommitOfManagedBranch implements ICommitOfManagedBranch {
@Getter
private final IGitCoreCommit coreCommit;
@Override
@ToString.Include(name = "shortMessage")
public String getShortMessage() {
return coreCommit.getShortMessage();
}
@Override
public String getFullMessage() {
return coreCommit.getFullMessage();
}
@Override
public @ArrayLen(40) String getHash() {
return coreCommit.getHash().getHashString();
}
@Override
@ToString.Include(name = "hash")
public @ArrayLen(7) String getShortHash() {
return coreCommit.getHash().getShortHashString();
}
@Override
public Instant getCommitTime() {
return coreCommit.getCommitTime();
}
@Override
public final boolean equals(@Nullable Object other) {
return ICommitOfManagedBranch.defaultEquals(this, other);
}
@Override
public final int hashCode() {
return ICommitOfManagedBranch.defaultHashCode(this);
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/GitMacheteRepositoryCache.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/GitMacheteRepositoryCache.java | package com.virtuslab.gitmachete.backend.impl;
import java.lang.ref.SoftReference;
import java.nio.file.Path;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.HashMap;
import io.vavr.collection.Map;
import lombok.val;
import com.virtuslab.gitcore.api.GitCoreException;
import com.virtuslab.gitcore.api.IGitCoreRepository;
import com.virtuslab.gitcore.api.IGitCoreRepositoryFactory;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepository;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositoryCache;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public class GitMacheteRepositoryCache implements IGitMacheteRepositoryCache {
private static Map<Tuple2<Path, Path>, SoftReference<GitMacheteRepository>> gitMacheteRepositoryCache = HashMap.empty();
@Override
@UIThreadUnsafe
public IGitMacheteRepository getInstance(Path rootDirectoryPath, Path mainGitDirectoryPath,
Path worktreeGitDirectoryPath, Injector injector)
throws GitMacheteException {
val key = Tuple.of(rootDirectoryPath, worktreeGitDirectoryPath);
val valueReference = gitMacheteRepositoryCache.get(key).getOrNull();
if (valueReference != null) {
val value = valueReference.get();
if (value != null) {
return value;
}
}
val gitCoreRepository = createGitCoreRepository(rootDirectoryPath, mainGitDirectoryPath, worktreeGitDirectoryPath,
injector);
val newValue = new GitMacheteRepository(gitCoreRepository);
gitMacheteRepositoryCache = gitMacheteRepositoryCache.put(key, new SoftReference<>(newValue));
return newValue;
}
@UIThreadUnsafe
private IGitCoreRepository createGitCoreRepository(Path rootDirectoryPath, Path mainGitDirectoryPath,
Path worktreeGitDirectoryPath, Injector injector) throws GitMacheteException {
try {
val gitCoreRepositoryFactory = injector.inject(IGitCoreRepositoryFactory.class);
return gitCoreRepositoryFactory.create(rootDirectoryPath, mainGitDirectoryPath, worktreeGitDirectoryPath);
} catch (GitCoreException e) {
throw new GitMacheteException("Can't create an ${IGitCoreRepository.class.getSimpleName()} instance " +
"under ${rootDirectoryPath} (with main git directory under ${mainGitDirectoryPath} " +
"and worktree git directory under ${worktreeGitDirectoryPath})", 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/RemoteTrackingBranchReference.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/RemoteTrackingBranchReference.java | package com.virtuslab.gitmachete.backend.impl;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.ExtensionMethod;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreRemoteBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
import com.virtuslab.gitmachete.backend.api.IRemoteTrackingBranchReference;
@ExtensionMethod(LocalBranchReference.class)
@Getter
@ToString
public final class RemoteTrackingBranchReference extends BaseBranchReference implements IRemoteTrackingBranchReference {
private final String remoteName;
private final ILocalBranchReference trackedLocalBranch;
private RemoteTrackingBranchReference(
String name, String fullName, String remoteName,
ILocalBranchReference trackedLocalBranch) {
super(name, fullName);
this.remoteName = remoteName;
this.trackedLocalBranch = trackedLocalBranch;
}
public static RemoteTrackingBranchReference of(IGitCoreRemoteBranchSnapshot coreRemoteBranch,
IGitCoreLocalBranchSnapshot coreTrackedLocalBranch) {
return new RemoteTrackingBranchReference(
coreRemoteBranch.getName(),
coreRemoteBranch.getFullName(),
coreRemoteBranch.getRemoteName(),
coreTrackedLocalBranch.toLocalBranchReference());
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/ForkPointCommitOfManagedBranch.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/ForkPointCommitOfManagedBranch.java | package com.virtuslab.gitmachete.backend.impl;
import io.vavr.collection.List;
import lombok.Getter;
import lombok.ToString;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
import com.virtuslab.gitmachete.backend.api.IForkPointCommitOfManagedBranch;
@ToString
public final class ForkPointCommitOfManagedBranch extends CommitOfManagedBranch implements IForkPointCommitOfManagedBranch {
@Getter
private final List<IBranchReference> branchesContainingInReflog;
@Getter
private final boolean isOverridden;
private ForkPointCommitOfManagedBranch(
IGitCoreCommit coreCommit,
List<IBranchReference> branchesContainingInReflog,
boolean isOverridden) {
super(coreCommit);
this.branchesContainingInReflog = branchesContainingInReflog;
this.isOverridden = isOverridden;
}
public static ForkPointCommitOfManagedBranch overridden(IGitCoreCommit overrideCoreCommit) {
return new ForkPointCommitOfManagedBranch(overrideCoreCommit, List.empty(), true);
}
public static ForkPointCommitOfManagedBranch inferred(
IGitCoreCommit coreCommit,
List<IBranchReference> branchesContainingInReflog) {
return new ForkPointCommitOfManagedBranch(coreCommit, branchesContainingInReflog, false);
}
public static ForkPointCommitOfManagedBranch fallbackToParent(IGitCoreCommit parentCoreCommit) {
return new ForkPointCommitOfManagedBranch(parentCoreCommit, List.empty(), false);
}
@Override
public List<IBranchReference> getUniqueBranchesContainingInReflog() {
return branchesContainingInReflog.reject(branch -> branch.isRemote()
&& branchesContainingInReflog.contains(branch.asRemote().getTrackedLocalBranch()));
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/LocalBranchReference.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/LocalBranchReference.java | package com.virtuslab.gitmachete.backend.impl;
import lombok.Getter;
import lombok.ToString;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
@Getter
@ToString
public final class LocalBranchReference extends BaseBranchReference implements ILocalBranchReference {
private LocalBranchReference(String name, String fullName) {
super(name, fullName);
}
public static LocalBranchReference toLocalBranchReference(IGitCoreLocalBranchSnapshot coreLocalBranch) {
return new LocalBranchReference(
coreLocalBranch.getName(),
coreLocalBranch.getFullName());
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/CreatedAndDuplicatedAndSkippedBranches.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/CreatedAndDuplicatedAndSkippedBranches.java | package com.virtuslab.gitmachete.backend.impl;
import io.vavr.collection.List;
import io.vavr.collection.Set;
import io.vavr.collection.TreeSet;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class CreatedAndDuplicatedAndSkippedBranches<T extends BaseManagedBranchSnapshot> {
private final List<T> createdBranches;
private final Set<String> duplicatedBranchNames;
private final Set<String> skippedBranchNames;
public CreatedAndDuplicatedAndSkippedBranches<T> withExtraDuplicatedBranch(String duplicatedBranchName) {
return new CreatedAndDuplicatedAndSkippedBranches<T>(getCreatedBranches(),
getDuplicatedBranchNames().add(duplicatedBranchName),
getSkippedBranchNames());
}
public CreatedAndDuplicatedAndSkippedBranches<T> withExtraSkippedBranch(String skippedBranchName) {
return new CreatedAndDuplicatedAndSkippedBranches<T>(getCreatedBranches(), getDuplicatedBranchNames(),
getSkippedBranchNames().add(skippedBranchName));
}
public static <T extends BaseManagedBranchSnapshot> CreatedAndDuplicatedAndSkippedBranches<T> of(List<T> createdBranches,
Set<String> duplicatedBranchName, Set<String> skippedBranchNames) {
return new CreatedAndDuplicatedAndSkippedBranches<T>(createdBranches, duplicatedBranchName, skippedBranchNames);
}
public static <T extends BaseManagedBranchSnapshot> CreatedAndDuplicatedAndSkippedBranches<T> empty() {
return new CreatedAndDuplicatedAndSkippedBranches<T>(List.empty(), TreeSet.empty(), TreeSet.empty());
}
public static <T extends BaseManagedBranchSnapshot> CreatedAndDuplicatedAndSkippedBranches<T> merge(
CreatedAndDuplicatedAndSkippedBranches<T> prevResult1, CreatedAndDuplicatedAndSkippedBranches<T> prevResult2) {
return new CreatedAndDuplicatedAndSkippedBranches<T>(
prevResult1.getCreatedBranches().appendAll(prevResult2.getCreatedBranches()),
prevResult1.getDuplicatedBranchNames().addAll(prevResult2.getDuplicatedBranchNames()),
prevResult1.getSkippedBranchNames().addAll(prevResult2.getSkippedBranchNames()));
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/BaseManagedBranchSnapshot.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/BaseManagedBranchSnapshot.java | package com.virtuslab.gitmachete.backend.impl;
import io.vavr.collection.List;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.val;
import org.checkerframework.checker.interning.qual.UsesObjectEquals;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.IRemoteTrackingBranchReference;
import com.virtuslab.gitmachete.backend.api.RelationToRemote;
@Getter
@ToString
@UsesObjectEquals
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class BaseManagedBranchSnapshot implements IManagedBranchSnapshot {
private final String name;
private final String fullName;
private final List<NonRootManagedBranchSnapshot> children;
private final ICommitOfManagedBranch pointedCommit;
private final @Nullable IRemoteTrackingBranchReference remoteTrackingBranch;
private final RelationToRemote relationToRemote;
private final @Nullable String customAnnotation;
private final @Nullable String statusHookOutput;
@ToString.Include(name = "children") // avoid recursive `toString` calls on child branches
private List<String> getChildNames() {
return children.map(e -> e.getName());
}
/**
* This is a hack necessary to create an immutable cyclic structure
* (children pointing at the parent and the parent pointing at the children).
* This is definitely not the cleanest solution, but still easier to manage and reason about than keeping the
* parent data somewhere outside of this class (e.g. in {@link GitMacheteRepositorySnapshot}).
*/
protected void setParentForChildren() {
for (val child : children) {
child.setParent(this);
}
}
@Override
public @Nullable IRemoteTrackingBranchReference getRemoteTrackingBranch() {
return remoteTrackingBranch;
}
@Override
public @Nullable String getCustomAnnotation() {
return customAnnotation;
}
@Override
public @Nullable String getStatusHookOutput() {
return statusHookOutput;
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/GitMacheteRepositorySnapshot.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/GitMacheteRepositorySnapshot.java | package com.virtuslab.gitmachete.backend.impl;
import java.nio.file.Path;
import io.vavr.collection.LinkedHashMap;
import io.vavr.collection.List;
import io.vavr.collection.Set;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
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.backend.api.IRootManagedBranchSnapshot;
@RequiredArgsConstructor
public class GitMacheteRepositorySnapshot implements IGitMacheteRepositorySnapshot {
@Getter
private final Path mainGitDirectoryPath;
@Getter
private final List<IRootManagedBranchSnapshot> rootBranches;
private final BranchLayout branchLayout;
private final @Nullable IManagedBranchSnapshot currentBranchIfManaged;
// Using LinkedHashMap to retain the original order of branches.
private final LinkedHashMap<String, IManagedBranchSnapshot> managedBranchByName;
@Getter
private final Set<String> duplicatedBranchNames;
@Getter
private final Set<String> skippedBranchNames;
@Getter
private final OngoingRepositoryOperation ongoingRepositoryOperation;
@Override
public BranchLayout getBranchLayout() {
return branchLayout;
}
@Override
public @Nullable IManagedBranchSnapshot getCurrentBranchIfManaged() {
return currentBranchIfManaged;
}
@Override
public List<IManagedBranchSnapshot> getManagedBranches() {
return managedBranchByName.values().toList();
}
@Override
public @Nullable IManagedBranchSnapshot getManagedBranchByName(String branchName) {
return managedBranchByName.get(branchName).getOrNull();
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/BaseBranchReference.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/BaseBranchReference.java | package com.virtuslab.gitmachete.backend.impl;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
@Getter
@RequiredArgsConstructor
@ToString
public abstract class BaseBranchReference implements IBranchReference {
private final String name;
private final String fullName;
@Override
public final boolean equals(@Nullable Object other) {
return IBranchReference.defaultEquals(this, other);
}
@Override
public final int hashCode() {
return IBranchReference.defaultHashCode(this);
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/RootManagedBranchSnapshot.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/RootManagedBranchSnapshot.java | package com.virtuslab.gitmachete.backend.impl;
import io.vavr.collection.List;
import lombok.CustomLog;
import lombok.ToString;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.ICommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.api.IRemoteTrackingBranchReference;
import com.virtuslab.gitmachete.backend.api.IRootManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.api.RelationToRemote;
@CustomLog
@ToString
public final class RootManagedBranchSnapshot extends BaseManagedBranchSnapshot implements IRootManagedBranchSnapshot {
public RootManagedBranchSnapshot(
String name,
String fullName,
List<NonRootManagedBranchSnapshot> children,
ICommitOfManagedBranch pointedCommit,
@Nullable IRemoteTrackingBranchReference remoteTrackingBranch,
RelationToRemote relationToRemote,
@Nullable String customAnnotation,
@Nullable String statusHookOutput) {
super(name, fullName, children, pointedCommit, remoteTrackingBranch, relationToRemote, customAnnotation, statusHookOutput);
LOG.debug("Creating ${this}");
// Note: since the class is final, `this` is already @Initialized at this point.
setParentForChildren();
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/GitMacheteRepository.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/GitMacheteRepository.java | package com.virtuslab.gitmachete.backend.impl;
import io.vavr.collection.Set;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.gitcore.api.GitCoreException;
import com.virtuslab.gitcore.api.IGitCoreRepository;
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.impl.helper.CreateGitMacheteRepositoryHelper;
import com.virtuslab.gitmachete.backend.impl.helper.DiscoverGitMacheteRepositoryHelper;
import com.virtuslab.gitmachete.backend.impl.helper.Helper;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public class GitMacheteRepository implements IGitMacheteRepository {
private final IGitCoreRepository gitCoreRepository;
private final StatusBranchHookExecutor statusHookExecutor;
private static final int NUMBER_OF_MOST_RECENTLY_CHECKED_OUT_BRANCHES_FOR_DISCOVER = 10;
@UIThreadUnsafe
public GitMacheteRepository(IGitCoreRepository gitCoreRepository) {
this.gitCoreRepository = gitCoreRepository;
this.statusHookExecutor = new StatusBranchHookExecutor(gitCoreRepository);
}
@Override
@UIThreadUnsafe
public IGitMacheteRepositorySnapshot createSnapshotForLayout(BranchLayout branchLayout) throws GitMacheteException {
try {
val helper = new CreateGitMacheteRepositoryHelper(gitCoreRepository, statusHookExecutor);
return helper.createSnapshot(branchLayout);
} catch (GitCoreException e) {
throw new GitMacheteException(e);
}
}
@Override
@UIThreadUnsafe
public @Nullable ILocalBranchReference inferParentForLocalBranch(
Set<String> eligibleLocalBranchNames,
String localBranchName) throws GitMacheteException {
try {
val helper = new Helper(gitCoreRepository);
return helper.inferParentForLocalBranch(eligibleLocalBranchNames, localBranchName);
} catch (GitCoreException e) {
throw new GitMacheteException(e);
}
}
@Override
@UIThreadUnsafe
public IGitMacheteRepositorySnapshot discoverLayoutAndCreateSnapshot() throws GitMacheteException {
try {
val helper = new DiscoverGitMacheteRepositoryHelper(gitCoreRepository, statusHookExecutor);
return helper.discoverLayoutAndCreateSnapshot(NUMBER_OF_MOST_RECENTLY_CHECKED_OUT_BRANCHES_FOR_DISCOVER);
} catch (GitCoreException e) {
throw new GitMacheteException(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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/helper/DiscoverGitMacheteRepositoryHelper.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/helper/DiscoverGitMacheteRepositoryHelper.java | package com.virtuslab.gitmachete.backend.impl.helper;
import java.time.Instant;
import io.vavr.Tuple;
import io.vavr.collection.HashMap;
import io.vavr.collection.List;
import io.vavr.collection.Map;
import io.vavr.collection.Seq;
import lombok.CustomLog;
import lombok.Getter;
import lombok.ToString;
import lombok.val;
import org.checkerframework.checker.initialization.qual.NotOnlyInitialized;
import org.checkerframework.checker.interning.qual.UsesObjectEquals;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.branchlayout.api.BranchLayoutEntry;
import com.virtuslab.gitcore.api.GitCoreException;
import com.virtuslab.gitcore.api.IGitCoreRepository;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
import com.virtuslab.gitmachete.backend.api.IGitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.api.SyncToParentStatus;
import com.virtuslab.gitmachete.backend.impl.StatusBranchHookExecutor;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
public class DiscoverGitMacheteRepositoryHelper extends CreateGitMacheteRepositoryHelper {
private static final String MASTER = "master";
private static final String MAIN = "main"; // see https://github.com/github/renaming
private static final String DEVELOP = "develop";
@UIThreadUnsafe
public DiscoverGitMacheteRepositoryHelper(
IGitCoreRepository gitCoreRepository,
StatusBranchHookExecutor statusHookExecutor) throws GitCoreException {
super(gitCoreRepository, statusHookExecutor);
}
/**
* A node of a mutable tree, with extra feature of near-constant time of checking up tree root thanks to path compression.
* See <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Find">Disjoint-set data structure on wikipedia</a>.
*/
@ToString
@UsesObjectEquals
private static class CompressablePathTreeNode {
@Getter
private final String name;
@Getter
private List<CompressablePathTreeNode> children;
@Getter
private @Nullable CompressablePathTreeNode parent;
private @NotOnlyInitialized CompressablePathTreeNode root;
CompressablePathTreeNode(String name) {
this.name = name;
this.children = List.empty();
this.parent = null;
this.root = this;
}
void attachUnder(CompressablePathTreeNode newParent) {
parent = newParent;
root = newParent.root;
}
void appendChild(CompressablePathTreeNode newChild) {
children = children.append(newChild);
}
void removeChild(CompressablePathTreeNode child) {
children = children.remove(child);
}
CompressablePathTreeNode getRoot() {
// The actual path compression happens here.
if (root != this && root.root != root) {
root = root.getRoot();
}
return root;
}
@ToString.Include(name = "children") // avoid recursive `toString` calls on children
private List<String> getChildNames() {
return children.map(e -> e.getName());
}
@ToString.Include(name = "parent") // avoid recursive `toString` call on parent
private @Nullable String getParentName() {
return parent != null ? parent.name : null;
}
@ToString.Include(name = "root") // avoid recursive `toString` call on root
private String getRootName() {
return root.name;
}
public BranchLayoutEntry toBranchLayoutEntry() {
return new BranchLayoutEntry(name, /* customAnnotation */ null, children.map(c -> c.toBranchLayoutEntry()));
}
}
@UIThreadUnsafe
private Map<String, Instant> deriveLastCheckoutTimestampByBranchName() throws GitCoreException {
java.util.Map<String, Instant> result = new java.util.HashMap<>();
for (val reflogEntry : gitCoreRepository.deriveHead().getReflogFromMostRecent()) {
val checkoutEntry = reflogEntry.parseCheckout();
if (checkoutEntry != null) {
val timestamp = reflogEntry.getTimestamp();
// `putIfAbsent` since we only care about the most recent occurrence of the given branch being checked out,
// and we iterate over the reflog starting from the latest entries.
result.putIfAbsent(checkoutEntry.getFromBranchName(), timestamp);
result.putIfAbsent(checkoutEntry.getToBranchName(), timestamp);
}
}
return HashMap.ofAll(result);
}
@UIThreadUnsafe
public IGitMacheteRepositorySnapshot discoverLayoutAndCreateSnapshot(int mostRecentlyCheckedOutBranchesCount)
throws GitMacheteException, GitCoreException {
List<String> localBranchNames = localBranches.map(lb -> lb.getName());
List<String> fixedRootBranchNames = List.empty();
List<String> nonFixedRootBranchNames = localBranchNames;
if (localBranchNames.contains(MASTER)) {
fixedRootBranchNames = fixedRootBranchNames.append(MASTER);
nonFixedRootBranchNames = nonFixedRootBranchNames.remove(MASTER);
} else if (localBranchNames.contains(MAIN)) {
fixedRootBranchNames = fixedRootBranchNames.append(MAIN);
nonFixedRootBranchNames = nonFixedRootBranchNames.remove(MAIN);
}
if (localBranchNames.contains(DEVELOP)) {
fixedRootBranchNames = fixedRootBranchNames.append(DEVELOP);
nonFixedRootBranchNames = nonFixedRootBranchNames.remove(DEVELOP);
}
List<String> freshNonFixedRootBranchNames;
// Let's only leave at most the given number of most recently checked out ("fresh") branches.
if (nonFixedRootBranchNames.size() <= mostRecentlyCheckedOutBranchesCount) {
freshNonFixedRootBranchNames = nonFixedRootBranchNames;
} else {
Map<String, Instant> lastCheckoutTimestampByBranchName = deriveLastCheckoutTimestampByBranchName();
val freshAndStaleNonFixedRootBranchNames = nonFixedRootBranchNames
.sortBy(branchName -> lastCheckoutTimestampByBranchName.getOrElse(branchName, Instant.MIN))
.reverse()
.splitAt(mostRecentlyCheckedOutBranchesCount);
freshNonFixedRootBranchNames = freshAndStaleNonFixedRootBranchNames._1.sorted();
LOG.debug(() -> "Skipping stale branches from the discovered layout: "
+ freshAndStaleNonFixedRootBranchNames._2.mkString(", "));
}
// Let's use linked maps to ensure a deterministic result.
Map<String, CompressablePathTreeNode> nodeByFixedRootBranchNames = fixedRootBranchNames
.toLinkedMap(name -> Tuple.of(name, new CompressablePathTreeNode(name)));
Map<String, CompressablePathTreeNode> nodeByFreshNonFixedRootBranch = freshNonFixedRootBranchNames
.toLinkedMap(name -> Tuple.of(name, new CompressablePathTreeNode(name)));
Map<String, CompressablePathTreeNode> nodeByIncludedBranchName = nodeByFixedRootBranchNames
.merge(nodeByFreshNonFixedRootBranch);
LOG.debug(() -> "Branches included in the discovered layout: " + nodeByIncludedBranchName.keySet().mkString(", "));
// `roots` may be an empty list in the rare case there's no master/main/develop branch in the repository.
List<CompressablePathTreeNode> roots = nodeByFixedRootBranchNames.values().toList();
// Skipping the parent inference for fixed roots and for the stale non-fixed-root branches.
for (val branchNode : nodeByFreshNonFixedRootBranch.values()) {
// Note that stale non-fixed-root branches are never considered as candidates for the parent.
Seq<String> parentCandidateNames = nodeByIncludedBranchName.values()
.filter(e -> e.getRoot() != branchNode)
.map(e -> e.getName());
LOG.debug(() -> "Parent candidate(s) for ${branchNode.getName()}: " + parentCandidateNames.mkString(", "));
IBranchReference parent = inferParentForLocalBranch(parentCandidateNames.toSet(), branchNode.getName());
if (parent != null) {
String parentName = parent.getName();
LOG.debug(() -> "Parent inferred for ${branchNode.getName()} is ${parentName}");
val parentNode = nodeByIncludedBranchName.get(parentName).getOrNull();
// Generally we expect an node for parent to always be present.
if (parentNode != null) {
branchNode.attachUnder(parentNode);
parentNode.appendChild(branchNode);
}
} else {
LOG.debug(() -> "No parent inferred for ${branchNode.getName()}; attaching as new root");
roots = roots.append(branchNode);
}
}
val NL = System.lineSeparator();
LOG.debug(() -> "Final discovered entries: " + NL + nodeByIncludedBranchName.values().mkString(NL));
// Post-process the discovered layout to remove the branches that would both:
// 1. have no child AND
// 2. be merged to their respective parents.
for (val branchNode : nodeByFreshNonFixedRootBranch.values()) {
if (branchNode.getChildren().nonEmpty()) {
continue;
}
val parentNode = branchNode.getParent();
if (parentNode == null) {
// This will happen for the roots of the discovered layout.
continue;
}
val branch = localBranchByName.get(branchNode.getName()).getOrNull();
val parentBranch = localBranchByName.get(parentNode.getName()).getOrNull();
if (branch == null || parentBranch == null) {
// This should never happen.
continue;
}
// A little hack wrt. fork point: we only want to distinguish between a branch merged or not merged to the parent,
// and fork point does not affect this specific distinction.
// It's in fact only useful for distinguishing between `InSync` and `InSyncButForkPointOff`,
// but here we don't care if the former is returned instead of the latter.
SyncToParentStatus syncStatus = deriveSyncToParentStatus(branch, parentBranch, /* forkPoint */ null);
if (syncStatus == SyncToParentStatus.MergedToParent) {
LOG.debug(() -> "Removing node for ${branchNode.getName()} " +
"since it's merged to its parent ${parentNode.getName()} and would have no children");
parentNode.removeChild(branchNode);
}
}
return createSnapshot(new BranchLayout(roots.map(r -> r.toBranchLayoutEntry())));
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/helper/CreateGitMacheteRepositoryHelper.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/helper/CreateGitMacheteRepositoryHelper.java | package com.virtuslab.gitmachete.backend.impl.helper;
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 java.nio.file.Path;
import java.time.Instant;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.LinkedHashMap;
import io.vavr.collection.List;
import io.vavr.collection.Seq;
import io.vavr.control.Try;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.branchlayout.api.BranchLayoutEntry;
import com.virtuslab.gitcore.api.GitCoreException;
import com.virtuslab.gitcore.api.GitCoreRelativeCommitCount;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreReflogEntry;
import com.virtuslab.gitcore.api.IGitCoreRemoteBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreRepository;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
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.IRemoteTrackingBranchReference;
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.impl.CommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.impl.CreatedAndDuplicatedAndSkippedBranches;
import com.virtuslab.gitmachete.backend.impl.ForkPointCommitOfManagedBranch;
import com.virtuslab.gitmachete.backend.impl.GitMacheteRepositorySnapshot;
import com.virtuslab.gitmachete.backend.impl.NonRootManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.impl.RemoteTrackingBranchReference;
import com.virtuslab.gitmachete.backend.impl.RootManagedBranchSnapshot;
import com.virtuslab.gitmachete.backend.impl.StatusBranchHookExecutor;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
public class CreateGitMacheteRepositoryHelper extends Helper {
private final StatusBranchHookExecutor statusHookExecutor;
private final List<String> remoteNames;
private final java.util.Set<String> createdBranches = new java.util.HashSet<>();
private final Path mainGitDirectoryPath;
@UIThreadUnsafe
public CreateGitMacheteRepositoryHelper(
IGitCoreRepository gitCoreRepository,
StatusBranchHookExecutor statusHookExecutor) throws GitCoreException {
super(gitCoreRepository);
this.statusHookExecutor = statusHookExecutor;
this.remoteNames = gitCoreRepository.deriveAllRemoteNames();
this.mainGitDirectoryPath = gitCoreRepository.getMainGitDirectoryPath();
}
@UIThreadUnsafe
public IGitMacheteRepositorySnapshot createSnapshot(BranchLayout branchLayout) throws GitMacheteException {
val rootBranchTries = branchLayout.getRootEntries().map(entry -> Try.of(() -> createGitMacheteRootBranch(entry)));
val rootBranchCreationResults = Try.sequence(rootBranchTries).getOrElseThrow(GitMacheteException::getOrWrap).toList();
val rootBranches = rootBranchCreationResults.flatMap(creationResult -> creationResult.getCreatedBranches());
val skippedBranchNames = rootBranchCreationResults.flatMap(creationResult -> creationResult.getSkippedBranchNames())
.toSet();
val duplicatedBranchNames = rootBranchCreationResults
.flatMap(creationResult -> creationResult.getDuplicatedBranchNames()).toSet();
val managedBranchByName = createManagedBranchByNameMap(rootBranches);
IGitCoreLocalBranchSnapshot coreCurrentBranch = deriveCoreCurrentBranch();
LOG.debug(() -> "Current branch: " + (coreCurrentBranch != null
? coreCurrentBranch.getName()
: "<none> (detached HEAD)"));
IManagedBranchSnapshot currentBranchIfManaged = coreCurrentBranch != null
? managedBranchByName.get(coreCurrentBranch.getName()).getOrNull()
: null;
LOG.debug(() -> "Current Git Machete branch (if managed): " + (currentBranchIfManaged != null
? currentBranchIfManaged.getName()
: "<none> (unmanaged branch or detached HEAD)"));
val ongoingOperationType = switch (gitCoreRepository.deriveRepositoryState()) {
case CHERRY_PICKING -> OngoingRepositoryOperationType.CHERRY_PICKING;
case MERGING -> OngoingRepositoryOperationType.MERGING;
case REBASING -> OngoingRepositoryOperationType.REBASING;
case REVERTING -> OngoingRepositoryOperationType.REVERTING;
case APPLYING -> OngoingRepositoryOperationType.APPLYING;
case BISECTING -> OngoingRepositoryOperationType.BISECTING;
case NO_OPERATION -> OngoingRepositoryOperationType.NO_OPERATION;
};
val operationsBaseBranchName = deriveOngoingOperationsBaseBranchName(ongoingOperationType);
return new GitMacheteRepositorySnapshot(mainGitDirectoryPath, List.narrow(rootBranches), branchLayout,
currentBranchIfManaged, managedBranchByName, duplicatedBranchNames, skippedBranchNames,
new IGitMacheteRepositorySnapshot.OngoingRepositoryOperation(ongoingOperationType, operationsBaseBranchName));
}
@UIThreadUnsafe
private @Nullable String deriveOngoingOperationsBaseBranchName(OngoingRepositoryOperationType ongoingOperation)
throws GitMacheteException {
try {
if (ongoingOperation == OngoingRepositoryOperationType.REBASING) {
return gitCoreRepository.deriveRebasedBranch();
} else if (ongoingOperation == OngoingRepositoryOperationType.BISECTING) {
return gitCoreRepository.deriveBisectedBranch();
}
} catch (GitCoreException e) {
throw new GitMacheteException("Error occurred while getting the base branch of ongoing repository operation", e);
}
return null;
}
@UIThreadUnsafe
private @Nullable IGitCoreLocalBranchSnapshot deriveCoreCurrentBranch() throws GitMacheteException {
try {
return gitCoreRepository.deriveHead().getTargetBranch();
} catch (GitCoreException e) {
throw new GitMacheteException("Can't get current branch", e);
}
}
// Using LinkedHashMap to retain the original order of branches.
private LinkedHashMap<String, IManagedBranchSnapshot> createManagedBranchByNameMap(
List<RootManagedBranchSnapshot> rootBranches) {
LinkedHashMap<String, IManagedBranchSnapshot> branchByName = LinkedHashMap.empty();
List<IManagedBranchSnapshot> stack = List.ofAll(rootBranches);
// A non-recursive DFS over all branches
while (stack.nonEmpty()) {
val branch = stack.head();
branchByName = branchByName.put(branch.getName(), branch);
stack = stack.tail().prependAll(branch.getChildren());
}
return branchByName;
}
@UIThreadUnsafe
private CreatedAndDuplicatedAndSkippedBranches<RootManagedBranchSnapshot> createGitMacheteRootBranch(
BranchLayoutEntry entry) throws GitCoreException {
val branchName = entry.getName();
IGitCoreLocalBranchSnapshot coreLocalBranch = localBranchByName.get(branchName).getOrNull();
if (coreLocalBranch == null) {
val childBranchTries = entry.getChildren()
.map(childEntry -> Try.of(() -> createGitMacheteRootBranch(childEntry)));
val newRoots = Try.sequence(childBranchTries)
.getOrElseThrow(GitCoreException::getOrWrap)
.fold(CreatedAndDuplicatedAndSkippedBranches.empty(), CreatedAndDuplicatedAndSkippedBranches::merge);
return newRoots.withExtraSkippedBranch(branchName);
}
if (!createdBranches.add(branchName)) {
val childBranchTries = entry.getChildren()
.map(childEntry -> Try.of(() -> createGitMacheteRootBranch(childEntry)));
val newRoots = Try.sequence(childBranchTries)
.getOrElseThrow(GitCoreException::getOrWrap)
.fold(CreatedAndDuplicatedAndSkippedBranches.empty(), CreatedAndDuplicatedAndSkippedBranches::merge);
return newRoots.withExtraDuplicatedBranch(branchName);
}
val branchFullName = coreLocalBranch.getFullName();
IGitCoreCommit corePointedCommit = coreLocalBranch.getPointedCommit();
val pointedCommit = new CommitOfManagedBranch(corePointedCommit);
val relationToRemote = deriveRelationToRemote(coreLocalBranch);
val customAnnotation = entry.getCustomAnnotation();
val childBranches = deriveChildBranches(coreLocalBranch, entry.getChildren());
val remoteTrackingBranch = getRemoteTrackingBranchForCoreLocalBranch(coreLocalBranch);
val statusHookOutput = statusHookExecutor.deriveHookOutputFor(branchName, pointedCommit);
val createdRootBranch = new RootManagedBranchSnapshot(branchName, branchFullName,
childBranches.getCreatedBranches(), pointedCommit, remoteTrackingBranch, relationToRemote, customAnnotation,
statusHookOutput);
return CreatedAndDuplicatedAndSkippedBranches.of(List.of(createdRootBranch),
childBranches.getDuplicatedBranchNames(), childBranches.getSkippedBranchNames());
}
@UIThreadUnsafe
private CreatedAndDuplicatedAndSkippedBranches<NonRootManagedBranchSnapshot> createGitMacheteNonRootBranch(
IGitCoreLocalBranchSnapshot parentCoreLocalBranch,
BranchLayoutEntry entry) throws GitCoreException {
val branchName = entry.getName();
IGitCoreLocalBranchSnapshot coreLocalBranch = localBranchByName.get(branchName).getOrNull();
if (coreLocalBranch == null) {
CreatedAndDuplicatedAndSkippedBranches<NonRootManagedBranchSnapshot> childResult = deriveChildBranches(
parentCoreLocalBranch,
entry.getChildren());
return childResult.withExtraSkippedBranch(branchName);
}
if (!createdBranches.add(branchName)) {
CreatedAndDuplicatedAndSkippedBranches<NonRootManagedBranchSnapshot> childResult = deriveChildBranches(
parentCoreLocalBranch,
entry.getChildren());
return childResult.withExtraDuplicatedBranch(branchName);
}
val branchFullName = coreLocalBranch.getFullName();
IGitCoreCommit corePointedCommit = coreLocalBranch.getPointedCommit();
ForkPointCommitOfManagedBranch forkPoint = deriveParentAwareForkPoint(coreLocalBranch, parentCoreLocalBranch);
val syncToParentStatus = deriveSyncToParentStatus(coreLocalBranch, parentCoreLocalBranch, forkPoint);
List<IGitCoreCommit> uniqueCommits;
if (forkPoint == null) {
// That's a rare case in practice, mostly happens due to reflog expiry.
uniqueCommits = List.empty();
} else if (syncToParentStatus == SyncToParentStatus.MergedToParent) {
uniqueCommits = List.empty();
} else if (syncToParentStatus == SyncToParentStatus.InSyncButForkPointOff) {
// In case of yellow edge, we include the entire range from the commit pointed by the branch until its parent,
// and not until just its fork point. This makes it possible to highlight the fork point candidate on the commit listing.
uniqueCommits = gitCoreRepository.deriveCommitRange(corePointedCommit, parentCoreLocalBranch.getPointedCommit());
} else {
// We're handling the cases of green and red edges here.
uniqueCommits = gitCoreRepository.deriveCommitRange(corePointedCommit, forkPoint.getCoreCommit());
}
val pointedCommit = new CommitOfManagedBranch(corePointedCommit);
val relationToRemote = deriveRelationToRemote(coreLocalBranch);
val customAnnotation = entry.getCustomAnnotation();
val childBranches = deriveChildBranches(coreLocalBranch, entry.getChildren());
val remoteTrackingBranch = getRemoteTrackingBranchForCoreLocalBranch(coreLocalBranch);
val statusHookOutput = statusHookExecutor.deriveHookOutputFor(branchName, pointedCommit);
val commitsUntilParent = gitCoreRepository.deriveCommitRange(corePointedCommit, parentCoreLocalBranch.getPointedCommit());
val result = new NonRootManagedBranchSnapshot(branchName, branchFullName, childBranches.getCreatedBranches(),
pointedCommit, remoteTrackingBranch, relationToRemote, customAnnotation, statusHookOutput, forkPoint,
uniqueCommits.map(CommitOfManagedBranch::new), commitsUntilParent.map(CommitOfManagedBranch::new),
syncToParentStatus);
return CreatedAndDuplicatedAndSkippedBranches.of(List.of(result),
childBranches.getDuplicatedBranchNames(), childBranches.getSkippedBranchNames());
}
private @Nullable IRemoteTrackingBranchReference getRemoteTrackingBranchForCoreLocalBranch(
IGitCoreLocalBranchSnapshot coreLocalBranch) {
IGitCoreRemoteBranchSnapshot coreRemoteTrackingBranch = coreLocalBranch.getRemoteTrackingBranch();
if (coreRemoteTrackingBranch == null) {
return null;
}
return RemoteTrackingBranchReference.of(coreRemoteTrackingBranch, coreLocalBranch);
}
@UIThreadUnsafe
public @Nullable ForkPointCommitOfManagedBranch deriveParentAwareForkPoint(
IGitCoreLocalBranchSnapshot coreLocalBranch,
IGitCoreLocalBranchSnapshot parentCoreLocalBranch) throws GitCoreException {
LOG.debug(() -> "Entering: coreLocalBranch = '${coreLocalBranch.getName()}', " +
"parentCoreLocalBranch = '${parentCoreLocalBranch.getName()}'");
IGitCoreCommit overriddenForkPointCommit = deriveParentAgnosticOverriddenForkPoint(coreLocalBranch);
ForkPointCommitOfManagedBranch parentAgnosticForkPoint = overriddenForkPointCommit != null
? ForkPointCommitOfManagedBranch.overridden(overriddenForkPointCommit)
: deriveParentAgnosticInferredForkPoint(coreLocalBranch);
val parentAgnosticForkPointString = parentAgnosticForkPoint != null ? parentAgnosticForkPoint.toString() : "empty";
val parentPointedCommit = parentCoreLocalBranch.getPointedCommit();
val pointedCommit = coreLocalBranch.getPointedCommit();
LOG.debug(() -> "parentAgnosticForkPoint = ${parentAgnosticForkPointString}, " +
"parentPointedCommit = ${parentPointedCommit.getHash().getHashString()}, " +
"pointedCommit = ${pointedCommit.getHash().getHashString()}");
val isParentAncestorOfChild = gitCoreRepository.isAncestorOrEqual(parentPointedCommit, pointedCommit);
LOG.debug(() -> "Parent branch commit (${parentPointedCommit.getHash().getHashString()}) " +
"is${isParentAncestorOfChild ? \"\" : \" NOT\"} ancestor of commit " +
"${pointedCommit.getHash().getHashString()}");
if (isParentAncestorOfChild) {
if (parentAgnosticForkPoint != null) {
val isParentAncestorOfForkPoint = gitCoreRepository.isAncestorOrEqual(parentPointedCommit,
parentAgnosticForkPoint.getCoreCommit());
if (!isParentAncestorOfForkPoint) {
// If parent(A) is ancestor of A, and parent(A) is NOT ancestor of fork-point(A),
// then assume fork-point(A)=parent(A)
LOG.debug(() -> "Parent branch commit (${parentPointedCommit.getHash().getHashString()}) is ancestor of " +
"commit (${pointedCommit.getHash().getHashString()}) but parent branch commit " +
"is NOT ancestor of parent-agnostic fork point (${parentAgnosticForkPointString}), " +
"so we assume that parent-aware fork point = parent branch commit");
return ForkPointCommitOfManagedBranch.fallbackToParent(parentPointedCommit);
}
} else {
// If parent(A) is ancestor of A, and fork-point(A) is missing,
// then assume fork-point(A)=parent(A)
LOG.debug(() -> "Parent branch commit (${parentPointedCommit.getHash().getHashString()}) is ancestor of " +
"commit (${pointedCommit.getHash().getHashString()}) and parent-agnostic fork point is missing, " +
"so we assume that parent-aware fork point = parent branch commit");
return ForkPointCommitOfManagedBranch.fallbackToParent(parentPointedCommit);
}
} else { // parent is NOT an ancestor of the child
// Let's avoid including any commits reachable from the parent into unique range of commits for the given branch.
if (parentAgnosticForkPoint != null) {
val isForkPointAncestorOfParent = gitCoreRepository.isAncestorOrEqual(parentAgnosticForkPoint.getCoreCommit(),
parentPointedCommit);
if (isForkPointAncestorOfParent) {
val commonAncestor = gitCoreRepository.deriveAnyMergeBase(parentPointedCommit, pointedCommit);
return commonAncestor != null
? ForkPointCommitOfManagedBranch.fallbackToParent(commonAncestor)
: parentAgnosticForkPoint;
} else {
var improvedForkPoint = parentAgnosticForkPoint;
for (val uniqueContainingBranch : parentAgnosticForkPoint.getUniqueBranchesContainingInReflog()) {
val containingBranchPointedCommit = gitCoreRepository.parseRevision(uniqueContainingBranch.getFullName());
if (containingBranchPointedCommit == null) {
continue;
}
val commonAncestor = gitCoreRepository.deriveAnyMergeBase(pointedCommit, containingBranchPointedCommit);
if (commonAncestor == null) {
continue;
}
if (gitCoreRepository.isAncestor(improvedForkPoint.getCoreCommit(), commonAncestor)) {
improvedForkPoint = ForkPointCommitOfManagedBranch.inferred(commonAncestor, List.of(uniqueContainingBranch));
}
}
return improvedForkPoint;
}
} else {
val commonAncestor = gitCoreRepository.deriveAnyMergeBase(parentPointedCommit, pointedCommit);
return commonAncestor != null ? ForkPointCommitOfManagedBranch.fallbackToParent(commonAncestor) : null;
}
}
LOG.debug(() -> "Parent-aware fork point for branch ${coreLocalBranch.getName()} is ${parentAgnosticForkPointString}");
return parentAgnosticForkPoint;
}
@UIThreadUnsafe
private @Nullable IGitCoreCommit deriveParentAgnosticOverriddenForkPoint(IGitCoreLocalBranchSnapshot coreLocalBranch)
throws GitCoreException {
String section = "machete";
String subsectionPrefix = "overrideForkPoint";
String branchName = coreLocalBranch.getName();
// Section spans the characters before the first dot
// Name spans the characters after the last dot
// Subsection is everything else
String toRevision = gitCoreRepository
.deriveConfigValue(section, subsectionPrefix + "." + branchName, "to");
// Note that we're ignoring `...whileDescendantOf` config key completely, as a step towards complete removal.
if (toRevision == null) {
return null;
}
LOG.debug(() -> "Fork point override config for '${branchName}': <to>='${toRevision}'");
// Let's validate the config - we can't rule out that it's been tampered with,
// or (more realistically) that it points to a commit that has since been e.g. GC'ed out of the repository.
IGitCoreCommit toCommit = gitCoreRepository.parseRevision(toRevision);
if (toCommit == null) {
LOG.warn("Could not parse <to> (${toCommit}) into a valid commit, ignoring faulty fork point override");
return null;
}
// Now we know that the commit pointed by the config exists, but it still doesn't mean
// that it actually applies to the given branch AT THIS POINT
// (it could e.g. have been applicable earlier but now no longer applies).
val branchCommit = coreLocalBranch.getPointedCommit();
if (!gitCoreRepository.isAncestorOrEqual(toCommit, branchCommit)) {
LOG.debug(() -> "Branch ${branchName} (${branchCommit}) is NOT a descendant of <to> (${toCommit}), " +
"ignoring the outdated fork point override");
return null;
}
// Note that we still need to validate whether the fork point is a descendant of the branch's parent,
// but this will happen in parent-aware logic (and we're parent-agnostic here yet).
LOG.debug(() -> "Applying fork point override for '${branchName}' (${branchCommit}): ${toCommit}");
return toCommit;
}
@UIThreadUnsafe
private @Nullable ForkPointCommitOfManagedBranch deriveParentAgnosticInferredForkPoint(IGitCoreLocalBranchSnapshot branch)
throws GitCoreException {
LOG.debug(() -> "Entering: branch = '${branch.getFullName()}'");
Tuple2<IGitCoreCommit, Seq<IBranchReference>> forkPointAndContainingBranches = gitCoreRepository
.ancestorsOf(branch.getPointedCommit(), MAX_ANCESTOR_COMMIT_COUNT)
.map(commit -> {
Seq<IBranchReference> containingBranches = deriveBranchesContainingGivenCommitInReflog()
.getOrElse(commit.getHash(), List.empty())
.reject(candidateBranch -> {
ILocalBranchReference correspondingLocalBranch = candidateBranch.isLocal()
? candidateBranch.asLocal()
: candidateBranch.asRemote().getTrackedLocalBranch();
return correspondingLocalBranch.getName().equals(branch.getName());
});
return Tuple.of(commit, containingBranches);
})
.find(commitAndContainingBranches -> commitAndContainingBranches._2.nonEmpty())
.getOrNull();
if (forkPointAndContainingBranches != null) {
val forkPoint = forkPointAndContainingBranches._1;
val containingBranches = forkPointAndContainingBranches._2.toList();
LOG.debug(() -> "Commit ${forkPoint} found in filtered reflog(s) of ${containingBranches.mkString(\", \")}; " +
"returning as fork point for branch '${branch.getFullName()}'");
return ForkPointCommitOfManagedBranch.inferred(forkPoint, containingBranches);
} else {
LOG.debug(() -> "Fork for branch '${branch.getFullName()}' not found ");
return null;
}
}
@UIThreadUnsafe
private CreatedAndDuplicatedAndSkippedBranches<NonRootManagedBranchSnapshot> deriveChildBranches(
IGitCoreLocalBranchSnapshot parentCoreLocalBranch,
List<BranchLayoutEntry> entries) throws GitCoreException {
val childBranchTries = entries.map(entry -> Try.of(
() -> createGitMacheteNonRootBranch(parentCoreLocalBranch, entry)));
return Try.sequence(childBranchTries)
.getOrElseThrow(GitCoreException::getOrWrap)
.fold(CreatedAndDuplicatedAndSkippedBranches.empty(), CreatedAndDuplicatedAndSkippedBranches::merge);
}
@UIThreadUnsafe
public RelationToRemote deriveRelationToRemote(IGitCoreLocalBranchSnapshot coreLocalBranch) throws GitCoreException {
String localBranchName = coreLocalBranch.getName();
LOG.debug(() -> "Entering: coreLocalBranch = '${localBranchName}'");
if (remoteNames.isEmpty()) {
LOG.debug("There are no remotes");
return RelationToRemote.noRemotes();
}
IGitCoreRemoteBranchSnapshot coreRemoteBranch = coreLocalBranch.getRemoteTrackingBranch();
if (coreRemoteBranch == null) {
LOG.debug(() -> "Branch '${localBranchName}' is untracked");
return RelationToRemote.untracked();
}
GitCoreRelativeCommitCount relativeCommitCount = gitCoreRepository
.deriveRelativeCommitCount(coreLocalBranch.getPointedCommit(), coreRemoteBranch.getPointedCommit());
if (relativeCommitCount == null) {
LOG.debug(() -> "Relative commit count for '${localBranchName}' could not be determined");
return RelationToRemote.untracked();
}
String remoteName = coreRemoteBranch.getRemoteName();
RelationToRemote relationToRemote;
if (relativeCommitCount.getAhead() > 0 && relativeCommitCount.getBehind() > 0) {
Instant localBranchCommitDate = coreLocalBranch.getPointedCommit().getCommitTime();
Instant remoteBranchCommitDate = coreRemoteBranch.getPointedCommit().getCommitTime();
// In case when commit dates are equal we assume that our relation is `DivergedFromAndNewerThanRemote`
if (remoteBranchCommitDate.compareTo(localBranchCommitDate) > 0) {
relationToRemote = RelationToRemote.of(DivergedFromAndOlderThanRemote, remoteName);
} else {
if (remoteBranchCommitDate.compareTo(localBranchCommitDate) == 0) {
LOG.debug("Commit dates of both local and remote branches are the same, so we assume " +
"${DivergedFromAndNewerThanRemote} sync to remote status");
}
relationToRemote = RelationToRemote.of(DivergedFromAndNewerThanRemote, remoteName);
}
} else if (relativeCommitCount.getAhead() > 0) {
relationToRemote = RelationToRemote.of(AheadOfRemote, remoteName);
} else if (relativeCommitCount.getBehind() > 0) {
relationToRemote = RelationToRemote.of(BehindRemote, remoteName);
} else {
relationToRemote = RelationToRemote.of(InSyncToRemote, remoteName);
}
LOG.debug(() -> "Relation to remote for branch '${localBranchName}': ${relationToRemote.toString()}");
return relationToRemote;
}
private boolean hasJustBeenCreated(IGitCoreLocalBranchSnapshot branch) {
List<IGitCoreReflogEntry> reflog = deriveFilteredReflog(branch);
return reflog.isEmpty() || reflog.head().getOldCommitHash() == null;
}
@UIThreadUnsafe
private boolean isEquivalentTreeReachable(IGitCoreCommit equivalentTo, IGitCoreCommit reachableFrom)
throws GitCoreException {
val applicableCommits = gitCoreRepository.deriveCommitRange(/* fromInclusive */ reachableFrom,
/* untilExclusive */ equivalentTo);
return applicableCommits.exists(commit -> commit.getTreeHash().equals(equivalentTo.getTreeHash()));
}
@UIThreadUnsafe
public SyncToParentStatus deriveSyncToParentStatus(
IGitCoreLocalBranchSnapshot coreLocalBranch,
IGitCoreLocalBranchSnapshot parentCoreLocalBranch,
@Nullable ForkPointCommitOfManagedBranch forkPoint) throws GitCoreException {
val branchName = coreLocalBranch.getName();
val parentBranchName = parentCoreLocalBranch.getName();
LOG.debug(() -> "Entering: coreLocalBranch = '${branchName}', " +
"parentCoreLocalBranch = '${parentBranchName}', " +
"forkPoint = ${forkPoint})");
IGitCoreCommit parentPointedCommit = parentCoreLocalBranch.getPointedCommit();
IGitCoreCommit pointedCommit = coreLocalBranch.getPointedCommit();
LOG.debug(() -> "parentPointedCommit = ${parentPointedCommit.getHash().getHashString()}; " +
"pointedCommit = ${pointedCommit.getHash().getHashString()}");
if (pointedCommit.equals(parentPointedCommit)) {
if (hasJustBeenCreated(coreLocalBranch)) {
LOG.debug(() -> "Branch '${branchName}' has been detected as just created, so we assume it's in sync");
return SyncToParentStatus.InSync;
} else {
LOG.debug(
() -> "For this branch (${branchName}) its parent's commit is equal to this branch pointed commit "
+ "and this branch hasn't been detected as just created, so we assume it's merged");
return SyncToParentStatus.MergedToParent;
}
} else {
val isParentAncestorOfChild = gitCoreRepository.isAncestorOrEqual(
/* presumedAncestor */ parentPointedCommit, /* presumedDescendant */ pointedCommit);
if (isParentAncestorOfChild) {
if (forkPoint == null || forkPoint.isOverridden() || forkPoint.getCoreCommit().equals(parentPointedCommit)) {
LOG.debug(
() -> "For this branch (${branchName}) its parent's commit is ancestor of this branch pointed commit "
+ "and fork point is absent or overridden or equal to parent branch commit, " +
"so we assume that this branch is in sync");
return SyncToParentStatus.InSync;
} else {
LOG.debug(
() -> "For this branch (${branchName}) its parent's commit is ancestor of this branch pointed commit "
+ "but fork point is not overridden and not equal to parent branch commit, " +
"so we assume that this branch is in sync but with fork point off");
return SyncToParentStatus.InSyncButForkPointOff;
}
} else {
val isChildAncestorOfParent = gitCoreRepository.isAncestorOrEqual(
/* presumedAncestor */ pointedCommit, /* presumedDescendant */ parentPointedCommit);
if (isChildAncestorOfParent) {
if (hasJustBeenCreated(coreLocalBranch)) {
LOG.debug(() -> "Branch '${branchName}' has been detected as just created, so we assume it's out of sync");
return SyncToParentStatus.OutOfSync;
} else {
LOG.debug(
() -> "For this branch (${branchName}) its parent's commit is not ancestor of this branch pointed commit "
+ "but this branch pointed commit is ancestor of parent branch commit, "
+ "and this branch hasn't been detected as just created, so we assume it's merged");
return SyncToParentStatus.MergedToParent;
}
} else {
if (isEquivalentTreeReachable(/* equivalentTo */ pointedCommit, /* reachableFrom */ parentPointedCommit)) {
LOG.debug(
() -> "Branch (${branchName}) is probably squash-merged into ${parentBranchName}");
return SyncToParentStatus.MergedToParent;
} else {
LOG.debug(
() -> "For this branch (${branchName}) its parent's commit is not ancestor of this branch pointed commit "
+ "neither this branch pointed commit is ancestor of parent branch commit, "
+ "so we assume that this branch is out of sync");
return SyncToParentStatus.OutOfSync;
}
}
}
}
}
}
| 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/backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/helper/Helper.java | backend/impl/src/main/java/com/virtuslab/gitmachete/backend/impl/helper/Helper.java | package com.virtuslab.gitmachete.backend.impl.helper;
import java.util.function.Predicate;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.List;
import io.vavr.collection.Map;
import io.vavr.collection.Seq;
import io.vavr.collection.Set;
import io.vavr.control.Option;
import lombok.CustomLog;
import lombok.val;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitcore.api.GitCoreException;
import com.virtuslab.gitcore.api.IGitCoreBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitcore.api.IGitCoreCommitHash;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreReflogEntry;
import com.virtuslab.gitcore.api.IGitCoreRemoteBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreRepository;
import com.virtuslab.gitmachete.backend.api.IBranchReference;
import com.virtuslab.gitmachete.backend.api.ILocalBranchReference;
import com.virtuslab.gitmachete.backend.impl.LocalBranchReference;
import com.virtuslab.gitmachete.backend.impl.RemoteTrackingBranchReference;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
public class Helper {
/**
* Let's avoid loading too many commits when trying to find fork point.
* It's unlikely that anyone will have that many unique commits on a branch.
*/
protected static final int MAX_ANCESTOR_COMMIT_COUNT = 100;
protected final IGitCoreRepository gitCoreRepository;
protected final List<IGitCoreLocalBranchSnapshot> localBranches;
protected final Map<String, IGitCoreLocalBranchSnapshot> localBranchByName;
private final java.util.Map<IGitCoreBranchSnapshot, List<IGitCoreReflogEntry>> filteredReflogByBranch = new java.util.HashMap<>();
private @MonotonicNonNull Map<IGitCoreCommitHash, Seq<IBranchReference>> branchesContainingGivenCommitInReflog;
@UIThreadUnsafe
public Helper(IGitCoreRepository gitCoreRepository) throws GitCoreException {
this.gitCoreRepository = gitCoreRepository;
this.localBranches = gitCoreRepository.deriveAllLocalBranches();
this.localBranchByName = localBranches.toMap(localBranch -> Tuple.of(localBranch.getName(), localBranch));
}
protected Map<IGitCoreCommitHash, Seq<IBranchReference>> deriveBranchesContainingGivenCommitInReflog() {
if (branchesContainingGivenCommitInReflog != null) {
return branchesContainingGivenCommitInReflog;
}
LOG.debug("Getting reflogs of local branches");
Map<IBranchReference, List<IGitCoreReflogEntry>> filteredReflogByLocalBranch = localBranches
.toMap(
/* keyMapper */ LocalBranchReference::toLocalBranchReference,
/* valueMapper */ this::deriveFilteredReflog);
LOG.debug("Getting reflogs of remote branches");
@SuppressWarnings("nullness:assignment") List<Tuple2<IGitCoreLocalBranchSnapshot, IGitCoreRemoteBranchSnapshot>> remoteTrackingBranches = localBranches
.flatMap(localBranch -> Option.of(localBranch.getRemoteTrackingBranch())
.map(remoteTrackingBranch -> Tuple.of(localBranch, remoteTrackingBranch)));
Map<IBranchReference, List<IGitCoreReflogEntry>> filteredReflogByRemoteTrackingBranch = remoteTrackingBranches
.toMap(
/* keyMapper */ localAndRemote -> RemoteTrackingBranchReference.of(localAndRemote._2, localAndRemote._1),
/* valueMapper */ localAndRemote -> deriveFilteredReflog(localAndRemote._2));
LOG.debug("Converting reflogs to mapping of branches containing in reflog by commit");
Map<IBranchReference, List<IGitCoreReflogEntry>> filteredReflogsByBranch = filteredReflogByLocalBranch
.merge(filteredReflogByRemoteTrackingBranch);
LOG.trace(() -> "Filtered reflogs by branch name:");
LOG.trace(() -> filteredReflogsByBranch
.map(kv -> kv._1.getName() + " -> " + kv._2.map(e -> e.getNewCommitHash()).mkString(", "))
.sorted().mkString(System.lineSeparator()));
Seq<Tuple2<IGitCoreCommitHash, IBranchReference>> reflogCommitHashAndBranchPairs = filteredReflogsByBranch
.flatMap(branchAndReflog -> branchAndReflog._2
.map(re -> Tuple.of(re.getNewCommitHash(), branchAndReflog._1)));
val result = reflogCommitHashAndBranchPairs
.groupBy(reflogCommitHashAndBranch -> reflogCommitHashAndBranch._1)
.mapValues(pairsOfReflogCommitHashAndBranch -> pairsOfReflogCommitHashAndBranch
.map(reflogCommitHashAndBranch -> reflogCommitHashAndBranch._2));
LOG.debug("Derived the map of branches containing given commit in reflog:");
LOG.debug(() -> result.toList().map(kv -> {
val values = kv._2.mkString(", ");
return kv._1 + " -> " + values;
})
.sorted().mkString(System.lineSeparator()));
branchesContainingGivenCommitInReflog = result;
return result;
}
/**
* @return reflog entries, excluding branch creation and branch reset events irrelevant for fork point/parent inference,
* ordered from the latest to the oldest
*/
protected List<IGitCoreReflogEntry> deriveFilteredReflog(IGitCoreBranchSnapshot branch) {
if (filteredReflogByBranch.containsKey(branch)) {
return filteredReflogByBranch.get(branch);
}
LOG.trace(() -> "Entering: branch = '${branch.getFullName()}'; original list of entries:");
List<IGitCoreReflogEntry> reflogEntries = branch.getReflogFromMostRecent();
reflogEntries.forEach(entry -> LOG.trace(() -> "* ${entry}"));
IGitCoreCommitHash entryToExcludeNewId;
if (reflogEntries.size() > 0) {
val firstEntry = reflogEntries.get(reflogEntries.size() - 1);
String createdFromPrefix = "branch: Created from";
if (firstEntry.getComment().startsWith(createdFromPrefix)) {
entryToExcludeNewId = firstEntry.getNewCommitHash();
LOG.trace(() -> "All entries with the same hash as first entry (${firstEntry.getNewCommitHash().toString()}) " +
"will be excluded because first entry comment starts with '${createdFromPrefix}'");
} else {
entryToExcludeNewId = null;
}
} else {
entryToExcludeNewId = null;
}
String noOpRebaseCommentSuffix = branch.getFullName() + " onto " + branch.getPointedCommit().getHash().getHashString();
// It's necessary to exclude entry with the same hash as the first entry in reflog (if it still exists)
// for cases like branch rename just after branch creation.
Predicate<IGitCoreReflogEntry> isEntryExcluded = e -> {
String comment = e.getComment();
if (e.getNewCommitHash().equals(entryToExcludeNewId)) {
LOG.trace(() -> "Exclude ${e} because it has the same hash as first entry");
} else if (e.getOldCommitHash() != null && e.getNewCommitHash().equals(e.getOldCommitHash())) {
LOG.trace(() -> "Exclude ${e} because its old and new IDs are the same");
} else if (comment.startsWith("branch: Created from")) {
LOG.trace(() -> "Exclude ${e} because its comment starts with 'branch: Created from'");
} else if (comment.equals("branch: Reset to " + branch.getName())) {
LOG.trace(() -> "Exclude ${e} because its comment is '${comment}'");
} else if (comment.equals("branch: Reset to HEAD")) {
LOG.trace(() -> "Exclude ${e} because its comment is '${comment}'");
} else if (comment.startsWith("reset: moving to ")) {
LOG.trace(() -> "Exclude ${e} because its comment starts with 'reset: moving to '");
} else if (comment.startsWith("fetch . ")) {
LOG.trace(() -> "Exclude ${e} because its comment starts with 'fetch . '");
} else if (comment.equals("rebase finished: " + noOpRebaseCommentSuffix)
|| comment.equals("rebase -i (finish): " + noOpRebaseCommentSuffix)) {
LOG.trace(() -> "Exclude ${e} because its comment is '${comment}' which indicates a no-op rebase");
} else if (comment.equals("update by push")) {
LOG.trace(() -> "Exclude ${e} because its comment is '${comment}'");
} else {
return false;
}
return true;
};
val result = reflogEntries.reject(isEntryExcluded);
LOG.debug(() -> "Filtered reflog of ${branch.getFullName()}:");
LOG.debug(() -> result.mkString(System.lineSeparator()));
filteredReflogByBranch.put(branch, result);
return result;
}
private record CommitAndContainingBranches(IGitCoreCommit commit, Seq<ILocalBranchReference> containingBranches) {
}
@UIThreadUnsafe
@Nullable
public ILocalBranchReference inferParentForLocalBranch(
Set<String> eligibleLocalBranchNames,
String localBranchName) throws GitCoreException {
val localBranch = localBranchByName.get(localBranchName).getOrNull();
if (localBranch == null) {
return null;
}
LOG.debug(() -> "Branch(es) eligible for becoming the parent of ${localBranchName}: " +
"${eligibleLocalBranchNames.mkString(\", \")}");
CommitAndContainingBranches commitAndContainingBranches = gitCoreRepository
.ancestorsOf(localBranch.getPointedCommit(), MAX_ANCESTOR_COMMIT_COUNT)
.map(commit -> {
Seq<ILocalBranchReference> eligibleContainingBranches = deriveBranchesContainingGivenCommitInReflog()
.getOrElse(commit.getHash(), List.empty())
.map(candidateBranch -> candidateBranch.isLocal()
? candidateBranch.asLocal()
: candidateBranch.asRemote().getTrackedLocalBranch())
.filter(correspondingLocalBranch -> !correspondingLocalBranch.getName().equals(localBranch.getName())
&& eligibleLocalBranchNames.contains(correspondingLocalBranch.getName()));
return new CommitAndContainingBranches(commit, eligibleContainingBranches);
})
.find(ccbs -> ccbs.containingBranches.nonEmpty())
.getOrNull();
if (commitAndContainingBranches != null) {
val commit = commitAndContainingBranches.commit;
val containingBranches = commitAndContainingBranches.containingBranches.toList();
assert containingBranches.nonEmpty() : "containingBranches is empty";
val firstContainingBranch = containingBranches.head();
val containingBranchNames = containingBranches.map(IBranchReference::getName);
LOG.debug(() -> "Commit ${commit} found in filtered reflog(s) " +
"of managed branch(es) ${containingBranchNames.mkString(\", \")}; " +
"returning ${firstContainingBranch.getName()} as the inferred parent for branch '${localBranchName}'");
return firstContainingBranch;
} else {
LOG.debug(() -> "Could not infer parent for branch '${localBranchName}'");
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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/hooks/OnExecutionTimeout.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/hooks/OnExecutionTimeout.java | package com.virtuslab.gitmachete.backend.hooks;
public enum OnExecutionTimeout {
RETURN_NULL, THROW_EXCEPTION
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/hooks/BaseHookExecutor.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/hooks/BaseHookExecutor.java | package com.virtuslab.gitmachete.backend.hooks;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import io.vavr.collection.List;
import io.vavr.collection.Map;
import kr.pe.kwonnam.slf4jlambda.LambdaLogger;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitmachete.backend.api.GitMacheteException;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public abstract class BaseHookExecutor {
protected static final String NL = System.lineSeparator();
protected final String name;
protected final File rootDirectory;
protected final File hookFile;
protected BaseHookExecutor(String name, Path rootDirectoryPath, Path mainGitDirectoryPath,
@Nullable String gitConfigCoreHooksPath) {
this.name = name;
this.rootDirectory = rootDirectoryPath.toFile();
val hooksDirPath = gitConfigCoreHooksPath != null
? Paths.get(gitConfigCoreHooksPath)
: mainGitDirectoryPath.resolve("hooks");
this.hookFile = hooksDirPath.resolve(name).toFile();
}
protected abstract LambdaLogger log();
@UIThreadUnsafe
protected @Nullable ExecutionResult executeHook(int timeoutSeconds, OnExecutionTimeout onTimeout,
Map<String, String> environment, String... args)
throws GitMacheteException {
val argsToString = Arrays.toString(args);
val hookFilePath = hookFile.getAbsolutePath();
if (!hookFile.isFile()) {
log().debug(() -> "Skipping ${name} hook execution for ${argsToString}: ${hookFilePath} does not exist");
return null;
} else if (!hookFile.canExecute()) {
log().warn("Skipping ${name} hook execution for ${argsToString}: ${hookFilePath} cannot be executed");
return null;
}
log().debug(() -> "Executing ${name} hook (${hookFilePath}) for ${argsToString} in cwd=${rootDirectory}");
ProcessBuilder pb = new ProcessBuilder();
String[] commandAndArgs = List.of(args).prepend(hookFilePath).toJavaArray(String[]::new);
pb.command(commandAndArgs);
for (val item : environment) {
pb.environment().put(item._1(), item._2());
}
// According to git hooks spec (`git help hooks`):
// Before Git invokes a hook, it changes its working directory to either $GIT_DIR in a bare repository
// or the root of the working tree in a non-bare repository.
// An exception are hooks triggered during a push (...) which are always executed in $GIT_DIR.
// We obviously assume a non-bare repository here, and this hook isn't related to push.
pb.directory(rootDirectory);
Process process;
String strippedStdout = null;
String strippedStderr = null;
try {
process = pb.start();
boolean completed = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
// It's quite likely that the hook's output will be terminated with a newline,
// and we don't want that to be displayed.
strippedStdout = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8).trim();
strippedStderr = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8).trim();
if (!completed) {
val message = "${name} hook (${hookFilePath}) for ${argsToString} did not complete within ${timeoutSeconds} seconds";
if (onTimeout == OnExecutionTimeout.RETURN_NULL) {
log().warn(message);
return null;
} else {
log().error(message);
throw new GitMacheteException(message
+ (!strippedStdout.isBlank() ? NL + "stdout:" + NL + strippedStdout : "")
+ (!strippedStderr.isBlank() ? NL + "stderr:" + NL + strippedStderr : ""));
}
}
log().debug("Stdout of ${name} hook is '${strippedStdout}'");
log().debug("Stderr of ${name} hook is '${strippedStderr}'");
} catch (IOException | InterruptedException e) {
val message = "An error occurred while running ${name} hook (${hookFilePath}) for ${argsToString}; aborting";
log().error(message, e);
throw new GitMacheteException(message
+ (strippedStdout != null && !strippedStdout.isBlank() ? NL + "stdout:" + NL + strippedStdout : "")
+ (strippedStderr != null && !strippedStderr.isBlank() ? NL + "stderr:" + NL + strippedStderr : ""), e);
}
log().info(() -> "${name} hook (${hookFilePath}) for ${argsToString} " +
"returned with ${process.exitValue()} exit code");
return new ExecutionResult(process.exitValue(), strippedStdout, strippedStderr);
}
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/hooks/ExecutionResult.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/hooks/ExecutionResult.java | package com.virtuslab.gitmachete.backend.hooks;
import lombok.Data;
@Data
public class ExecutionResult {
private final int exitCode;
private final String stdout;
private final String stderr;
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/MacheteFileReaderException.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/MacheteFileReaderException.java | package com.virtuslab.gitmachete.backend.api;
import lombok.experimental.StandardException;
@StandardException
@SuppressWarnings("nullness:argument")
public class MacheteFileReaderException extends GitMacheteException {}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/RelationToRemote.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/RelationToRemote.java | package com.virtuslab.gitmachete.backend.api;
import lombok.Data;
import org.checkerframework.checker.nullness.qual.Nullable;
@Data(staticConstructor = "of")
// So that Interning Checker doesn't complain about enum comparison (by `equals` and not by `==`) in Lombok-generated `equals`
@SuppressWarnings("interning:unnecessary.equals")
public class RelationToRemote {
public static RelationToRemote noRemotes() {
return of(SyncToRemoteStatus.NoRemotes, null);
}
public static RelationToRemote untracked() {
return of(SyncToRemoteStatus.Untracked, null);
}
private final SyncToRemoteStatus syncToRemoteStatus;
private final @Nullable String remoteName;
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IGitMacheteRepositoryCache.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IGitMacheteRepositoryCache.java | package com.virtuslab.gitmachete.backend.api;
import java.nio.file.Path;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
/** Each implementing class must have a public parameterless constructor. */
public interface IGitMacheteRepositoryCache {
@FunctionalInterface
interface Injector {
<T> T inject(Class<T> clazz);
}
@UIThreadUnsafe
IGitMacheteRepository getInstance(Path rootDirectoryPath, Path mainGitDirectoryPath, Path worktreeGitDirectoryPath,
Injector injector)
throws GitMacheteException;
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/NullGitMacheteRepositorySnapshot.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/NullGitMacheteRepositorySnapshot.java | package com.virtuslab.gitmachete.backend.api;
import java.nio.file.Path;
import io.vavr.collection.List;
import io.vavr.collection.Set;
import io.vavr.collection.TreeSet;
import lombok.Getter;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
public final class NullGitMacheteRepositorySnapshot implements IGitMacheteRepositorySnapshot {
private static final NullGitMacheteRepositorySnapshot instance = new NullGitMacheteRepositorySnapshot();
private NullGitMacheteRepositorySnapshot() {}
public static IGitMacheteRepositorySnapshot getInstance() {
return instance;
}
@Override
public Path getMainGitDirectoryPath() {
return Path.of("");
}
@Override
public BranchLayout getBranchLayout() {
return new BranchLayout(List.empty());
}
@Override
public List<IRootManagedBranchSnapshot> getRootBranches() {
return List.empty();
}
@Override
public @Nullable IManagedBranchSnapshot getCurrentBranchIfManaged() {
return null;
}
@Override
public List<IManagedBranchSnapshot> getManagedBranches() {
return List.empty();
}
@Override
public @Nullable IManagedBranchSnapshot getManagedBranchByName(String branchName) {
return null;
}
@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);
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/SyncToRemoteStatus.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/SyncToRemoteStatus.java | package com.virtuslab.gitmachete.backend.api;
public enum SyncToRemoteStatus {
NoRemotes, Untracked, InSyncToRemote, AheadOfRemote, BehindRemote, DivergedFromAndNewerThanRemote, DivergedFromAndOlderThanRemote
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IGitMacheteRepositorySnapshot.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IGitMacheteRepositorySnapshot.java | package com.virtuslab.gitmachete.backend.api;
import java.nio.file.Path;
import io.vavr.collection.List;
import io.vavr.collection.Set;
import lombok.Data;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
/**
* An immutable snapshot of an {@link IGitMacheteRepository} for some specific moment in time.
* Each {@code get...} method is guaranteed to return the same value each time it's called on a given object.
*/
public interface IGitMacheteRepositorySnapshot {
Path getMainGitDirectoryPath();
BranchLayout getBranchLayout();
List<IRootManagedBranchSnapshot> getRootBranches();
@Nullable
IManagedBranchSnapshot getCurrentBranchIfManaged();
/** Branches are ordered as they occur in the machete file */
List<IManagedBranchSnapshot> getManagedBranches();
@Nullable
IManagedBranchSnapshot getManagedBranchByName(String branchName);
Set<String> getDuplicatedBranchNames();
Set<String> getSkippedBranchNames();
@Data
// So that Interning Checker doesn't complain about enum comparison (by `equals` and not by `==`) in Lombok-generated `equals`
@SuppressWarnings("interning:unnecessary.equals")
class OngoingRepositoryOperation {
private final OngoingRepositoryOperationType operationType;
private final @Nullable String baseBranchName;
}
OngoingRepositoryOperation getOngoingRepositoryOperation();
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IRemoteTrackingBranchReference.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IRemoteTrackingBranchReference.java | package com.virtuslab.gitmachete.backend.api;
import io.vavr.NotImplementedError;
public interface IRemoteTrackingBranchReference extends IBranchReference {
@Override
default boolean isLocal() {
return false;
}
@Override
default ILocalBranchReference asLocal() {
throw new NotImplementedError();
}
@Override
default IRemoteTrackingBranchReference asRemote() {
return this;
}
String getRemoteName();
ILocalBranchReference getTrackedLocalBranch();
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/INonRootManagedBranchSnapshot.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/INonRootManagedBranchSnapshot.java | package com.virtuslab.gitmachete.backend.api;
import io.vavr.NotImplementedError;
import io.vavr.collection.List;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface INonRootManagedBranchSnapshot extends IManagedBranchSnapshot {
@Override
default boolean isRoot() {
return false;
}
@Override
default IRootManagedBranchSnapshot asRoot() {
throw new NotImplementedError();
}
@Override
default INonRootManagedBranchSnapshot asNonRoot() {
return this;
}
List<ICommitOfManagedBranch> getUniqueCommits();
List<ICommitOfManagedBranch> getCommitsUntilParent();
IManagedBranchSnapshot getParent();
SyncToParentStatus getSyncToParentStatus();
@Nullable
IForkPointCommitOfManagedBranch getForkPoint();
IGitRebaseParameters getParametersForRebaseOntoParent() throws GitMacheteMissingForkPointException;
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/SyncToParentStatus.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/SyncToParentStatus.java | package com.virtuslab.gitmachete.backend.api;
public enum SyncToParentStatus {
InSync, MergedToParent, InSyncButForkPointOff, OutOfSync
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/OngoingRepositoryOperationType.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/OngoingRepositoryOperationType.java | package com.virtuslab.gitmachete.backend.api;
public enum OngoingRepositoryOperationType {
NO_OPERATION, APPLYING, BISECTING, CHERRY_PICKING, MERGING, REBASING, REVERTING
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IGitRebaseParameters.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IGitRebaseParameters.java | package com.virtuslab.gitmachete.backend.api;
public interface IGitRebaseParameters {
IManagedBranchSnapshot getCurrentBranch();
IManagedBranchSnapshot getNewBaseBranch();
ICommitOfManagedBranch getForkPointCommit();
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/ICommitOfManagedBranch.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/ICommitOfManagedBranch.java | package com.virtuslab.gitmachete.backend.api;
import java.time.Instant;
import org.checkerframework.checker.interning.qual.FindDistinct;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.value.qual.ArrayLen;
/**
* The only criterion for equality of any instances of any class implementing this interface is equality of {@link #getHash}
*/
public interface ICommitOfManagedBranch {
String getShortMessage();
String getFullMessage();
@ArrayLen(40)
String getHash();
@ArrayLen(7)
String getShortHash();
Instant getCommitTime();
@EnsuresNonNullIf(expression = "#2", result = true)
static boolean defaultEquals(@FindDistinct ICommitOfManagedBranch self, @Nullable Object other) {
if (self == other) {
return true;
} else if (!(other instanceof ICommitOfManagedBranch)) {
return false;
} else {
return self.getHash().equals(((ICommitOfManagedBranch) other).getHash());
}
}
static int defaultHashCode(ICommitOfManagedBranch self) {
return self.getHash().hashCode();
}
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IManagedBranchSnapshot.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IManagedBranchSnapshot.java | package com.virtuslab.gitmachete.backend.api;
import io.vavr.collection.List;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.EnsuresQualifierIf;
import org.checkerframework.framework.qual.RequiresQualifier;
import com.virtuslab.qual.subtyping.gitmachete.backend.api.ConfirmedNonRoot;
import com.virtuslab.qual.subtyping.gitmachete.backend.api.ConfirmedRoot;
/**
* The only criterion for equality of any instances of any class implementing this interface is reference equality
*/
public interface IManagedBranchSnapshot extends ILocalBranchReference {
@EnsuresQualifierIf(expression = "this", result = true, qualifier = ConfirmedRoot.class)
@EnsuresQualifierIf(expression = "this", result = false, qualifier = ConfirmedNonRoot.class)
boolean isRoot();
@EnsuresQualifierIf(expression = "this", result = true, qualifier = ConfirmedNonRoot.class)
@EnsuresQualifierIf(expression = "this", result = false, qualifier = ConfirmedRoot.class)
default boolean isNonRoot() {
return !isRoot();
}
@RequiresQualifier(expression = "this", qualifier = ConfirmedRoot.class)
IRootManagedBranchSnapshot asRoot();
@RequiresQualifier(expression = "this", qualifier = ConfirmedNonRoot.class)
INonRootManagedBranchSnapshot asNonRoot();
String getName();
String getFullName();
ICommitOfManagedBranch getPointedCommit();
List<? extends INonRootManagedBranchSnapshot> getChildren();
RelationToRemote getRelationToRemote();
@Nullable
IRemoteTrackingBranchReference getRemoteTrackingBranch();
@Nullable
String getCustomAnnotation();
@Nullable
String getStatusHookOutput();
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IBranchReference.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IBranchReference.java | package com.virtuslab.gitmachete.backend.api;
import org.checkerframework.checker.interning.qual.FindDistinct;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.EnsuresQualifierIf;
import org.checkerframework.framework.qual.RequiresQualifier;
import com.virtuslab.qual.subtyping.gitmachete.backend.api.ConfirmedLocal;
import com.virtuslab.qual.subtyping.gitmachete.backend.api.ConfirmedRemote;
/**
* The only criterion for equality of any instances of any class implementing this interface
* is equality of {@link #getFullName()}
*/
public interface IBranchReference {
String getName();
String getFullName();
@EnsuresQualifierIf(expression = "this", result = true, qualifier = ConfirmedLocal.class)
@EnsuresQualifierIf(expression = "this", result = false, qualifier = ConfirmedRemote.class)
boolean isLocal();
@EnsuresQualifierIf(expression = "this", result = true, qualifier = ConfirmedRemote.class)
@EnsuresQualifierIf(expression = "this", result = false, qualifier = ConfirmedLocal.class)
default boolean isRemote() {
return !isLocal();
}
@RequiresQualifier(expression = "this", qualifier = ConfirmedLocal.class)
ILocalBranchReference asLocal();
@RequiresQualifier(expression = "this", qualifier = ConfirmedRemote.class)
IRemoteTrackingBranchReference asRemote();
@EnsuresNonNullIf(expression = "#2", result = true)
static boolean defaultEquals(@FindDistinct IBranchReference self, @Nullable Object other) {
if (self == other) {
return true;
} else if (!(other instanceof IBranchReference)) {
return false;
} else {
return self.getFullName().equals(((IBranchReference) other).getFullName());
}
}
static int defaultHashCode(IBranchReference self) {
return self.getFullName().hashCode();
}
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IGitMacheteRepository.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IGitMacheteRepository.java | package com.virtuslab.gitmachete.backend.api;
import io.vavr.collection.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.branchlayout.api.BranchLayout;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public interface IGitMacheteRepository {
@UIThreadUnsafe
IGitMacheteRepositorySnapshot createSnapshotForLayout(BranchLayout branchLayout) throws GitMacheteException;
@UIThreadUnsafe
@Nullable
ILocalBranchReference inferParentForLocalBranch(
Set<String> eligibleLocalBranchNames,
String localBranchName) throws GitMacheteException;
@UIThreadUnsafe
IGitMacheteRepositorySnapshot discoverLayoutAndCreateSnapshot() throws GitMacheteException;
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/GitMacheteException.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/GitMacheteException.java | package com.virtuslab.gitmachete.backend.api;
import lombok.experimental.StandardException;
@StandardException
@SuppressWarnings("nullness:argument")
public class GitMacheteException extends Exception {
public static GitMacheteException getOrWrap(Throwable e) {
return e instanceof GitMacheteException gme ? gme : new GitMacheteException(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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IForkPointCommitOfManagedBranch.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IForkPointCommitOfManagedBranch.java | package com.virtuslab.gitmachete.backend.api;
import io.vavr.collection.List;
public interface IForkPointCommitOfManagedBranch extends ICommitOfManagedBranch {
List<IBranchReference> getBranchesContainingInReflog();
/**
* @return a subset of {@link #getBranchesContainingInReflog} that skips a reference to each remote tracking branch
* such that a reference to its tracked local branch is also included.
* For instance, if {@code getBranchesContainingInReflog}
* returns {@code [develop, origin/develop, origin/master, fix]},
* then this method will return {@code [develop, origin/master, fix]}.
*/
List<IBranchReference> getUniqueBranchesContainingInReflog();
boolean isOverridden();
}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IRootManagedBranchSnapshot.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/IRootManagedBranchSnapshot.java | package com.virtuslab.gitmachete.backend.api;
import io.vavr.NotImplementedError;
public interface IRootManagedBranchSnapshot extends IManagedBranchSnapshot {
@Override
default boolean isRoot() {
return true;
}
@Override
default IRootManagedBranchSnapshot asRoot() {
return this;
}
@Override
default INonRootManagedBranchSnapshot asNonRoot() {
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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/GitMacheteMissingForkPointException.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/GitMacheteMissingForkPointException.java | package com.virtuslab.gitmachete.backend.api;
import lombok.experimental.StandardException;
@StandardException
@SuppressWarnings("nullness:argument")
public class GitMacheteMissingForkPointException extends GitMacheteException {}
| 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/backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/ILocalBranchReference.java | backend/api/src/main/java/com/virtuslab/gitmachete/backend/api/ILocalBranchReference.java | package com.virtuslab.gitmachete.backend.api;
import io.vavr.NotImplementedError;
public interface ILocalBranchReference extends IBranchReference {
@Override
default boolean isLocal() {
return true;
}
@Override
default ILocalBranchReference asLocal() {
return this;
}
@Override
default IRemoteTrackingBranchReference asRemote() {
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/qual/src/main/java/com/virtuslab/qual/async/BackgroundableQueuedElsewhere.java | qual/src/main/java/com/virtuslab/qual/async/BackgroundableQueuedElsewhere.java | package com.virtuslab.qual.async;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to mark methods that create an instance of {@code com.intellij.openapi.progress.Task.Backgroundable},
* but do <b>not</b> call {@code #queue()}.
* <p>
* Typically, it is a smell that indicates that the programmer forgot to actually schedule the task.
* Such cases are detected by ArchUnit test {@code com.virtuslab.archunit.BackgroundTaskEnqueuingTestSuite}.
* Still, in some rare cases it might happen that a method passes the newly-created backgroundable
* to downstream APIs to actually enqueue.
* Such methods must be marked as {@link BackgroundableQueuedElsewhere} for {@code BackgroundTaskEnqueuingTestSuite} to ignore.
* <p>
* This annotation must have runtime retention to be visible to ArchUnit tests.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface BackgroundableQueuedElsewhere {}
| 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/qual/src/main/java/com/virtuslab/qual/async/DoesNotContinueInBackground.java | qual/src/main/java/com/virtuslab/qual/async/DoesNotContinueInBackground.java | package com.virtuslab.qual.async;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to mark methods that get a free pass on calling {@link ContinuesInBackground} methods,
* despite <b>not</b> being marked as {@link ContinuesInBackground} themselves.
* <p>
* This is only taken into account by ArchUnit test {@code com.virtuslab.archunit.BackgroundTaskEnqueuingTestSuite}
* that enforces the correct usage of {@link ContinuesInBackground} annotation.
* <p>
* This annotation must have runtime retention to be visible to ArchUnit tests.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface DoesNotContinueInBackground {
String reason();
}
| 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/qual/src/main/java/com/virtuslab/qual/async/ContinuesInBackground.java | qual/src/main/java/com/virtuslab/qual/async/ContinuesInBackground.java | package com.virtuslab.qual.async;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to mark methods that schedule a background task.
* It is <b>not</b> enforced during compilation whether the annotation is used correctly.
* Its purpose is to make the programmer aware of the increased risk of race conditions,
* esp. to avoid treating such methods as if they completed in a fully synchronous/blocking manner.
* <p>
* As for now, we use an ArchUnit test {@code com.virtuslab.archunit.BackgroundTaskEnqueuingTestSuite}
* to enforce that:
* <ol>
* <li>methods that call {@code queue()} on classes extending {@code Task.Backgroundable} are marked as {@link ContinuesInBackground}</li>
* <li>methods that call {@code git4idea.branch.GitBrancher#checkout} are marked as {@link ContinuesInBackground}</li>
* <li>methods that call {@link ContinuesInBackground} methods are themselves marked as {@link ContinuesInBackground}</li>
* </ol>
* <p>
* This annotation must have runtime retention to be visible to ArchUnit tests.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ContinuesInBackground {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/package-info.java | qual/src/main/java/com/virtuslab/qual/subtyping/package-info.java | /**
* Java 17 allows for pattern matching in switch expressions & statements
* (https://www.baeldung.com/java-switch-pattern-matching).
* Still, a quick evaluation shows that Subtyping Checker is more convenient.
* Let's consider the example of {@code com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot},
* with its two sub-interfaces {@code IRootManagedBranchSnapshot} and {@code INonRootManagedBranchSnapshot}.
* <p>
* With Subtyping Checker, the following is possible:
* <pre>
* if (branch.isRoot()) {
* ... branch.asRoot() ...
* } else {
* ... branch.asNonRoot() ...
* }
* </pre>
* <p>
* With {@code instanceof}, it would look like:
* <pre>
* if (branch instanceof IRootManagedBranchSnapshot rootBranch) {
* ... rootBranch ...
* } else {
* ... ((INonRootManagedBranchSnapshot) branch) ...
* }
* </pre>
* or alternatively
* <pre>
* if (branch instanceof IRootManagedBranchSnapshot rootBranch) {
* ... rootBranch ...
* } else if (branch instanceof INonRootManagedBranchSnapshot nonRootBranch) {
* ... nonRootBranch ..
* }
* </pre>
* <p>
* Pattern matching in switch (Java 17 with {@code --enable-preview})
* won't work for interfaces that are directly extended by an abstract class
* (and not only by sub-interfaces), as is the case with {@code IManagedBranchSnapshot}.
* The existence of {@code com.virtuslab.gitmachete.backend.impl.BaseManagedBranchSnapshot} would massively mess up the checks
* for sealed interface, which are needed for pattern matching to work properly.
* We can either sacrifice sealedness of {@code IManagedBranchSnapshot}:
* <pre>
* switch (branch) {
* case IRootManagedBranchSnapshot rootBranch -> ...
* case INonRootManagedBranchSnapshot nonRootBranch -> ...
* // WHOOPS compiler sees this match as non-exhaustive
* }
* </pre>
* or include {@code BaseManagedBranchSnapshot} in {@code permits} clause for {@code IManagedBranchSnapshot},
* which would also cause the compiler to report a non-exhaustive {@code switch} error.
* <p>
* All things consider, as of Java 17, Subtyping Checker remains a cleaner choice for exhaustive matching on subtypes
* than whatever mechanism built into the language.
*/
package com.virtuslab.qual.subtyping;
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/backend/api/ConfirmedLocal.java | qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/backend/api/ConfirmedLocal.java | package com.virtuslab.qual.subtyping.gitmachete.backend.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import com.virtuslab.qual.subtyping.internal.SubtypingTop;
/**
* Used to annotate a type of a {@code com.virtuslab.gitmachete.backend.api.IBranchReference} object
* that has been statically proven to be a {@code com.virtuslab.gitmachete.backend.api.ILocalBranchReference}.
* <p>
* See <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker manual</a>.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf(SubtypingTop.class)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface ConfirmedLocal {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/backend/api/ConfirmedRoot.java | qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/backend/api/ConfirmedRoot.java | package com.virtuslab.qual.subtyping.gitmachete.backend.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import com.virtuslab.qual.subtyping.internal.SubtypingTop;
/**
* Used to annotate a type of a {@code com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot} object
* that has been statically proven to be a {@code com.virtuslab.gitmachete.backend.api.IRootManagedBranchSnapshot}.
* <p>
* See <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker manual</a>.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf(SubtypingTop.class)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface ConfirmedRoot {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/backend/api/ConfirmedNonRoot.java | qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/backend/api/ConfirmedNonRoot.java | package com.virtuslab.qual.subtyping.gitmachete.backend.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import com.virtuslab.qual.subtyping.internal.SubtypingTop;
/**
* Used to annotate a type of a {@code com.virtuslab.gitmachete.backend.api.IManagedBranchSnapshot} object
* that has been statically proven to be a {@code com.virtuslab.gitmachete.backend.api.INonRootManagedBranchSnapshot}.
* <p>
* See <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker manual</a>.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf(SubtypingTop.class)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface ConfirmedNonRoot {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/backend/api/ConfirmedRemote.java | qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/backend/api/ConfirmedRemote.java | package com.virtuslab.qual.subtyping.gitmachete.backend.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import com.virtuslab.qual.subtyping.internal.SubtypingTop;
/**
* Used to annotate a type of a {@code com.virtuslab.gitmachete.backend.api.IBranchReference} object
* that has been statically proven to be a {@code com.virtuslab.gitmachete.backend.api.IRemoteBranchReference}.
* <p>
* See <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker manual</a>.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf(SubtypingTop.class)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface ConfirmedRemote {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/frontend/graph/api/elements/ConfirmedGraphEdge.java | qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/frontend/graph/api/elements/ConfirmedGraphEdge.java | package com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.elements;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import com.virtuslab.qual.subtyping.internal.SubtypingTop;
/**
* Used to annotate a type of a {@code com.virtuslab.gitmachete.frontend.graph.api.elements.IGraphElement} object
* that has been statically proven to be a {@code com.virtuslab.gitmachete.frontend.graph.api.elements.GraphEdge}.
* <p>
* See <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker manual</a>.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf(SubtypingTop.class)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface ConfirmedGraphEdge {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/frontend/graph/api/elements/ConfirmedGraphNode.java | qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/frontend/graph/api/elements/ConfirmedGraphNode.java | package com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.elements;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import com.virtuslab.qual.subtyping.internal.SubtypingTop;
/**
* Used to annotate a type of a {@code com.virtuslab.gitmachete.frontend.graph.api.elements.IGraphElement} object
* that has been statically proven to be a {@code com.virtuslab.gitmachete.frontend.graph.api.elements.GraphNode}.
* <p>
* See <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker manual</a>.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf(SubtypingTop.class)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface ConfirmedGraphNode {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/frontend/graph/api/items/ConfirmedBranchItem.java | qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/frontend/graph/api/items/ConfirmedBranchItem.java | package com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.items;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import com.virtuslab.qual.subtyping.internal.SubtypingTop;
/**
* Used to annotate a type of a {@code com.virtuslab.gitmachete.frontend.graph.api.items.IBranchItem} object
* that has been statically proven to be a {@code com.virtuslab.gitmachete.frontend.graph.impl.items.BranchItem}.
* <p>
* See <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker manual</a>.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf(SubtypingTop.class)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface ConfirmedBranchItem {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/frontend/graph/api/items/ConfirmedCommitItem.java | qual/src/main/java/com/virtuslab/qual/subtyping/gitmachete/frontend/graph/api/items/ConfirmedCommitItem.java | package com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.items;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import com.virtuslab.qual.subtyping.internal.SubtypingTop;
/**
* Used to annotate a type of a {@code com.virtuslab.gitmachete.frontend.graph.api.items.IBranchItem} object
* that has been statically proven to be a {@code com.virtuslab.gitmachete.frontend.graph.impl.items.CommitItem}.
* <p>
* See <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker manual</a>.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf(SubtypingTop.class)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface ConfirmedCommitItem {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/internal/package-info.java | qual/src/main/java/com/virtuslab/qual/subtyping/internal/package-info.java | /**
* Module private. Do not use outside {@link com.virtuslab.qual.subtyping}.
*/
package com.virtuslab.qual.subtyping.internal;
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/internal/SubtypingBottom.java | qual/src/main/java/com/virtuslab/qual/subtyping/internal/SubtypingBottom.java | package com.virtuslab.qual.subtyping.internal;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.SubtypeOf;
import org.checkerframework.framework.qual.TargetLocations;
import org.checkerframework.framework.qual.TypeUseLocation;
import com.virtuslab.qual.subtyping.gitmachete.backend.api.ConfirmedLocal;
import com.virtuslab.qual.subtyping.gitmachete.backend.api.ConfirmedNonRoot;
import com.virtuslab.qual.subtyping.gitmachete.backend.api.ConfirmedRemote;
import com.virtuslab.qual.subtyping.gitmachete.backend.api.ConfirmedRoot;
import com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.elements.ConfirmedGraphEdge;
import com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.elements.ConfirmedGraphNode;
import com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.items.ConfirmedBranchItem;
import com.virtuslab.qual.subtyping.gitmachete.frontend.graph.api.items.ConfirmedCommitItem;
/**
* There needs to be single subtyping hierarchy with single bottom and top annotation.
* We could theoretically create a separate hierarchy with a dedicated top and bottom type
* for each pair of annotations from {@link com.virtuslab.qual.subtyping}.* packages,
* but then <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker</a>
* would raise an error about multiple top/bottom types.
*/
@Retention(RetentionPolicy.CLASS)
@SubtypeOf({
// Despite having a unified type hierarchy, we're actually doing 4 completely independent checks here.
ConfirmedLocal.class,
ConfirmedRemote.class,
ConfirmedRoot.class,
ConfirmedNonRoot.class,
ConfirmedGraphNode.class,
ConfirmedGraphEdge.class,
ConfirmedBranchItem.class,
ConfirmedCommitItem.class,
})
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
@TargetLocations({TypeUseLocation.EXPLICIT_LOWER_BOUND, TypeUseLocation.EXPLICIT_UPPER_BOUND})
public @interface SubtypingBottom {}
| 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/qual/src/main/java/com/virtuslab/qual/subtyping/internal/SubtypingTop.java | qual/src/main/java/com/virtuslab/qual/subtyping/internal/SubtypingTop.java | package com.virtuslab.qual.subtyping.internal;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.framework.qual.DefaultQualifierInHierarchy;
import org.checkerframework.framework.qual.SubtypeOf;
/**
* There needs to be single subtyping hierarchy with single bottom and top annotation.
* We could theoretically create a separate hierarchy with a dedicated top and bottom type
* for each pair of annotations from {@link com.virtuslab.qual.subtyping}.* packages,
* but then <a href="https://checkerframework.org/manual/#subtyping-checker">Subtyping Checker</a>
* would raise an error about multiple top/bottom types.
*/
@DefaultQualifierInHierarchy
@Retention(RetentionPolicy.CLASS)
@SubtypeOf({})
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface SubtypingTop {}
| 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/qual/src/main/java/com/virtuslab/qual/guieffect/IgnoreUIThreadUnsafeCalls.java | qual/src/main/java/com/virtuslab/qual/guieffect/IgnoreUIThreadUnsafeCalls.java | package com.virtuslab.qual.guieffect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to mark methods that get a free pass on calling {@link UIThreadUnsafe} methods,
* despite <b>not</b> being marked as {@link UIThreadUnsafe} themselves.
* <p>
* This is only taken into account by ArchUnit test {@code com.virtuslab.archunit.UIThreadUnsafeMethodInvocationsTestSuite}
* that enforces the correct usage of {@link UIThreadUnsafe} annotation.
* <p>
* Needs to be used sparingly, as this basically allows for a method to call potentially heavyweight operations on UI thread.
* And that, in turn, might lead to UI freeze.
* <p>
* This annotation must have runtime retention to be visible to ArchUnit tests.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface IgnoreUIThreadUnsafeCalls {
/**
* {@code value} must include full names (in the format as returned by
* {@code com.tngtech.archunit.core.domain.AccessTarget#getFullName()})
* of UI-thread-unsafe methods that can legally be called from the annotated method.
*/
String[] value();
}
| 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/qual/src/main/java/com/virtuslab/qual/guieffect/UIThreadUnsafe.java | qual/src/main/java/com/virtuslab/qual/guieffect/UIThreadUnsafe.java | package com.virtuslab.qual.guieffect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.checkerframework.checker.guieffect.qual.UIEffect;
/**
* Used to mark methods that should NOT be executed on UI thread to avoid a UI freeze.
* In case of IntelliJ Platform, the UI thread is Swing's Event Dispatch Thread aka EDT.
* These include methods that are heavyweight or blocking. Typically, this means accessing disk and/or network.
* <p>
* It is <b>not</b> enforced during compilation whether the annotation is used correctly.
* TODO (typetools/checker-framework#3253): replace with proper {@code @Heavyweight} annotation.
* As for now, we use an ArchUnit test {@code com.virtuslab.archunit.UIThreadUnsafeMethodInvocationsTestSuite}
* to enforce that:
* <ol>
* <li>methods that call certain known heavyweight methods (like the ones from {@code java.nio}) are marked as {@link UIThreadUnsafe}</li>
* <li>methods that call {@link UIThreadUnsafe} methods are themselves marked as {@link UIThreadUnsafe}</li>
* <li>no methods are marked as both {@link UIThreadUnsafe} and {@link UIEffect}</li>
* </ol>
* <p>
* This annotation must have runtime retention to be visible to ArchUnit tests.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface UIThreadUnsafe {}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreReflogEntry.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreReflogEntry.java | package com.virtuslab.gitcore.api;
import java.time.Instant;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.dataflow.qual.Pure;
public interface IGitCoreReflogEntry {
@Pure
String getComment();
@Pure
Instant getTimestamp();
@Pure
@Nullable
IGitCoreCommitHash getOldCommitHash();
@Pure
IGitCoreCommitHash getNewCommitHash();
/**
* @return a {@link IGitCoreCheckoutEntry} if this reflog entry corresponds to a checkout;
* otherwise, null
*/
@Nullable
IGitCoreCheckoutEntry parseCheckout();
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreTreeHash.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreTreeHash.java | package com.virtuslab.gitcore.api;
public interface IGitCoreTreeHash extends IGitCoreObjectHash {}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreCommit.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreCommit.java | package com.virtuslab.gitcore.api;
import java.time.Instant;
import org.checkerframework.checker.interning.qual.FindDistinct;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* The only criterion for equality of any instances of any class implementing this interface is equality of {@link #getHash}
*/
public interface IGitCoreCommit {
String getShortMessage();
String getFullMessage();
Instant getCommitTime();
IGitCoreCommitHash getHash();
IGitCoreTreeHash getTreeHash();
@EnsuresNonNullIf(expression = "#2", result = true)
static boolean defaultEquals(@FindDistinct IGitCoreCommit self, @Nullable Object other) {
if (self == other) {
return true;
} else if (!(other instanceof IGitCoreCommit)) {
return false;
} else {
return self.getHash().equals(((IGitCoreCommit) other).getHash());
}
}
static int defaultHashCode(IGitCoreCommit self) {
return self.getHash().hashCode();
}
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreException.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreException.java | package com.virtuslab.gitcore.api;
import lombok.experimental.StandardException;
@StandardException
@SuppressWarnings("nullness:argument")
public class GitCoreException extends Exception {
public static GitCoreException getOrWrap(Throwable e) {
return e instanceof GitCoreException ? (GitCoreException) e : new GitCoreException(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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreObjectHash.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreObjectHash.java | package com.virtuslab.gitcore.api;
import org.checkerframework.checker.interning.qual.FindDistinct;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.value.qual.ArrayLen;
/**
* The only criterion for equality of any instances of any class implementing this interface is equality of
* {@link #getHashString}
*/
public interface IGitCoreObjectHash {
@ArrayLen(40)
String getHashString();
/**
* @return hash string abbreviated to the first 7 characters, without a guarantee on being unique within the repository
*/
@SuppressWarnings({"index:argument", "value:return"})
@ArrayLen(7)
default String getShortHashString() {
return getHashString().substring(0, 7);
}
@EnsuresNonNullIf(expression = "#2", result = true)
static boolean defaultEquals(@FindDistinct IGitCoreObjectHash self, @Nullable Object other) {
if (self == other) {
return true;
} else if (!(other instanceof IGitCoreObjectHash)) {
return false;
} else {
return self.getHashString().equals(((IGitCoreObjectHash) other).getHashString());
}
}
static int defaultHashCode(IGitCoreObjectHash self) {
return self.getHashString().hashCode();
}
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreCheckoutEntry.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreCheckoutEntry.java | package com.virtuslab.gitcore.api;
public interface IGitCoreCheckoutEntry {
String getFromBranchName();
String getToBranchName();
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreHeadSnapshot.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreHeadSnapshot.java | package com.virtuslab.gitcore.api;
import io.vavr.collection.List;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An immutable snapshot of git repository's HEAD for some specific moment in time.
* Each {@code get...} method is guaranteed to return the same value each time it's called on a given object.
*/
public interface IGitCoreHeadSnapshot {
/**
* @return a branch pointed by HEAD, or null in case of detached HEAD
*/
@Nullable
IGitCoreLocalBranchSnapshot getTargetBranch();
List<IGitCoreReflogEntry> getReflogFromMostRecent();
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreBranchSnapshot.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreBranchSnapshot.java | package com.virtuslab.gitcore.api;
import io.vavr.collection.List;
import lombok.val;
import org.checkerframework.checker.interning.qual.FindDistinct;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An immutable snapshot of a git branch for some specific moment in time.
* Each {@code get...} method is guaranteed to return the same value each time it's called on a given object.
*
* The only criterion for equality of any instances of any class implementing this interface is equality of
* {@link #getFullName} and {@link #getPointedCommit}
*/
public interface IGitCoreBranchSnapshot {
boolean isLocal();
/**
* @return {@code X} part of {@code refs/heads/X} or {@code [remote-name]/X} part of {@code refs/remotes/[remote-name]/X}
*/
String getName();
/**
* @return {@code refs/heads/X} or {@code refs/remotes/[remote-name]/X}
*/
String getFullName();
IGitCoreCommit getPointedCommit();
List<IGitCoreReflogEntry> getReflogFromMostRecent();
@EnsuresNonNullIf(expression = "#2", result = true)
static boolean defaultEquals(@FindDistinct IGitCoreBranchSnapshot self, @Nullable Object other) {
if (self == other) {
return true;
} else if (!(other instanceof IGitCoreBranchSnapshot)) {
return false;
} else {
val o = (IGitCoreBranchSnapshot) other;
return self.getFullName().equals(o.getFullName())
&& self.getPointedCommit().equals(o.getPointedCommit());
}
}
static int defaultHashCode(IGitCoreBranchSnapshot self) {
return self.getFullName().hashCode() * 37 + self.getPointedCommit().hashCode();
}
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreRepositoryState.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreRepositoryState.java | package com.virtuslab.gitcore.api;
public enum GitCoreRepositoryState {
NO_OPERATION, APPLYING, BISECTING, CHERRY_PICKING, MERGING, REBASING, REVERTING
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreCannotAccessGitDirectoryException.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreCannotAccessGitDirectoryException.java | package com.virtuslab.gitcore.api;
import lombok.experimental.StandardException;
@StandardException
@SuppressWarnings("nullness:argument")
public class GitCoreCannotAccessGitDirectoryException extends GitCoreException {}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreNoSuchRevisionException.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreNoSuchRevisionException.java | package com.virtuslab.gitcore.api;
import lombok.experimental.StandardException;
@StandardException
@SuppressWarnings("nullness:argument")
public class GitCoreNoSuchRevisionException extends GitCoreException {}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreLocalBranchSnapshot.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreLocalBranchSnapshot.java | package com.virtuslab.gitcore.api;
import org.checkerframework.checker.nullness.qual.Nullable;
public interface IGitCoreLocalBranchSnapshot extends IGitCoreBranchSnapshot {
@Override
default boolean isLocal() {
return true;
}
@Nullable
IGitCoreRemoteBranchSnapshot getRemoteTrackingBranch();
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreRepositoryFactory.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreRepositoryFactory.java | package com.virtuslab.gitcore.api;
import java.nio.file.Path;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public interface IGitCoreRepositoryFactory {
@UIThreadUnsafe
IGitCoreRepository create(Path rootDirectoryPath, Path mainGitDirectoryPath, Path worktreeGitDirectoryPath)
throws GitCoreException;
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreRelativeCommitCount.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/GitCoreRelativeCommitCount.java | package com.virtuslab.gitcore.api;
import lombok.Data;
import lombok.ToString;
@Data(staticConstructor = "of")
@ToString
public class GitCoreRelativeCommitCount {
private final int ahead;
private final int behind;
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreCommitHash.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreCommitHash.java | package com.virtuslab.gitcore.api;
public interface IGitCoreCommitHash extends IGitCoreObjectHash {}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreRepository.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreRepository.java | package com.virtuslab.gitcore.api;
import java.nio.file.Path;
import io.vavr.collection.List;
import io.vavr.collection.Stream;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public interface IGitCoreRepository {
Path getRootDirectoryPath();
Path getMainGitDirectoryPath();
Path getWorktreeGitDirectoryPath();
@UIThreadUnsafe
@Nullable
String deriveConfigValue(String section, String subsection, String name);
@UIThreadUnsafe
@Nullable
String deriveConfigValue(String section, String name);
@UIThreadUnsafe
@Nullable
IGitCoreCommit parseRevision(String revision) throws GitCoreException;
/**
* @return snapshots of all local branches in the repository, sorted by name
* @throws GitCoreException when reading git repository data fails
*/
@UIThreadUnsafe
List<IGitCoreLocalBranchSnapshot> deriveAllLocalBranches() throws GitCoreException;
@UIThreadUnsafe
IGitCoreHeadSnapshot deriveHead() throws GitCoreException;
@UIThreadUnsafe
@Nullable
GitCoreRelativeCommitCount deriveRelativeCommitCount(
IGitCoreCommit fromPerspectiveOf,
IGitCoreCommit asComparedTo) throws GitCoreException;
@UIThreadUnsafe
List<String> deriveAllRemoteNames();
@UIThreadUnsafe
@Nullable
String deriveRebasedBranch() throws GitCoreException;
@UIThreadUnsafe
@Nullable
String deriveBisectedBranch() throws GitCoreException;
@UIThreadUnsafe
boolean isAncestor(IGitCoreCommit presumedAncestor, IGitCoreCommit presumedDescendant) throws GitCoreException;
@UIThreadUnsafe
boolean isAncestorOrEqual(IGitCoreCommit presumedAncestor, IGitCoreCommit presumedDescendant) throws GitCoreException;
/** <i>Any</i> merge base, as in, in the rare case of criss-cross histories there might be <b>multiple merge bases</b>.
* Still, Git Machete isn't well suited to handling such cases, as it generally endorses and deals with linear histories,
* which use merge commits rarely, and hence are very unlikely to introduce criss-cross histories.
*/
@UIThreadUnsafe
@Nullable
IGitCoreCommit deriveAnyMergeBase(IGitCoreCommit commit1, IGitCoreCommit commit2) throws GitCoreException;
@UIThreadUnsafe
Stream<IGitCoreCommit> ancestorsOf(IGitCoreCommit commitInclusive, int maxCommits) throws GitCoreException;
@UIThreadUnsafe
List<IGitCoreCommit> deriveCommitRange(IGitCoreCommit fromInclusive, IGitCoreCommit untilExclusive) throws GitCoreException;
@UIThreadUnsafe
GitCoreRepositoryState deriveRepositoryState();
}
| 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/gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreRemoteBranchSnapshot.java | gitCore/api/src/main/java/com/virtuslab/gitcore/api/IGitCoreRemoteBranchSnapshot.java | package com.virtuslab.gitcore.api;
public interface IGitCoreRemoteBranchSnapshot extends IGitCoreBranchSnapshot {
@Override
default boolean isLocal() {
return false;
}
String getRemoteName();
}
| 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/gitCore/jGit/src/test/java/com/virtuslab/gitcore/impl/jgit/GitCoreRepositoryIntegrationTest.java | gitCore/jGit/src/test/java/com/virtuslab/gitcore/impl/jgit/GitCoreRepositoryIntegrationTest.java | package com.virtuslab.gitcore.impl.jgit;
import static com.virtuslab.gitmachete.testcommon.SetupScripts.SETUP_WITH_SINGLE_REMOTE;
import static com.virtuslab.gitmachete.testcommon.TestFileUtils.cleanUpDir;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import lombok.SneakyThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.simplify4u.slf4jmock.LoggerMock;
import org.slf4j.Logger;
import com.virtuslab.gitmachete.testcommon.TestGitRepository;
public class GitCoreRepositoryIntegrationTest {
private TestGitRepository repo;
private GitCoreRepository gitCoreRepository;
@BeforeEach
@SneakyThrows
public void setUp() {
repo = new TestGitRepository(SETUP_WITH_SINGLE_REMOTE);
gitCoreRepository = new GitCoreRepository(repo.rootDirectoryPath, repo.mainGitDirectoryPath, repo.worktreeGitDirectoryPath);
}
// See https://github.com/VirtusLab/git-machete-intellij-plugin/issues/1029 for the origin of this test
@Test
@SneakyThrows
public void shouldContainExceptionsInsideOptionReturningMethods() {
// Let's check against a non-existent commit.
// No exception should be thrown, just a null returned.
assertNull(gitCoreRepository.parseRevision("0".repeat(40)));
// Deliberately done in the test and not in an @AfterEach method, so that the directory is retained in case of test failure.
cleanUpDir(repo.parentDirectoryPath);
}
// See https://github.com/VirtusLab/git-machete-intellij-plugin/issues/1298 for the origin of this test
@Test
public void shouldNeverLeadToLogErrorCalledWithThrowable() {
assertTrue(gitCoreRepository.isBranchPresent("refs/heads/develop"));
Logger logger = mock(Logger.class);
LoggerMock.setMock(org.eclipse.jgit.internal.storage.file.FileSnapshot.class, logger);
assertFalse(gitCoreRepository.isBranchPresent("refs/heads/develop/something-else"));
// In test setup, a call to `LOG.error(String, Throwable)` doesn't crash the test
// (and we aren't able to simply catch an exception to detect whether such a call took place).
// In fact, with slf4j-simple (rather than slf4j-mock) on classpath, we'll just see stack trace printed out
// (unless stderr is suppressed, which is the default when running tests under Gradle).
// In IntelliJ, however, the situation is different, as IntelliJ provides an SLF4J implementation
// which opens an error notification for each `LOG.error(String, Throwable)` (but not `LOG.error(String)`) call.
// In this particular case, we want to avoid an `LOG.error(String, Throwable)` call in FileSnapshot c'tor
// ending up in a user-visible, confusing error notification.
// See the issue and PR #1304 for more details.
verify(logger, never()).error(anyString(), any(Throwable.class));
// Deliberately done in the test and not in an @AfterEach method, so that the directory is retained in case of test failure.
cleanUpDir(repo.parentDirectoryPath);
}
@Test
@SneakyThrows
public void shouldCorrectlyHandleSyntacticallyInvalidGitRefs() {
assertFalse(gitCoreRepository.isBranchPresent("refs/heads/./foo"));
assertFalse(gitCoreRepository.isBranchPresent("refs/heads/."));
assertNull(gitCoreRepository.parseRevision("refs/remotes/./foo"));
assertNull(gitCoreRepository.parseRevision("refs/remotes/."));
// Deliberately done in the test and not in an @AfterEach method, so that the directory is retained in case of test failure.
cleanUpDir(repo.parentDirectoryPath);
}
}
| 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/gitCore/jGit/src/test/java/com/virtuslab/gitcore/impl/jgit/GitCoreCommitUnitTest.java | gitCore/jGit/src/test/java/com/virtuslab/gitcore/impl/jgit/GitCoreCommitUnitTest.java | package com.virtuslab.gitcore.impl.jgit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.charset.StandardCharsets;
import lombok.val;
import org.eclipse.jgit.revwalk.RevCommit;
import org.junit.jupiter.api.Test;
public class GitCoreCommitUnitTest {
private static final String rawCommitData = """
tree b8518260a35f740dbaa8161feda53017ab8c8be4
parent e3be034fdef163e288f8219664f0df447bfe0ec3
author foo <foo@example.com> 1664994622 +0200
author foo <foo@example.com> 1664994622 +0200
First line of subject
- another line of subject
- moar lines of subject
First line of description
More lines of description
""";
@Test
public void shouldOnlyIncludeFirstLineOfSubjectInShortMessage() {
val revCommit = RevCommit.parse(rawCommitData.getBytes(StandardCharsets.UTF_8));
val commit = new GitCoreCommit(revCommit);
assertEquals("First line of subject", commit.getShortMessage());
}
}
| 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreCheckoutEntry.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreCheckoutEntry.java | package com.virtuslab.gitcore.impl.jgit;
import lombok.AccessLevel;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.eclipse.jgit.lib.CheckoutEntry;
import com.virtuslab.gitcore.api.IGitCoreCheckoutEntry;
@Data
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class GitCoreCheckoutEntry implements IGitCoreCheckoutEntry {
private final String fromBranchName;
private final String toBranchName;
static GitCoreCheckoutEntry of(CheckoutEntry checkoutEntry) {
return new GitCoreCheckoutEntry(checkoutEntry.getFromBranch(), checkoutEntry.getToBranch());
}
}
| 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreRepository.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreRepository.java | package com.virtuslab.gitcore.impl.jgit;
import static com.virtuslab.gitcore.impl.jgit.BranchFullNameUtils.getLocalBranchFullName;
import static com.virtuslab.gitcore.impl.jgit.BranchFullNameUtils.getRemoteBranchFullName;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_BRANCH_SECTION;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_MERGE;
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_REMOTE;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import io.vavr.CheckedFunction1;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.collection.Iterator;
import io.vavr.collection.List;
import io.vavr.collection.Stream;
import io.vavr.control.Option;
import io.vavr.control.Try;
import lombok.CustomLog;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.ToString;
import lombok.val;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.aliasing.qual.Unique;
import org.eclipse.jgit.errors.RevisionSyntaxException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.ReflogReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevSort;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.revwalk.RevWalkUtils;
import org.eclipse.jgit.revwalk.filter.RevFilter;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import com.virtuslab.gitcore.api.GitCoreCannotAccessGitDirectoryException;
import com.virtuslab.gitcore.api.GitCoreException;
import com.virtuslab.gitcore.api.GitCoreNoSuchRevisionException;
import com.virtuslab.gitcore.api.GitCoreRelativeCommitCount;
import com.virtuslab.gitcore.api.GitCoreRepositoryState;
import com.virtuslab.gitcore.api.IGitCoreCommit;
import com.virtuslab.gitcore.api.IGitCoreHeadSnapshot;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreReflogEntry;
import com.virtuslab.gitcore.api.IGitCoreRepository;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@CustomLog
@ToString(onlyExplicitlyIncluded = true)
public final class GitCoreRepository implements IGitCoreRepository {
@Getter
@ToString.Include
private final Path rootDirectoryPath;
@Getter
@ToString.Include
private final Path mainGitDirectoryPath;
@Getter
@ToString.Include
private final Path worktreeGitDirectoryPath;
// As of early 2022, JGit still doesn't have a first-class support for multiple worktrees in a single repository.
// See https://bugs.eclipse.org/bugs/show_bug.cgi?id=477475
// As a workaround, let's create two separate JGit Repositories:
// The one for main .git/ directory, used for most purposes, including as the target location for machete file:
private final Repository jgitRepoForMainGitDir;
// The one for per-worktree .git/worktrees/<worktree> directory,
// used for HEAD and checking repository state (rebasing/merging etc.):
private final Repository jgitRepoForWorktreeGitDir;
private static final String ORIGIN = "origin";
// Note that these caches can be static since merge-base and commit range for the given two commits
// will never change thanks to git commit graph immutability.
private static final java.util.Map<Tuple2<IGitCoreCommit, IGitCoreCommit>, @Nullable GitCoreCommitHash> mergeBaseCache = new java.util.HashMap<>();
private static final java.util.Map<Tuple2<IGitCoreCommit, IGitCoreCommit>, List<IGitCoreCommit>> commitRangeCache = new java.util.HashMap<>();
@UIThreadUnsafe
public GitCoreRepository(Path rootDirectoryPath, Path mainGitDirectoryPath, Path worktreeGitDirectoryPath)
throws GitCoreException {
this.rootDirectoryPath = rootDirectoryPath;
this.mainGitDirectoryPath = mainGitDirectoryPath;
this.worktreeGitDirectoryPath = worktreeGitDirectoryPath;
val builderForMainGitDir = new FileRepositoryBuilder();
builderForMainGitDir.setWorkTree(rootDirectoryPath.toFile());
builderForMainGitDir.setGitDir(mainGitDirectoryPath.toFile());
try {
this.jgitRepoForMainGitDir = builderForMainGitDir.build();
} catch (IOException e) {
throw new GitCoreCannotAccessGitDirectoryException("Cannot create a repository object for " +
"rootDirectoryPath=${rootDirectoryPath}, mainGitDirectoryPath=${mainGitDirectoryPath}", e);
}
val builderForWorktreeGitDir = new FileRepositoryBuilder();
builderForWorktreeGitDir.setWorkTree(rootDirectoryPath.toFile());
builderForWorktreeGitDir.setGitDir(worktreeGitDirectoryPath.toFile());
try {
this.jgitRepoForWorktreeGitDir = builderForWorktreeGitDir.build();
} catch (IOException e) {
throw new GitCoreCannotAccessGitDirectoryException("Cannot create a repository object for " +
"rootDirectoryPath=${rootDirectoryPath}, worktreeGitDirectoryPath=${worktreeGitDirectoryPath}", e);
}
LOG.debug(() -> "Created ${this})");
}
@Override
@UIThreadUnsafe
public @Nullable String deriveConfigValue(String section, String subsection, String name) {
return jgitRepoForMainGitDir.getConfig().getString(section, subsection, name);
}
@Override
@UIThreadUnsafe
public @Nullable String deriveConfigValue(String section, String name) {
return jgitRepoForMainGitDir.getConfig().getString(section, null, name);
}
@Override
@UIThreadUnsafe
public @Nullable IGitCoreCommit parseRevision(String revision) throws GitCoreException {
return convertRevisionToGitCoreCommit(revision);
}
@UIThreadUnsafe
@SuppressWarnings("IllegalCatch")
private <T> T withRevWalk(CheckedFunction1<RevWalk, T> fun) throws GitCoreException {
try (RevWalk walk = new RevWalk(jgitRepoForMainGitDir)) {
return fun.apply(walk);
} catch (Throwable e) {
throw new GitCoreException(e);
}
}
@UIThreadUnsafe
@SneakyThrows
private <T> T withRevWalkUnchecked(CheckedFunction1<RevWalk, T> fun) {
try (RevWalk walk = new RevWalk(jgitRepoForMainGitDir)) {
return fun.apply(walk);
}
}
// Visible only for the sake of tests, not a part of the interface
@UIThreadUnsafe
boolean isBranchPresent(String branchFullName) {
// If '/' characters exist in the branch name, then loop-based testing is needed in order to avoid
// possible IDE errors, which could appear in scenarios similar to the one explained below.
// - If a branch 'foo' exists locally (which means that .git/refs/heads/foo file exists in the repository)
// and
// - There is a branch name entry "foo/bar" in the machete file
// Then `org.eclipse.jgit.lib.Repository#resolve` called to check if `foo/bar` branch exists will try to
// find the branch using the following file path:
// .git/refs/heads/foo/bar
// which will end in an IDE error with a "Not a directory" `java.nio.file.FileSystemException`.
// Explanation:
// 1) One of the classes used by `org.eclipse.jgit` to resolve the git branch is
// `org.eclipse.jgit.internal.storage.file.FileSnapshot`.
// 2) `org.eclipse.jgit.internal.storage.file.FileSnapshot.<init>` called to find if .git/refs/heads/foo/bar exists
// will try to resolve this path, which will produce "Not a directory" `java.nio.file.FileSystemException`,
// because file .git/refs/heads/foo (part of the resolved path) is NOT a directory.
// 3) Catching `FileSystemException` will produce a `LOG.error` - `org.slf4j.Logger#error(java.lang.String, java.lang.Throwable)`
// 4) `LOG.error` will generate an IDE error. Note that it would NOT happen if `org.slf4j.Logger#error(java.lang.String)`
// was called instead.
// So, the cause of the loop-based testing below is to avoid such IDE errors.
val segments = List.of(branchFullName.split("/"));
// A loop-based test below checks if there is a branch that has a name equal to a part of the `branchFullName` -
// - without the last segment (last part of the path). If such a branch exists, `isBranchPresent` should return false.
// Reasoning: if branch 'foo' exists, then for sure branch 'foo/bar' does not exist in the same directory.
// Starting with `numOfSegmentsToUse = 3` as 3 is the lowest number of segments that can correspond
// to a branch name (for `refs/heads/<branch_name>`)
for (int numOfSegmentsToUse = 3; numOfSegmentsToUse < segments.size(); numOfSegmentsToUse++) {
val testedPrefix = segments.take(numOfSegmentsToUse).mkString("/");
try {
val objectId = jgitRepoForMainGitDir.resolve(testedPrefix);
if (objectId != null) {
return false;
}
} catch (IOException ignored) {
// See https://github.com/VirtusLab/git-machete-intellij-plugin/issues/1298
} catch (RevisionSyntaxException ignored) {
// See https://github.com/VirtusLab/git-machete-intellij-plugin/issues/1826
}
}
try {
return jgitRepoForMainGitDir.resolve(branchFullName) != null;
} catch (IOException | RevisionSyntaxException e) {
return false;
}
}
@UIThreadUnsafe
private GitCoreCommit convertExistingRevisionToGitCoreCommit(String revision) throws GitCoreException {
return withRevWalk(walk -> new GitCoreCommit(walk.parseCommit(convertExistingRevisionToObjectId(revision))));
}
@UIThreadUnsafe
private GitCoreCommit convertObjectIdToGitCoreCommit(ObjectId objectId) throws GitCoreException {
return withRevWalk(walk -> new GitCoreCommit(walk.parseCommit(objectId)));
}
@UIThreadUnsafe
private @Nullable GitCoreCommit convertRevisionToGitCoreCommit(String revision) throws GitCoreException {
val objectId = convertRevisionToObjectId(revision);
return objectId != null
? Try.of(() -> withRevWalkUnchecked(walk -> new GitCoreCommit(walk.parseCommit(objectId)))).getOrNull()
: null;
}
@UIThreadUnsafe
private ObjectId convertExistingRevisionToObjectId(String revision) throws GitCoreException {
val objectId = convertRevisionToObjectId(revision);
if (objectId == null) {
throw new GitCoreNoSuchRevisionException("Commit '${revision}' does not exist in this repository");
}
return objectId;
}
@UIThreadUnsafe
private @Nullable ObjectId convertRevisionToObjectId(String revision) throws GitCoreException {
try {
return jgitRepoForMainGitDir.resolve(revision);
} catch (IOException e) {
throw new GitCoreException(e);
} catch (RevisionSyntaxException e) {
// See https://github.com/VirtusLab/git-machete-intellij-plugin/issues/1826
LOG.warn("convertRevisionToObjectId failed on invalid revision syntax", e);
return null;
}
}
@UIThreadUnsafe
private ObjectId convertGitCoreCommitToObjectId(IGitCoreCommit commit) throws GitCoreException {
return convertExistingRevisionToObjectId(commit.getHash().getHashString());
}
@UIThreadUnsafe
@Override
public IGitCoreHeadSnapshot deriveHead() throws GitCoreException {
try {
Ref ref = jgitRepoForWorktreeGitDir.getRefDatabase().findRef(Constants.HEAD);
if (ref == null) {
throw new GitCoreException("Error occurred while getting current branch ref");
}
// Unlike branches which are shared between all worktrees, HEAD is defined on per-worktree basis.
val reflog = deriveReflogByRefFullName(Constants.HEAD, jgitRepoForWorktreeGitDir);
String currentBranchName = null;
if (ref.isSymbolic()) {
currentBranchName = Repository.shortenRefName(ref.getTarget().getName());
} else {
Option<Path> headNamePath = Stream.of("rebase-apply", "rebase-merge")
.map(dir -> jgitRepoForWorktreeGitDir.getDirectory().toPath().resolve(dir).resolve("head-name"))
.find(path -> path.toFile().isFile());
if (headNamePath.isDefined()) {
currentBranchName = Stream.ofAll(Files.readAllLines(headNamePath.get()))
.headOption()
.map(Repository::shortenRefName)
.getOrNull();
}
}
IGitCoreLocalBranchSnapshot targetBranch;
if (currentBranchName != null) {
targetBranch = deriveLocalBranchByName(currentBranchName);
} else {
targetBranch = null;
}
return new GitCoreHeadSnapshot(targetBranch, reflog);
} catch (IOException e) {
throw new GitCoreException("Cannot get current branch", e);
}
}
@UIThreadUnsafe
private List<IGitCoreReflogEntry> deriveReflogByRefFullName(String refFullName, Repository repository)
throws GitCoreException {
try {
ReflogReader reflogReader = repository.getReflogReader(refFullName);
if (reflogReader == null) {
throw new GitCoreNoSuchRevisionException("Ref '${refFullName}' does not exist in this repository");
}
return reflogReader
.getReverseEntries()
.stream()
.map(GitCoreReflogEntry::new)
.collect(List.collector());
} catch (IOException e) {
throw new GitCoreException(e);
}
}
@Override
@UIThreadUnsafe
public @Nullable GitCoreRelativeCommitCount deriveRelativeCommitCount(
IGitCoreCommit fromPerspectiveOf,
IGitCoreCommit asComparedTo) throws GitCoreException {
return (GitCoreRelativeCommitCount) withRevWalk(walk -> {
val mergeBaseHash = deriveAnyMergeBaseIfNeeded(fromPerspectiveOf, asComparedTo);
if (mergeBaseHash == null) {
// Nullness checker does not allow this method to return null, let's rely on Option instead
return Option.none();
}
@Unique RevCommit fromPerspectiveOfCommit = walk.parseCommit(convertGitCoreCommitToObjectId(fromPerspectiveOf));
@Unique RevCommit asComparedToCommit = walk.parseCommit(convertGitCoreCommitToObjectId(asComparedTo));
@Unique RevCommit mergeBase = walk.parseCommit(mergeBaseHash.getObjectId());
// Yes, `walk` is leaked here.
// `count()` calls `walk.reset()` at the very beginning but NOT at the end.
// `walk` must NOT be used afterwards (or at least without a prior `reset()` call).
@SuppressWarnings("aliasing:unique.leaked") int aheadCount = RevWalkUtils.count(walk, fromPerspectiveOfCommit, mergeBase);
@SuppressWarnings("aliasing:unique.leaked") int behindCount = RevWalkUtils.count(walk, asComparedToCommit, mergeBase);
return Option.some(GitCoreRelativeCommitCount.of(aheadCount, behindCount));
}).getOrNull();
}
@UIThreadUnsafe
private @Nullable IGitCoreLocalBranchSnapshot deriveLocalBranchByName(String localBranchName) throws GitCoreException {
String localBranchFullName = getLocalBranchFullName(localBranchName);
if (!isBranchPresent(localBranchFullName)) {
return null;
}
val remoteBranch = deriveRemoteBranchForLocalBranch(localBranchName);
return new GitCoreLocalBranchSnapshot(
localBranchName,
convertExistingRevisionToGitCoreCommit(localBranchFullName),
deriveReflogByRefFullName(localBranchFullName, jgitRepoForMainGitDir),
remoteBranch);
}
@UIThreadUnsafe
private @Nullable GitCoreRemoteBranchSnapshot deriveRemoteBranchByName(
String remoteName,
String remoteBranchName) throws GitCoreException {
String remoteBranchFullName = getRemoteBranchFullName(remoteName, remoteBranchName);
if (!isBranchPresent(remoteBranchFullName)) {
return null;
}
val remoteBranch = new GitCoreRemoteBranchSnapshot(
remoteBranchName,
convertExistingRevisionToGitCoreCommit(remoteBranchFullName),
deriveReflogByRefFullName(remoteBranchFullName, jgitRepoForMainGitDir),
remoteName);
return remoteBranch;
}
@Override
@UIThreadUnsafe
public List<IGitCoreLocalBranchSnapshot> deriveAllLocalBranches() throws GitCoreException {
LOG.debug(() -> "Entering: this = ${this}");
LOG.debug("List of local branches:");
List<Try<GitCoreLocalBranchSnapshot>> result = Try
.of(() -> jgitRepoForMainGitDir.getRefDatabase().getRefsByPrefix(Constants.R_HEADS))
.getOrElseThrow(e -> new GitCoreException("Error while getting list of local branches", e))
.stream()
.filter(branch -> !branch.getName().equals(Constants.HEAD))
.map(ref -> Try.of(() -> {
String localBranchFullName = ref.getName();
LOG.debug(() -> "* " + localBranchFullName);
String localBranchName = localBranchFullName.replace(Constants.R_HEADS, /* replacement */ "");
val objectId = ref.getObjectId();
if (objectId == null) {
throw new GitCoreException("Cannot access git object id corresponding to ${localBranchFullName}");
}
val pointedCommit = convertObjectIdToGitCoreCommit(objectId);
val reflog = deriveReflogByRefFullName(localBranchFullName, jgitRepoForMainGitDir);
val remoteBranch = deriveRemoteBranchForLocalBranch(localBranchName);
return new GitCoreLocalBranchSnapshot(localBranchName, pointedCommit, reflog, remoteBranch);
}))
.collect(List.collector());
return List.narrow(Try.sequence(result).getOrElseThrow(GitCoreException::getOrWrap).toList().sortBy(b -> b.getName()));
}
@Override
@UIThreadUnsafe
public List<String> deriveAllRemoteNames() {
return List.ofAll(jgitRepoForMainGitDir.getRemoteNames());
}
@Override
@UIThreadUnsafe
public @Nullable String deriveRebasedBranch() throws GitCoreException {
Option<Path> headNamePath = Stream.of("rebase-apply", "rebase-merge")
.map(dir -> jgitRepoForWorktreeGitDir.getDirectory().toPath().resolve(dir).resolve("head-name"))
.find(path -> path.toFile().isFile());
try {
return headNamePath.isDefined()
? Stream.ofAll(Files.readAllLines(headNamePath.get()))
.headOption()
.map(Repository::shortenRefName).getOrNull()
: null;
} catch (IOException e) {
throw new GitCoreException("Error occurred while getting currently rebased branch name", e);
}
}
@UIThreadUnsafe
@Override
public @Nullable String deriveBisectedBranch() throws GitCoreException {
Path headNamePath = jgitRepoForWorktreeGitDir.getDirectory().toPath().resolve("BISECT_START");
try {
return headNamePath.toFile().isFile()
? Stream.ofAll(Files.readAllLines(headNamePath))
.headOption()
.map(Repository::shortenRefName).getOrNull()
: null;
} catch (IOException e) {
throw new GitCoreException("Error occurred while getting currently bisected branch name", e);
}
}
@UIThreadUnsafe
private @Nullable GitCoreRemoteBranchSnapshot deriveRemoteBranchForLocalBranch(String localBranchName) {
val configuredRemoteBranchForLocalBranch = deriveConfiguredRemoteBranchForLocalBranch(localBranchName);
try {
return configuredRemoteBranchForLocalBranch != null
? configuredRemoteBranchForLocalBranch
: deriveInferredRemoteBranchForLocalBranch(localBranchName);
} catch (GitCoreException ignored) {}
return null;
}
@UIThreadUnsafe
private @Nullable GitCoreRemoteBranchSnapshot deriveConfiguredRemoteBranchForLocalBranch(String localBranchName) {
val remoteName = deriveConfiguredRemoteNameForLocalBranch(localBranchName);
val remoteShortBranchName = remoteName != null ? deriveConfiguredRemoteBranchNameForLocalBranch(localBranchName) : null;
try {
if (remoteShortBranchName != null && remoteName != null) {
return deriveRemoteBranchByName(remoteName, remoteShortBranchName);
}
} catch (GitCoreException ignored) {}
return null;
}
@UIThreadUnsafe
private @Nullable String deriveConfiguredRemoteNameForLocalBranch(String localBranchName) {
return jgitRepoForMainGitDir.getConfig().getString(CONFIG_BRANCH_SECTION, localBranchName, CONFIG_KEY_REMOTE);
}
@UIThreadUnsafe
private @Nullable String deriveConfiguredRemoteBranchNameForLocalBranch(String localBranchName) {
val branchFullName = jgitRepoForMainGitDir.getConfig().getString(CONFIG_BRANCH_SECTION, localBranchName, CONFIG_KEY_MERGE);
return branchFullName != null ? branchFullName.replace(Constants.R_HEADS, /* replacement */ "") : null;
}
@UIThreadUnsafe
private @Nullable GitCoreRemoteBranchSnapshot deriveInferredRemoteBranchForLocalBranch(String localBranchName)
throws GitCoreException {
val remotes = deriveAllRemoteNames();
if (remotes.contains(ORIGIN)) {
val maybeRemoteBranch = deriveRemoteBranchByName(ORIGIN, localBranchName);
if (maybeRemoteBranch != null) {
return maybeRemoteBranch;
}
}
for (String otherRemote : remotes.reject(r -> r.equals(ORIGIN))) {
val maybeRemoteBranch = deriveRemoteBranchByName(otherRemote, localBranchName);
if (maybeRemoteBranch != null) {
return maybeRemoteBranch;
}
}
return null;
}
@UIThreadUnsafe
private @Nullable GitCoreCommitHash deriveAnyMergeBaseInternal(IGitCoreCommit c1, IGitCoreCommit c2) throws GitCoreException {
LOG.debug(() -> "Entering: this = ${this}");
return (GitCoreCommitHash) withRevWalk(walk -> {
walk.setRevFilter(RevFilter.MERGE_BASE);
walk.markStart(walk.parseCommit(convertGitCoreCommitToObjectId(c1)));
walk.markStart(walk.parseCommit(convertGitCoreCommitToObjectId(c2)));
// Note that we're asking for only one merge-base here
// even if there is more than one (in the rare case of criss-cross histories).
// This is still okay from the perspective of is-ancestor checks:
// * if any of c1, c2 is an ancestor of another,
// then there is exactly one merge-base - the ancestor,
// * if neither of c1, c2 is an ancestor of another,
// then none of the (possibly more than one) merge-bases is equal to either of c1 or c2 anyway.
// This might NOT necessarily be OK from the perspective of remote tracking status
// i.e. the number of commits ahead of/behind remote, but in case of criss-cross histories
// it's basically impossible to get these numbers correctly in a unambiguous manner.
@Unique RevCommit mergeBase = walk.next();
LOG.debug(() -> "Detected merge base for ${c1.getHash().getHashString()} " +
"and ${c2.getHash().getHashString()} is " + (mergeBase != null ? mergeBase.getId().getName() : "<none>"));
if (mergeBase != null) {
return Option.some(GitCoreCommitHash.toGitCoreCommitHash(mergeBase.getId()));
} else {
return Option.none();
}
}).getOrNull();
}
@UIThreadUnsafe
private @Nullable GitCoreCommitHash deriveAnyMergeBaseIfNeeded(IGitCoreCommit a, IGitCoreCommit b) throws GitCoreException {
LOG.debug(() -> "Entering: commit1 = ${a.getHash().getHashString()}, commit2 = ${b.getHash().getHashString()}");
val abKey = Tuple.of(a, b);
val baKey = Tuple.of(b, a);
if (mergeBaseCache.containsKey(abKey)) {
LOG.debug(() -> "Merge base for ${a.getHash().getHashString()} and ${b.getHash().getHashString()} found in cache");
return mergeBaseCache.get(abKey);
} else if (mergeBaseCache.containsKey(baKey)) {
LOG.debug(() -> "Merge base for ${b.getHash().getHashString()} and ${a.getHash().getHashString()} found in cache");
return mergeBaseCache.get(baKey);
} else {
val result = deriveAnyMergeBaseInternal(a, b);
mergeBaseCache.put(abKey, result);
return result;
}
}
@Override
@UIThreadUnsafe
public @Nullable IGitCoreCommit deriveAnyMergeBase(IGitCoreCommit commit1, IGitCoreCommit commit2) throws GitCoreException {
if (commit1.equals(commit2)) {
return commit1;
}
val mergeBaseHash = deriveAnyMergeBaseIfNeeded(commit1, commit2);
if (mergeBaseHash == null) {
return null;
}
return convertObjectIdToGitCoreCommit(mergeBaseHash.getObjectId());
}
@Override
@UIThreadUnsafe
public boolean isAncestor(IGitCoreCommit presumedAncestor, IGitCoreCommit presumedDescendant) throws GitCoreException {
if (presumedAncestor.equals(presumedDescendant)) {
LOG.debug("presumedAncestor is equal to presumedDescendant");
return false;
}
return isAncestorOrEqual(presumedAncestor, presumedDescendant);
}
@Override
@UIThreadUnsafe
public boolean isAncestorOrEqual(IGitCoreCommit presumedAncestor, IGitCoreCommit presumedDescendant) throws GitCoreException {
LOG.debug(() -> "Entering: presumedAncestor = ${presumedAncestor.getHash().getHashString()}, " +
"presumedDescendant = ${presumedDescendant.getHash().getHashString()}");
if (presumedAncestor.equals(presumedDescendant)) {
LOG.debug("presumedAncestor is equal to presumedDescendant");
return true;
}
val mergeBaseHash = deriveAnyMergeBaseIfNeeded(presumedAncestor, presumedDescendant);
if (mergeBaseHash == null) {
LOG.debug("Merge base of presumedAncestor and presumedDescendant not found " +
"=> presumedAncestor is not ancestor of presumedDescendant");
return false;
}
boolean isAncestor = mergeBaseHash.equals(presumedAncestor.getHash());
LOG.debug("Merge base of presumedAncestor and presumedDescendant is equal to presumedAncestor " +
"=> presumedAncestor is ancestor of presumedDescendant");
return isAncestor;
}
@UIThreadUnsafe
private List<IGitCoreCommit> deriveCommitRangeInternal(IGitCoreCommit fromInclusive, IGitCoreCommit untilExclusive)
throws GitCoreException {
LOG.debug(() -> "Entering: fromInclusive = '${fromInclusive}', untilExclusive = '${untilExclusive}'");
return withRevWalk(walk -> {
// Note that `RevSort.COMMIT_TIME_DESC` is compatible with git-machete CLI,
// which relies on vanilla `git log` under the hood,
// which by default shows commits in reverse chronological order (https://git-scm.com/docs/git-log#_commit_ordering).
// In this case (unlike with `ancestorsOf`), apparently there is no significant effect on performance.
walk.sort(RevSort.COMMIT_TIME_DESC);
walk.sort(RevSort.BOUNDARY);
walk.markStart(walk.parseCommit(convertGitCoreCommitToObjectId(fromInclusive)));
walk.markUninteresting(walk.parseCommit(convertGitCoreCommitToObjectId(untilExclusive)));
return Iterator.ofAll(walk.iterator())
.takeWhile(revCommit -> !revCommit.getId().getName().equals(untilExclusive.getHash().getHashString()))
.toJavaStream()
.peek(revCommit -> LOG.debug(() -> "* " + revCommit.getId().getName()))
.map(GitCoreCommit::new)
.collect(List.collector());
});
}
@Override
@UIThreadUnsafe
public List<IGitCoreCommit> deriveCommitRange(IGitCoreCommit fromInclusive, IGitCoreCommit untilExclusive)
throws GitCoreException {
val key = Tuple.of(fromInclusive, untilExclusive);
if (commitRangeCache.containsKey(key)) {
return commitRangeCache.get(key);
} else {
val result = deriveCommitRangeInternal(fromInclusive, untilExclusive);
commitRangeCache.put(key, result);
return result;
}
}
@Override
@UIThreadUnsafe
public GitCoreRepositoryState deriveRepositoryState() {
val state = jgitRepoForWorktreeGitDir.getRepositoryState();
return switch (state) {
case CHERRY_PICKING, CHERRY_PICKING_RESOLVED -> GitCoreRepositoryState.CHERRY_PICKING;
case MERGING, MERGING_RESOLVED -> GitCoreRepositoryState.MERGING;
case REBASING, REBASING_INTERACTIVE, REBASING_MERGE, REBASING_REBASING -> GitCoreRepositoryState.REBASING;
case REVERTING, REVERTING_RESOLVED -> GitCoreRepositoryState.REVERTING;
case APPLY -> GitCoreRepositoryState.APPLYING;
case BISECTING -> GitCoreRepositoryState.BISECTING;
case SAFE -> GitCoreRepositoryState.NO_OPERATION;
case BARE -> throw new IllegalStateException("Unexpected value: " + state);
};
}
@Override
@UIThreadUnsafe
public Stream<IGitCoreCommit> ancestorsOf(IGitCoreCommit commitInclusive, int maxCommits) throws GitCoreException {
RevWalk walk = new RevWalk(jgitRepoForMainGitDir);
// Note that `RevSort.COMMIT_TIME_DESC` is both:
// * compatible with git-machete CLI, which relies on vanilla `git log` under the hood,
// which by default shows commits in reverse chronological order (https://git-scm.com/docs/git-log#_commit_ordering),
// * significantly faster than `RevSort.TOPO` on repos with large histories (100,000's of commits),
// due to `org.eclipse.jgit.revwalk.TopoSortGenerator` constructor eagerly loading the entire git log.
walk.sort(RevSort.COMMIT_TIME_DESC);
ObjectId objectId = convertGitCoreCommitToObjectId(commitInclusive);
try {
walk.markStart(walk.parseCommit(objectId));
} catch (IOException e) {
throw new GitCoreException(e);
}
return Stream.ofAll(walk).take(maxCommits).map(GitCoreCommit::new);
}
}
| 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreRepositoryFactory.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreRepositoryFactory.java | package com.virtuslab.gitcore.impl.jgit;
import java.nio.file.Path;
import com.virtuslab.gitcore.api.GitCoreException;
import com.virtuslab.gitcore.api.IGitCoreRepository;
import com.virtuslab.gitcore.api.IGitCoreRepositoryFactory;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
public class GitCoreRepositoryFactory implements IGitCoreRepositoryFactory {
@UIThreadUnsafe
public IGitCoreRepository create(Path rootDirectoryPath, Path mainGitDirectoryPath, Path worktreeGitDirectoryPath)
throws GitCoreException {
return new GitCoreRepository(rootDirectoryPath, mainGitDirectoryPath, worktreeGitDirectoryPath);
}
}
| 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreTreeHash.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreTreeHash.java | package com.virtuslab.gitcore.impl.jgit;
import org.eclipse.jgit.lib.ObjectId;
import com.virtuslab.gitcore.api.IGitCoreTreeHash;
public final class GitCoreTreeHash extends GitCoreObjectHash implements IGitCoreTreeHash {
private GitCoreTreeHash(ObjectId objectId) {
super(objectId);
}
public static IGitCoreTreeHash toGitCoreTreeHash(ObjectId objectId) {
return new GitCoreTreeHash(objectId);
}
@Override
public String toString() {
return "<tree " + getHashString() + ">";
}
}
| 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreRemoteBranchSnapshot.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreRemoteBranchSnapshot.java | package com.virtuslab.gitcore.impl.jgit;
import io.vavr.collection.List;
import lombok.Getter;
import com.virtuslab.gitcore.api.IGitCoreReflogEntry;
import com.virtuslab.gitcore.api.IGitCoreRemoteBranchSnapshot;
public class GitCoreRemoteBranchSnapshot extends BaseGitCoreBranchSnapshot implements IGitCoreRemoteBranchSnapshot {
@Getter
private final String remoteName;
public GitCoreRemoteBranchSnapshot(
String shortName,
GitCoreCommit pointedCommit,
List<IGitCoreReflogEntry> reflog,
String remoteName) {
super(shortName, pointedCommit, reflog);
this.remoteName = remoteName;
}
@Override
public String getName() {
return BranchFullNameUtils.getRemoteBranchName(remoteName, shortName);
}
@Override
public String getFullName() {
return BranchFullNameUtils.getRemoteBranchFullName(remoteName, shortName);
}
@Override
public String getBranchTypeString(boolean capitalized) {
return capitalized ? "Remote" : "remote";
}
}
| 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreReflogEntry.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreReflogEntry.java | package com.virtuslab.gitcore.impl.jgit;
import java.time.Instant;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.interning.qual.UsesObjectEquals;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.eclipse.jgit.lib.ReflogEntry;
import com.virtuslab.gitcore.api.IGitCoreCheckoutEntry;
import com.virtuslab.gitcore.api.IGitCoreCommitHash;
import com.virtuslab.gitcore.api.IGitCoreReflogEntry;
@RequiredArgsConstructor(access = AccessLevel.MODULE)
@ExtensionMethod(GitCoreCommitHash.class)
@ToString(onlyExplicitlyIncluded = true)
@UsesObjectEquals
public class GitCoreReflogEntry implements IGitCoreReflogEntry {
private final ReflogEntry reflogEntry;
@Override
@ToString.Include(name = "comment")
public String getComment() {
return reflogEntry.getComment();
}
@Override
@ToString.Include(name = "timestamp")
public Instant getTimestamp() {
return reflogEntry.getWho().getWhen().toInstant();
}
@Override
@ToString.Include(name = "oldCommitHash")
public @Nullable IGitCoreCommitHash getOldCommitHash() {
return reflogEntry.getOldId().toGitCoreCommitHashOption();
}
@Override
@ToString.Include(name = "newCommitHash")
public IGitCoreCommitHash getNewCommitHash() {
return reflogEntry.getNewId().toGitCoreCommitHash();
}
@Override
public @Nullable IGitCoreCheckoutEntry parseCheckout() {
val parseCheckout = reflogEntry.parseCheckout();
return parseCheckout != null ? GitCoreCheckoutEntry.of(parseCheckout) : 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/BaseGitCoreBranchSnapshot.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/BaseGitCoreBranchSnapshot.java | package com.virtuslab.gitcore.impl.jgit;
import io.vavr.collection.List;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitcore.api.IGitCoreBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreReflogEntry;
@RequiredArgsConstructor
public abstract class BaseGitCoreBranchSnapshot implements IGitCoreBranchSnapshot {
/**
* {@code X} part of {@code refs/heads/X} or {@code refs/heads/[remote-name]/X}
*/
protected final String shortName;
@Getter
private final GitCoreCommit pointedCommit;
@Getter
private final List<IGitCoreReflogEntry> reflogFromMostRecent;
public abstract String getBranchTypeString(boolean capitalized);
@Override
public final boolean equals(@Nullable Object other) {
return IGitCoreBranchSnapshot.defaultEquals(this, other);
}
@Override
public final int hashCode() {
return IGitCoreBranchSnapshot.defaultHashCode(this);
}
}
| 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreHeadSnapshot.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreHeadSnapshot.java | package com.virtuslab.gitcore.impl.jgit;
import io.vavr.collection.List;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.virtuslab.gitcore.api.IGitCoreHeadSnapshot;
import com.virtuslab.gitcore.api.IGitCoreLocalBranchSnapshot;
import com.virtuslab.gitcore.api.IGitCoreReflogEntry;
@RequiredArgsConstructor
@ToString(onlyExplicitlyIncluded = true)
public class GitCoreHeadSnapshot implements IGitCoreHeadSnapshot {
@ToString.Include
private final @Nullable IGitCoreLocalBranchSnapshot targetBranch;
@Getter
private final List<IGitCoreReflogEntry> reflogFromMostRecent;
@Override
public @Nullable IGitCoreLocalBranchSnapshot getTargetBranch() {
return targetBranch;
}
}
| 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/gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreObjectHash.java | gitCore/jGit/src/main/java/com/virtuslab/gitcore/impl/jgit/GitCoreObjectHash.java | package com.virtuslab.gitcore.impl.jgit;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.common.value.qual.ArrayLen;
import org.eclipse.jgit.lib.ObjectId;
import com.virtuslab.gitcore.api.IGitCoreObjectHash;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
public abstract class GitCoreObjectHash implements IGitCoreObjectHash {
@Getter(AccessLevel.PACKAGE)
private final ObjectId objectId;
@Override
public final @ArrayLen(40) String getHashString() {
return objectId.getName();
}
@Override
public abstract String toString();
@Override
public final boolean equals(@Nullable Object other) {
return IGitCoreObjectHash.defaultEquals(this, other);
}
@Override
public final int hashCode() {
return IGitCoreObjectHash.defaultHashCode(this);
}
}
| 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.